bpaf/
complete_shell.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
use std::borrow::Cow;

use crate::{complete_gen::ShowComp, Error, Meta, Parser, State};

struct Shell<'a>(&'a str);

impl std::fmt::Display for Shell<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        use std::fmt::Write;
        f.write_char('\'')?;
        for c in self.0.chars() {
            if c == '\'' {
                f.write_str("'\\''")
            } else {
                f.write_char(c)
            }?
        }
        f.write_char('\'')?;
        Ok(())
    }
}

#[derive(Debug, Clone, Copy)]
/// Shell specific completion
#[non_exhaustive]
pub enum ShellComp {
    /// A file or directory name with an optional file mask.
    ///
    /// For bash filemask should start with `*.` or contain only the
    /// extension
    File {
        /// Optional filemask to use, no spaces, no tabs
        mask: Option<&'static str>,
    },

    /// Similar to `File` but limited to directories only
    /// For bash filemask should start with `*.` or contain only the
    /// extension
    Dir {
        /// Optional filemask to use, no spaces, no tabs
        mask: Option<&'static str>,
    },

    /// You can also specify a raw value to use for each supported shell
    ///
    /// It is possible to fill in values for shells you don't want to support
    /// with empty strings but the code is not going to work for those shells
    Raw {
        /// This raw string will be used for `bash` shell
        /// <https://www.gnu.org/software/bash/manual/html_node/Command-Line-Editing.html>
        bash: &'static str,

        /// This raw string will be used for `zsh` shell
        /// <https://zsh.sourceforge.io/Doc/Release/Completion-System.html>
        zsh: &'static str,

        /// This raw string will be used for `fish` shell
        /// <https://fishshell.com/docs/current/completions.html>
        fish: &'static str,

        /// This raw string will be used for `elvish` shell
        /// <https://elv.sh/ref/edit.html#completion-api>
        elvish: &'static str,
    },

    /// Don't produce anything at all from this parser - can be useful if you want to compose
    /// bpaf completion with shell completion
    Nothing,
}

/// Parser that inserts static shell completion into bpaf's dynamic shell completion
#[cfg(feature = "autocomplete")]
pub struct ParseCompShell<P> {
    pub(crate) inner: P,
    pub(crate) op: crate::complete_shell::ShellComp,
}

#[cfg(feature = "autocomplete")]
impl<P, T> Parser<T> for ParseCompShell<P>
where
    P: Parser<T> + Sized,
{
    fn eval(&self, args: &mut State) -> Result<T, Error> {
        // same as with ParseComp the goal is to replace metavars added by inner parser
        // with a completion that would call a bash script.
        // unlike ParseComp we don't care if inner parser succeeds

        // stash old completions
        let mut comp_items = Vec::new();
        args.swap_comps_with(&mut comp_items);

        let res = self.inner.eval(args);

        // at this point comp_items contains values added by the inner parser
        args.swap_comps_with(&mut comp_items);

        let depth = args.depth();
        if let Some(comp) = args.comp_mut() {
            for ci in comp_items {
                if let Some(is_argument) = ci.is_metavar() {
                    comp.push_shell(self.op, is_argument, depth);
                } else {
                    comp.push_comp(ci);
                }
            }
        }

        res
    }

    fn meta(&self) -> Meta {
        self.inner.meta()
    }
}

pub(crate) fn render_zsh(
    items: &[ShowComp],
    ops: &[ShellComp],
    full_lit: &str,
) -> Result<String, std::fmt::Error> {
    use std::fmt::Write;
    let mut res = String::new();

    if items.is_empty() && ops.is_empty() {
        return Ok(format!("compadd -- {}\n", full_lit));
    }

    for op in ops {
        match op {
            ShellComp::File { mask: None } => writeln!(res, "_files"),
            ShellComp::File { mask: Some(mask) } => writeln!(res, "_files -g {}", Shell(mask)),
            ShellComp::Dir { mask: None } => writeln!(res, "_files -/"),
            ShellComp::Dir { mask: Some(mask) } => writeln!(res, "_files -/ -g {}", Shell(mask)),
            ShellComp::Raw { zsh, .. } => writeln!(res, "{}", zsh),
            ShellComp::Nothing => Ok(()),
        }?;
    }

    if items.len() == 1 {
        if items[0].subst.is_empty() {
            writeln!(res, "compadd -- {}", Shell(items[0].pretty.as_str()))?;
            writeln!(res, "compadd ''")?;
            return Ok(res);
        } else {
            return Ok(format!("compadd -- {}\n", Shell(items[0].subst.as_str())));
        }
    }
    writeln!(res, "local -a descr")?;

    for item in items {
        writeln!(res, "descr=({})", Shell(&item.to_string()))?;
        //        writeln!(res, "args=(\"{}\")", item.subst)?;
        if let Some(group) = &item.extra.group {
            writeln!(
                res,
                "compadd -l -d descr -V {} -X {} -- {}",
                Shell(group),
                Shell(group),
                Shell(&item.subst),
            )?;
        } else {
            // it seems sorting as well as not sorting is done in a group,
            // by default group contains just one element so and `-o nosort`
            // does nothing, while `-V whatever` stops sorting...
            writeln!(
                res,
                "compadd -l -V nosort -d descr -- {}",
                Shell(&item.subst)
            )?;
        }
    }
    Ok(res)
}

