Skip to main content

usage/spec/
complete.rs

1use crate::kdl::{KdlEntry, KdlNode};
2use serde::{Deserialize, Serialize};
3
4use crate::error::UsageErr;
5use crate::spec::context::ParsingContext;
6use crate::spec::helpers::{NodeHelper, string_entry};
7use crate::spec::is_false;
8
9#[derive(Debug, Default, Clone, Serialize, Deserialize)]
10#[non_exhaustive]
11pub struct SpecComplete {
12    pub name: String,
13    #[serde(skip_serializing_if = "Option::is_none")]
14    pub run: Option<String>,
15    #[serde(skip_serializing_if = "is_false")]
16    pub descriptions: bool,
17    #[serde(skip_serializing_if = "Option::is_none")]
18    pub type_: Option<String>,
19    /// A command whose own shell completion answers for this argument.
20    ///
21    /// Written as a command line (`"terraform"`, `"kubectl --context prod"`). Completing a
22    /// word of the argument asks the user's shell what it would offer after that command
23    /// line followed by the words the argument already holds, so a wrapper passes the
24    /// wrapped tool's completion through unchanged.
25    #[serde(skip_serializing_if = "Option::is_none")]
26    pub delegate: Option<String>,
27}
28
29impl SpecComplete {
30    /// A completer for the arg or flag named `name`.
31    pub fn new(name: impl Into<String>) -> Self {
32        Self {
33            name: name.into(),
34            ..Default::default()
35        }
36    }
37
38    /// Shell command whose output supplies the completions.
39    pub fn run(mut self, run: impl Into<String>) -> Self {
40        self.run = Some(run.into());
41        self
42    }
43
44    /// Command line whose own shell completion answers for this argument.
45    pub fn delegate(mut self, delegate: impl Into<String>) -> Self {
46        self.delegate = Some(delegate.into());
47        self
48    }
49
50    /// Whether the completer emits descriptions alongside values.
51    pub fn descriptions(mut self, descriptions: bool) -> Self {
52        self.descriptions = descriptions;
53        self
54    }
55}
56
57impl SpecComplete {
58    /// A top-level or command-level `complete "<name>" ...` node, which finds the arg or flag
59    /// value it completes by name.
60    pub(crate) fn parse(ctx: &ParsingContext, node: &NodeHelper) -> Result<Self, UsageErr> {
61        node.ensure_arg_len(1..=1)?;
62        let name = node.arg(0)?.ensure_string()?.to_string().to_lowercase();
63        let mut config = Self::parse_props(ctx, node)?;
64        config.name = name;
65        Ok(config)
66    }
67
68    /// A `complete run=...` node written inside the `arg` it completes. It takes no name: the
69    /// enclosing arg is what is being completed, so the caller fills in [`SpecComplete::name`]
70    /// once the arg's own name is settled.
71    pub(crate) fn parse_inline(ctx: &ParsingContext, node: &NodeHelper) -> Result<Self, UsageErr> {
72        if let Some(name) = node.args().next() {
73            bail_parse!(
74                ctx,
75                name.entry.span(),
76                "a complete inside an arg completes that arg, so it takes no name"
77            )
78        }
79        Self::parse_props(ctx, node)
80    }
81
82    fn parse_props(ctx: &ParsingContext, node: &NodeHelper) -> Result<Self, UsageErr> {
83        let mut config = Self::default();
84        for (k, v) in node.props() {
85            match k {
86                "run" | "type" | "delegate"
87                    if config.run.is_some()
88                        || config.type_.is_some()
89                        || config.delegate.is_some() =>
90                {
91                    bail_parse!(
92                        ctx,
93                        v.entry.span(),
94                        "can set only one of run, type or delegate"
95                    )
96                }
97                "run" => config.run = Some(v.ensure_string()?.to_string()),
98                "descriptions" => config.descriptions = v.ensure_bool()?,
99                "type" => config.type_ = Some(v.ensure_string()?.to_string()),
100                "delegate" => {
101                    let delegate = v.ensure_string()?;
102                    // Split here rather than at completion time, so a typo in the quoting is
103                    // reported where the spec is read instead of as a Tab that does nothing.
104                    match crate::shell_words::split(&delegate) {
105                        Ok(words) if !words.is_empty() => {}
106                        Ok(_) => bail_parse!(ctx, v.entry.span(), "delegate names no command"),
107                        Err(err) => {
108                            bail_parse!(
109                                ctx,
110                                v.entry.span(),
111                                "delegate is not a command line: {err}"
112                            )
113                        }
114                    }
115                    config.delegate = Some(delegate)
116                }
117                k => bail_parse!(ctx, v.entry.span(), "unsupported complete key {k}"),
118            }
119        }
120        Ok(config)
121    }
122
123    /// The node written inside an `arg`: the named form's properties without the name, since
124    /// the enclosing arg says what is being completed.
125    pub(crate) fn to_inline_node(&self) -> KdlNode {
126        let mut node = KdlNode::new("complete");
127        self.push_props(&mut node);
128        node
129    }
130
131    fn push_props(&self, node: &mut KdlNode) {
132        if let Some(run) = &self.run {
133            node.push(string_entry(Some("run"), run));
134        }
135        if let Some(type_) = &self.type_ {
136            node.push(string_entry(Some("type"), type_));
137        }
138        if let Some(delegate) = &self.delegate {
139            node.push(string_entry(Some("delegate"), delegate));
140        }
141        if self.descriptions {
142            node.push(KdlEntry::new_prop("descriptions", true));
143        }
144    }
145}
146
147impl From<&SpecComplete> for KdlNode {
148    fn from(complete: &SpecComplete) -> Self {
149        let mut node = KdlNode::new("complete");
150        node.push(string_entry(None, &complete.name));
151        complete.push_props(&mut node);
152        node
153    }
154}
155
156#[cfg(test)]
157mod tests {
158    use crate::Spec;
159
160    #[test]
161    fn delegate_round_trips() {
162        let spec: Spec = r#"
163arg "<layer>"
164arg "<command>" var=#true
165complete "command" delegate="terraform -chdir=infra"
166"#
167        .parse()
168        .unwrap();
169        let complete = &spec.complete["command"];
170        assert_eq!(complete.delegate.as_deref(), Some("terraform -chdir=infra"));
171        assert!(complete.run.is_none() && complete.type_.is_none());
172
173        let printed = spec.to_string();
174        assert!(
175            printed.contains(r#"complete command delegate="terraform -chdir=infra""#),
176            "{printed}"
177        );
178        let reparsed: Spec = printed.parse().unwrap();
179        assert_eq!(
180            reparsed.complete["command"].delegate.as_deref(),
181            Some("terraform -chdir=infra")
182        );
183    }
184
185    #[test]
186    fn delegate_excludes_run_and_type() {
187        for spec in [
188            r#"complete "c" delegate="git" run="ls""#,
189            r#"complete "c" run="ls" delegate="git""#,
190            r#"complete "c" type="file" delegate="git""#,
191            r#"complete "c" delegate="git" type="file""#,
192            r#"complete "c" run="ls" type="file""#,
193        ] {
194            let err = spec.parse::<Spec>().unwrap_err();
195            assert!(
196                format!("{err:?}").contains("can set only one of run, type or delegate"),
197                "{spec}: {err:?}"
198            );
199        }
200    }
201
202    #[test]
203    fn delegate_must_be_a_command_line() {
204        for (spec, expected) in [
205            (r#"complete "c" delegate="""#, "delegate names no command"),
206            (
207                r#"complete "c" delegate="git 'oops""#,
208                "delegate is not a command line",
209            ),
210        ] {
211            let err = spec.parse::<Spec>().unwrap_err();
212            assert!(format!("{err:?}").contains(expected), "{spec}: {err:?}");
213        }
214    }
215}