argenv_resolve/generate/
fish.rs1use super::{asked_words, commands, model, GenerateError, Model, Program};
4use crate::Record;
5
6fn quote(text: &str) -> String {
8 format!("'{}'", text.replace('\\', "\\\\").replace('\'', "\\'"))
9}
10
11pub fn fish(program: &Program<'_>, records: &[Record]) -> Result<String, GenerateError> {
13 let commands = commands(program)?;
14 let Model { flags, positionals } = model(records);
15 let name = program.name;
16
17 let mut out = format!(
18 "# fish completion for {name} (generated by argenv; do not edit by hand)\n# No file names unless an input says so.\ncomplete -c {name} -f\n"
19 );
20
21 for command in &commands {
22 out.push_str(&format!(
23 "complete -c {name} -n '__fish_use_subcommand' -a {} -d {}\n",
24 command.name,
25 quote(&super::one_line(command.summary))
26 ));
27 }
28
29 for flag in &flags {
30 let condition = if flag.scope.is_empty() {
31 String::new()
32 } else {
33 format!(" -n '__fish_seen_subcommand_from {}'", flag.scope.join(" "))
34 };
35 let mut spec = format!("complete -c {name}{condition}");
36 if let Some(short) = &flag.short {
37 spec.push_str(&format!(" -s {short}"));
38 }
39 if let Some(long) = &flag.long {
40 spec.push_str(&format!(" -l {long}"));
41 }
42 if flag.takes_value {
43 if !flag.values.is_empty() {
44 spec.push_str(&format!(" -x -a {}", quote(&flag.values.join(" "))));
45 } else if flag.path {
46 spec.push_str(" -r -F");
47 } else {
48 spec.push_str(" -x");
49 }
50 }
51 if !flag.summary.is_empty() {
52 spec.push_str(&format!(" -d {}", quote(&flag.summary)));
53 }
54 out.push_str(&spec);
55 out.push('\n');
56 if flag.negatable {
57 if let Some(long) = &flag.long {
58 out.push_str(&format!("complete -c {name}{condition} -l no-{long}"));
59 if !flag.summary.is_empty() {
60 out.push_str(&format!(
61 " -d {}",
62 quote(&format!("Turn off: {}", flag.summary))
63 ));
64 }
65 out.push('\n');
66 }
67 }
68 }
69
70 for positional in &positionals {
71 for command in commands.iter().filter(|c| positional.available_for(c.name)) {
72 let asked = asked_words(program, command.name, positional.index);
73 if asked.is_none() && positional.values.is_empty() && !positional.path {
74 continue;
75 }
76 let mut spec = format!(
77 "complete -c {name} -n '__fish_seen_subcommand_from {}'",
78 command.name
79 );
80 if let Some(words) = &asked {
81 spec.push_str(&format!(
83 " -a {}",
84 quote(&format!("({} 2>/dev/null)", words.join(" ")))
85 ));
86 } else if positional.values.is_empty() {
87 spec.push_str(" -F");
88 } else {
89 spec.push_str(&format!(" -a {}", quote(&positional.values.join(" "))));
90 }
91 if !positional.summary.is_empty() {
92 spec.push_str(&format!(" -d {}", quote(&positional.summary)));
93 }
94 out.push_str(&spec);
95 out.push('\n');
96 }
97 }
98 Ok(out)
99}