clap/completions/
fish.rs
1use std::io::Write;
3
4use crate::app::parser::Parser;
6
7pub struct FishGen<'a, 'b>
8where
9 'a: 'b,
10{
11 p: &'b Parser<'a, 'b>,
12}
13
14impl<'a, 'b> FishGen<'a, 'b> {
15 pub fn new(p: &'b Parser<'a, 'b>) -> Self {
16 FishGen { p }
17 }
18
19 pub fn generate_to<W: Write>(&self, buf: &mut W) {
20 let command = self.p.meta.bin_name.as_ref().unwrap();
21 let mut buffer = String::new();
22 gen_fish_inner(command, self, command, &mut buffer);
23 w!(buf, buffer.as_bytes());
24 }
25}
26
27fn escape_string(string: &str) -> String {
29 string.replace("\\", "\\\\").replace("'", "\\'")
30}
31
32fn gen_fish_inner(root_command: &str, comp_gen: &FishGen, subcommand: &str, buffer: &mut String) {
33 debugln!("FishGen::gen_fish_inner;");
34 let mut basic_template = format!("complete -c {} -n ", root_command);
48 if root_command == subcommand {
49 basic_template.push_str("\"__fish_use_subcommand\"");
50 } else {
51 basic_template.push_str(format!("\"__fish_seen_subcommand_from {}\"", subcommand).as_str());
52 }
53
54 for option in comp_gen.p.opts() {
55 let mut template = basic_template.clone();
56 if let Some(data) = option.s.short {
57 template.push_str(format!(" -s {}", data).as_str());
58 }
59 if let Some(data) = option.s.long {
60 template.push_str(format!(" -l {}", data).as_str());
61 }
62 if let Some(data) = option.b.help {
63 template.push_str(format!(" -d '{}'", escape_string(data)).as_str());
64 }
65 if let Some(ref data) = option.v.possible_vals {
66 template.push_str(format!(" -r -f -a \"{}\"", data.join(" ")).as_str());
67 }
68 buffer.push_str(template.as_str());
69 buffer.push('\n');
70 }
71
72 for flag in comp_gen.p.flags() {
73 let mut template = basic_template.clone();
74 if let Some(data) = flag.s.short {
75 template.push_str(format!(" -s {}", data).as_str());
76 }
77 if let Some(data) = flag.s.long {
78 template.push_str(format!(" -l {}", data).as_str());
79 }
80 if let Some(data) = flag.b.help {
81 template.push_str(format!(" -d '{}'", escape_string(data)).as_str());
82 }
83 buffer.push_str(template.as_str());
84 buffer.push('\n');
85 }
86
87 for subcommand in &comp_gen.p.subcommands {
88 let mut template = basic_template.clone();
89 template.push_str(" -f");
90 template.push_str(format!(" -a \"{}\"", &subcommand.p.meta.name).as_str());
91 if let Some(data) = subcommand.p.meta.about {
92 template.push_str(format!(" -d '{}'", escape_string(data)).as_str())
93 }
94 buffer.push_str(template.as_str());
95 buffer.push('\n');
96 }
97
98 for subcommand in &comp_gen.p.subcommands {
100 let sub_comp_gen = FishGen::new(&subcommand.p);
101 gen_fish_inner(root_command, &sub_comp_gen, &subcommand.to_string(), buffer);
102 }
103}