subspace_board_command/
root.rs1use subspace_product::{MCP_USAGE, ProductContext, UPGRADE_USAGE};
5
6const COMPLETION_USAGE: &str = r#"cmd "completion" effect="read" help="Print a shell completion script for the current shell" {
7 arg "<shell>" help="Target shell" {
8 choices "bash" "zsh" "fish"
9 }
10}
11cmd "__complete-word" hide=#true effect="read" help="Internal: list completion candidates for a partial command line" {
12 arg "[words]..." help="Words after the shell completion separator"
13}"#;
14
15pub(crate) const COMPLETION: &str = "completion";
16pub(crate) use subspace_product::COMPLETE_WORD_COMMAND as COMPLETE_WORD;
17
18pub fn tree(context: &ProductContext) -> Result<usage::Spec, String> {
20 let upgrade = if context.product.update.is_some() {
21 UPGRADE_USAGE
22 } else {
23 ""
24 };
25 format!(
26 "bin {:?}\nversion {:?}\n{COMPLETION_USAGE}\n{MCP_USAGE}\n{upgrade}\n",
27 context.product.binary_name.as_str(),
28 context.version,
29 )
30 .parse::<usage::Spec>()
31 .map_err(|error| error.to_string())
32}
33
34pub(crate) fn declares_framework_completion(spec: &usage::Spec) -> bool {
37 let framework = format!("bin {:?}\n{COMPLETION_USAGE}", spec.bin).parse::<usage::Spec>();
38 let declared = |spec: &usage::Spec| {
39 spec.cmd
40 .subcommands
41 .get(COMPLETION)
42 .and_then(|command| serde_json::to_value(command).ok())
43 };
44 framework.is_ok_and(|framework| {
45 declared(spec).is_some_and(|ours| Some(ours) == declared(&framework))
46 })
47}
48
49pub fn complete_word(spec: &usage::Spec, words: &[String]) -> Vec<String> {
52 let Some((prefix, preceding)) = words.split_last() else {
53 return Vec::new();
54 };
55 if !prefix.starts_with('-')
58 && let Some((flag_word, before_flag)) = preceding.split_last()
59 && flag_word.starts_with('-')
60 {
61 return flag_choices(spec, before_flag, flag_word, prefix);
62 }
63 let argv: Vec<String> = std::iter::once(spec.bin.clone())
64 .chain(preceding.iter().cloned())
65 .collect();
66 let Ok(output) = usage::parse::Parser::new(spec).explain(&argv) else {
67 return Vec::new();
68 };
69 let mut candidates: Vec<String> = if prefix.starts_with('-') {
70 output
71 .completion_flags()
72 .into_keys()
73 .filter(|key| key.starts_with(prefix.as_str()))
74 .collect()
75 } else {
76 let choices = output
77 .next_arg
78 .as_ref()
79 .and_then(|arg| arg.choices.as_ref())
80 .map(|choices| choices.choices.clone())
81 .unwrap_or_default();
82 output
83 .cmd
84 .subcommands
85 .iter()
86 .filter(|(_, command)| !command.hide)
87 .map(|(name, _)| name.clone())
88 .chain(choices)
89 .filter(|word| word.starts_with(prefix.as_str()))
90 .collect()
91 };
92 candidates.sort();
93 candidates.dedup();
94 candidates
95}
96
97fn flag_choices(
98 spec: &usage::Spec,
99 before_flag: &[String],
100 flag_word: &str,
101 prefix: &str,
102) -> Vec<String> {
103 let argv: Vec<String> = std::iter::once(spec.bin.clone())
104 .chain(before_flag.iter().cloned())
105 .collect();
106 let Ok(output) = usage::parse::Parser::new(spec).explain(&argv) else {
107 return Vec::new();
108 };
109 let mut candidates: Vec<String> = output
110 .completion_flags()
111 .get(flag_word)
112 .and_then(|flag| flag.arg.as_ref())
113 .and_then(|arg| arg.choices.as_ref())
114 .map(|choices| {
115 choices
116 .choices
117 .iter()
118 .filter(|choice| choice.starts_with(prefix))
119 .cloned()
120 .collect()
121 })
122 .unwrap_or_default();
123 candidates.sort();
124 candidates.dedup();
125 candidates
126}
127
128pub(crate) fn init_script(bin: &str, shell: &str) -> Option<String> {
130 let bin_fn = bin.replace(['-', ' '], "_");
131 match shell {
132 "bash" => Some(format!(
133 r#"_{bin_fn}_complete() {{
134 local cur="${{COMP_WORDS[COMP_CWORD]}}"
135 local words=("${{COMP_WORDS[@]:1:COMP_CWORD}}")
136 COMPREPLY=($(compgen -W "$(command {bin} __complete-word -- "${{words[@]}}" 2>/dev/null)" -- "$cur"))
137}}
138complete -F _{bin_fn}_complete {bin}
139"#
140 )),
141 "zsh" => Some(format!(
142 r#"#compdef {bin}
143_{bin_fn}_complete() {{
144 local -a words=("${{(@)words[2,CURRENT]}}")
145 local -a candidates
146 candidates=("${{(@f)$(command {bin} __complete-word -- "${{words[@]}}" 2>/dev/null)}}")
147 compadd -a candidates
148}}
149compdef _{bin_fn}_complete {bin}
150"#
151 )),
152 "fish" => Some(format!(
153 r#"function __{bin_fn}_complete_word
154 set -l tokens (commandline -opc)
155 set -l cur (commandline -ct)
156 command {bin} __complete-word -- $tokens[2..-1] $cur 2>/dev/null
157end
158complete -c {bin} -f -a '(__{bin_fn}_complete_word)'
159"#
160 )),
161 _ => None,
162 }
163}