Skip to main content

subspace_board_command/
cli.rs

1use crate::{Composition, execute, fail, root, tree};
2use std::{collections::HashMap, process::ExitCode};
3use subspace_agent_tools::ToolEnvironment;
4use subspace_product::ProductContext;
5use usage::parse::{ParseOutput, ParseValue, TokenRole};
6
7/// Headless product command using the same served catalog as MCP.
8pub fn run(
9    context: &ProductContext,
10    boards: &[subspace_mcp::Board],
11    environment: &ToolEnvironment,
12    args: &[String],
13) -> ExitCode {
14    match capabilities(context, boards, environment) {
15        Ok(capabilities) => run_catalog(context, &capabilities, args),
16        Err(error) => fail(&error, 1),
17    }
18}
19
20/// The served catalogue, with the tools each declared Space provides.
21pub(crate) fn capabilities(
22    context: &ProductContext,
23    boards: &[subspace_mcp::Board],
24    environment: &ToolEnvironment,
25) -> Result<tree::Capabilities, String> {
26    subspace_mcp::served_catalog(boards, &[], environment)
27        .map(|grouped| tree::Capabilities::new(context, &grouped))
28}
29
30/// The default CLI: the Framework's root tree, its completion, and no
31/// product commands, so an unmatched root command is reported.
32const STANDARD: Composition = Composition::new(root::tree, root::complete_word, unknown_command);
33
34type Fallback = fn(&ProductContext, &[String]) -> ExitCode;
35
36#[cfg(test)]
37pub(crate) fn commands(
38    context: &ProductContext,
39    capabilities: &tree::Capabilities,
40) -> Result<tree::Commands, String> {
41    STANDARD.commands(context, capabilities)
42}
43
44pub(crate) fn run_catalog(
45    context: &ProductContext,
46    capabilities: &tree::Capabilities,
47    args: &[String],
48) -> ExitCode {
49    STANDARD.run_catalog(context, capabilities, args)
50}
51
52pub(crate) fn run_commands(
53    context: &ProductContext,
54    generated: &tree::Commands,
55    args: &[String],
56    complete: fn(&usage::Spec, &[String]) -> Vec<String>,
57    fallback: Fallback,
58) -> ExitCode {
59    if let Some(words) = args.strip_prefix(&[root::COMPLETE_WORD.into(), "--".into()]) {
60        for word in complete(&generated.spec, words) {
61            println!("{word}");
62        }
63        return ExitCode::SUCCESS;
64    }
65    if args.len() == 1
66        && generated
67            .routes
68            .iter()
69            .any(|route| route.path.len() == 2 && route.path[0] == args[0])
70    {
71        return parse_and_run(
72            context,
73            generated,
74            &[args[0].clone(), "--help".into()],
75            fallback,
76        );
77    }
78    parse_and_run(context, generated, args, fallback)
79}
80
81fn parse_and_run(
82    context: &ProductContext,
83    commands: &tree::Commands,
84    args: &[String],
85    fallback: Fallback,
86) -> ExitCode {
87    let argv: Vec<String> = std::iter::once(commands.spec.bin.clone())
88        .chain(args.iter().cloned())
89        .collect();
90    let output = match usage::parse::Parser::new(&commands.spec).explain(&argv) {
91        Ok(output) => output,
92        Err(error) => return refused(context, commands, &argv, &error, fallback),
93    };
94    if let Some(page) = output.errors.iter().find(|error| {
95        matches!(
96            error,
97            usage::error::UsageErr::Help(_) | usage::error::UsageErr::Version(_)
98        )
99    }) {
100        print!("{page}");
101        return ExitCode::SUCCESS;
102    }
103    // An error the parser collected came from a declaration that took the
104    // word, so it never names an unmatched root command.
105    if !output.errors.is_empty() {
106        for error in &output.errors {
107            eprintln!("{error}");
108        }
109        return ExitCode::from(2);
110    }
111    let path: Vec<&str> = output
112        .cmds
113        .iter()
114        .skip(1)
115        .map(|cmd| cmd.name.as_str())
116        .collect();
117    if path == [root::COMPLETION] && root::declares_framework_completion(&commands.spec) {
118        return completion(context, &output);
119    }
120    match commands.routes.iter().find(|route| {
121        route
122            .path
123            .iter()
124            .map(String::as_str)
125            .eq(path.iter().copied())
126    }) {
127        Some(route) => execute(route, &output),
128        None => fallback(context, args),
129    }
130}
131
132/// A line the parser refused. It goes to the fallback only when usage-lib
133/// stopped on an `unexpected word` at the root and everything before that
134/// word is a complete, valid line of root flags on its own; any other
135/// failure is reported.
136///
137/// usage-lib drops the errors it had collected when it stops on an
138/// unexpected word, so the words before the stop are validated by parsing
139/// them alone with the full parser, which reaches its end and reports every
140/// error. Only the stop's position comes from a token trace.
141fn refused(
142    context: &ProductContext,
143    commands: &tree::Commands,
144    argv: &[String],
145    error: &usage::miette::Error,
146    fallback: Fallback,
147) -> ExitCode {
148    let stop = unexpected_word(error).and_then(|word| root_stop(&commands.spec, argv, &word));
149    match stop.filter(|&stop| valid_root_prefix(&commands.spec, &argv[..stop])) {
150        Some(_) => fallback(context, &argv[1..]),
151        None => fail(&error.to_string(), 2),
152    }
153}
154
155/// The word usage-lib's binding stop names. usage-lib raises that stop as an
156/// untyped message rather than a `UsageErr` variant, so its text is all
157/// there is to read; the trace must then stop at the same word.
158fn unexpected_word(error: &usage::miette::Error) -> Option<String> {
159    error
160        .to_string()
161        .strip_prefix("unexpected word: ")
162        .map(str::to_owned)
163}
164
165/// Where in `argv` the parse stopped on `word`, a non-flag word nothing
166/// took. usage-lib 7.3.0 gives the message (`Parser::explain`) and the token
167/// trace (`Parser::explain_refused`) only from separate parses, so the
168/// position comes from a second one that runs nothing: no mount discovery
169/// and no `choices run=`. It binds as the first did up to the first mount;
170/// at a mount it stops with no refused word, and where it binds further
171/// than the first it stops at another word, so both are reported. A
172/// declared `default_subcommand` takes every non-flag word, so with one no
173/// stop is at the root.
174fn root_stop(spec: &usage::Spec, argv: &[String], word: &str) -> Option<usize> {
175    if spec.default_subcommand.is_some() || word.starts_with('-') {
176        return None;
177    }
178    let tokens = usage::parse::Parser::new(spec)
179        .with_mount_outputs(HashMap::new())
180        .without_running_commands()
181        .explain_refused(argv)
182        .err()?;
183    let stop = tokens.iter().rev().find(|token| {
184        token
185            .roles
186            .iter()
187            .any(|role| !matches!(role, TokenRole::Unread))
188    })?;
189    let refused = stop
190        .roles
191        .iter()
192        .any(|role| matches!(role, TokenRole::Refused { .. }));
193    (refused && stop.word == word).then_some(stop.index)
194}
195
196/// Whether `prefix` (the program name and the words before the stop) parses
197/// on its own, with every check the parser makes, into the root command with
198/// no argument bound and no `--` separator: then the stop was at the root
199/// and every word before it was a valid root flag or flag value. Any error
200/// disqualifies it, a `required` root flag the line omits included, since
201/// the product declared that every line needs it.
202fn valid_root_prefix(spec: &usage::Spec, prefix: &[String]) -> bool {
203    usage::parse::Parser::new(spec)
204        .explain(prefix)
205        .is_ok_and(|output| {
206            output.errors.is_empty()
207                && output.cmds.len() == 1
208                && output.args.is_empty()
209                && !output.double_dash_seen
210        })
211}
212
213pub(crate) fn unknown_command(_: &ProductContext, args: &[String]) -> ExitCode {
214    fail(&format!("Unknown command: {}", args.join(" ")), 2)
215}
216
217fn completion(context: &ProductContext, output: &ParseOutput) -> ExitCode {
218    let shell = output.args.iter().find_map(|(arg, value)| match value {
219        ParseValue::String(shell) if arg.name == "shell" => Some(shell.as_str()),
220        _ => None,
221    });
222    match shell.and_then(|shell| root::init_script(context.product.binary_name.as_str(), shell)) {
223        Some(script) => {
224            print!("{script}");
225            ExitCode::SUCCESS
226        }
227        None => fail("Choose a completion shell: bash, zsh or fish.", 2),
228    }
229}