pub(crate) fn render_bash(
    items: &[ShowComp],
    ops: &[ShellComp],
    full_lit: &str,
) -> Result<String, std::fmt::Error> {
    // Bash is strange when it comes to completion - rather than taking
    // a glob - _filedir takes an extension which it later to include uppercase
    // version as well and to include "*." in front. For compatibility with
    // zsh and other shells - this code strips "*." from the beginning....
    //
    // Second difference between bash and zsh is that if you are trying to
    // allow for multiple extensions zsh takes a sane "*.(foo|bar|baz)" approach,
    // while bash wants it to be "@(foo|bar|baz)"
    //
    // This doesn't cover all the possible masks, I suspect that the right way of
    // handling this would be ignoring the shell machinery and handling masks on the
    // Rust side... But for now try this
    //
    fn bashmask(i: &str) -> Cow<str> {
        let i = i.strip_prefix("*.").unwrap_or(i);

        if i.starts_with('(') {
            Cow::Owned(format!("@{}", i))
        } else {
            Cow::Borrowed(i)
        }
    }

    use std::fmt::Write;
    let mut res = String::new();

    if items.is_empty() && ops.is_empty() {
        return Ok(format!("COMPREPLY+=({})\n", Shell(full_lit)));
    }

    let init = "local cur prev words cword ; _init_completion || return ;";
    for op in ops {
        match op {
            ShellComp::File { mask: None } => write!(res, "{} _filedir", init),
            ShellComp::File { mask: Some(mask) } => {
                writeln!(res, "{} _filedir {}", init, Shell(&bashmask(mask)))
            }
            ShellComp::Dir { mask: None } => write!(res, "{} _filedir -d", init),
            ShellComp::Dir { mask: Some(mask) } => {
                writeln!(res, "{} _filedir -d {}", init, Shell(&bashmask(mask)))
            }
            ShellComp::Raw { bash, .. } => writeln!(res, "{}", bash),
            ShellComp::Nothing => Ok(()),
        }?;
    }

    if items.len() == 1 {
        if items[0].subst.is_empty() {
            writeln!(res, "COMPREPLY+=( {} '')", Shell(&items[0].pretty))?;
        } else {
            writeln!(res, "COMPREPLY+=( {} )\n", Shell(&items[0].subst))?;
        }

        return Ok(res);
    }
    let mut prev = "";
    for item in items.iter() {
        if let Some(group) = &item.extra.group {
            if prev != group {
                prev = group;
                writeln!(res, "COMPREPLY+=({})", Shell(group))?;
            }
        }
        writeln!(res, "COMPREPLY+=({})", Shell(&item.to_string()))?;
    }

    Ok(res)
}

pub(crate) fn render_test(
    items: &[ShowComp],
    ops: &[ShellComp],
    lit: &str,
) -> Result<String, std::fmt::Error> {
    use std::fmt::Write;

    if items.is_empty() && ops.is_empty() {
        return Ok(format!("{}\n", lit));
    }

    if items.len() == 1 && ops.is_empty() && !items[0].subst.is_empty() {
        return Ok(items[0].subst.clone());
    }

    let mut res = String::new();
    for op in items {
        writeln!(
            res,
            "{}\t{}\t{}\t{}",
            op.subst,
            op.pretty,
            op.extra.group.as_deref().unwrap_or(""),
            op.extra.help.as_deref().unwrap_or("")
        )?;
    }
    writeln!(res)?;
    for op in ops {
        writeln!(res, "{:?}", op)?;
    }

    Ok(res)
}

pub(crate) fn render_fish(
    items: &[ShowComp],
    ops: &[ShellComp],
    full_lit: &str,
    _app: &str,
) -> Result<String, std::fmt::Error> {
    use std::fmt::Write;
    let mut res = String::new();
    if items.is_empty() && ops.is_empty() {
        writeln!(res, "{}", full_lit)?;
    }

    // skip things without substitutions, I think they
    // are headers and such, and fish is a bit
    for item in items.iter().rev().filter(|i| !i.subst.is_empty()) {
        if let Some(help) = item.extra.help.as_deref() {
            writeln!(res, "{}\t{}", item.subst, help)?;
        } else {
            writeln!(res, "{}", item.subst)?;
        }
    }

    Ok(res)
}

pub(crate) fn render_simple(items: &[ShowComp]) -> Result<String, std::fmt::Error> {
    use std::fmt::Write;
    let mut res = String::new();
    if items.len() == 1 {
        writeln!(res, "{}", items[0].subst)?;
    } else {
        for item in items {
            if let Some(descr) = item.extra.help.as_deref() {
                writeln!(
                    res,
                    "{}\t{}",
                    item.subst,
                    descr.split('\n').next().unwrap_or("")
                )
            } else {
                writeln!(res, "{}", item.subst)
            }?;
        }
    }
    Ok(res)
}