use super::{commands, model, GenerateError, Model, Program};
use crate::Record;
fn quote(text: &str) -> String {
format!("'{}'", text.replace('\\', "\\\\").replace('\'', "\\'"))
}
pub fn fish(program: &Program<'_>, records: &[Record]) -> Result<String, GenerateError> {
let commands = commands(program)?;
let Model { flags, positionals } = model(records);
let name = program.name;
let mut out = format!(
"# 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"
);
for command in &commands {
out.push_str(&format!(
"complete -c {name} -n '__fish_use_subcommand' -a {} -d {}\n",
command.name,
quote(&super::one_line(command.summary))
));
}
for flag in &flags {
let condition = if flag.scope.is_empty() {
String::new()
} else {
format!(" -n '__fish_seen_subcommand_from {}'", flag.scope.join(" "))
};
let mut spec = format!("complete -c {name}{condition}");
if let Some(short) = &flag.short {
spec.push_str(&format!(" -s {short}"));
}
if let Some(long) = &flag.long {
spec.push_str(&format!(" -l {long}"));
}
if flag.takes_value {
if !flag.values.is_empty() {
spec.push_str(&format!(" -x -a {}", quote(&flag.values.join(" "))));
} else if flag.path {
spec.push_str(" -r -F");
} else {
spec.push_str(" -x");
}
}
if !flag.summary.is_empty() {
spec.push_str(&format!(" -d {}", quote(&flag.summary)));
}
out.push_str(&spec);
out.push('\n');
if flag.negatable {
if let Some(long) = &flag.long {
out.push_str(&format!("complete -c {name}{condition} -l no-{long}"));
if !flag.summary.is_empty() {
out.push_str(&format!(
" -d {}",
quote(&format!("Turn off: {}", flag.summary))
));
}
out.push('\n');
}
}
}
for positional in &positionals {
if positional.values.is_empty() && !positional.path {
continue;
}
for command in commands.iter().filter(|c| positional.available_for(c.name)) {
let mut spec = format!(
"complete -c {name} -n '__fish_seen_subcommand_from {}'",
command.name
);
if positional.values.is_empty() {
spec.push_str(" -F");
} else {
spec.push_str(&format!(" -a {}", quote(&positional.values.join(" "))));
}
if !positional.summary.is_empty() {
spec.push_str(&format!(" -d {}", quote(&positional.summary)));
}
out.push_str(&spec);
out.push('\n');
}
}
Ok(out)
}