1use comfy_table::{Table, presets::UTF8_FULL};
2use core_types::{EventKind, SecurityLevel, TrustProfileName};
3use owo_colors::OwoColorize;
4
5use crate::ipc::{connect, rpc};
6
7pub(crate) async fn cmd_snippet_list(profile: &str) -> anyhow::Result<()> {
8 let client = connect().await?;
9 let profile = TrustProfileName::try_from(profile).map_err(|e| anyhow::anyhow!("{e}"))?;
10
11 match rpc(
12 &client,
13 EventKind::SnippetList { profile },
14 SecurityLevel::Internal,
15 )
16 .await?
17 {
18 EventKind::SnippetListResponse { snippets } => {
19 if snippets.is_empty() {
20 println!("{}", "No snippets configured.".dimmed());
21 } else {
22 let mut table = Table::new();
23 table.load_preset(UTF8_FULL);
24 table.set_header(vec!["Trigger", "Template Preview"]);
25
26 for s in &snippets {
27 table.add_row(vec![&s.trigger, &s.template_preview]);
28 }
29
30 println!("{table}");
31 }
32 }
33 other => anyhow::bail!("unexpected response: {other:?}"),
34 }
35
36 Ok(())
37}
38
39pub(crate) async fn cmd_snippet_expand(profile: &str, trigger: &str) -> anyhow::Result<()> {
40 let client = connect().await?;
41 let profile = TrustProfileName::try_from(profile).map_err(|e| anyhow::anyhow!("{e}"))?;
42
43 let event = EventKind::SnippetExpand {
44 profile,
45 trigger: trigger.to_owned(),
46 };
47
48 match rpc(&client, event, SecurityLevel::Internal).await? {
49 EventKind::SnippetExpandResponse {
50 expanded: Some(text),
51 } => {
52 println!("{text}");
53 }
54 EventKind::SnippetExpandResponse { expanded: None } => {
55 anyhow::bail!("snippet trigger '{trigger}' not found");
56 }
57 other => anyhow::bail!("unexpected response: {other:?}"),
58 }
59
60 Ok(())
61}
62
63pub(crate) async fn cmd_snippet_add(
64 profile: &str,
65 trigger: &str,
66 template: &str,
67) -> anyhow::Result<()> {
68 let client = connect().await?;
69 let profile = TrustProfileName::try_from(profile).map_err(|e| anyhow::anyhow!("{e}"))?;
70
71 let event = EventKind::SnippetAdd {
72 profile,
73 trigger: trigger.to_owned(),
74 template: template.to_owned(),
75 };
76
77 match rpc(&client, event, SecurityLevel::Internal).await? {
78 EventKind::SnippetAddResponse { success: true } => {
79 println!("Snippet '{}' added.", trigger.green());
80 }
81 EventKind::SnippetAddResponse { success: false } => {
82 anyhow::bail!("failed to add snippet");
83 }
84 other => anyhow::bail!("unexpected response: {other:?}"),
85 }
86
87 Ok(())
88}