Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(cua-driver): print the named command's help for `<command> --help` (#5083)

Ritika Gupta2a50b895eb05
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
index eb93897c07..3df2de0c43 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
@@ -538,6 +538,10 @@ pub fn parse_command() -> Command {
std::process::exit(0);
}
if args.iter().any(|a| a == "--help" || a == "-h") {
+ if let Some(help) = command_help(&args) {
+ print!("{help}");
+ std::process::exit(0);
+ }
println!(
"cua-driver {} — cross-platform computer-use automation driver",
env!("CARGO_PKG_VERSION")
@@ -4155,6 +4159,133 @@ fn cli_docs_json() -> serde_json::Value {
docs
}
+/// Help for `cua-driver <command> [<subcommand>...] --help`: the deepest
+/// command the positional words name, rendered from `cli_docs_json()`. A word
+/// that is not a subcommand (an argument value) ends the walk. `None` when the
+/// first word is not a command, so the caller prints the top-level help.
+fn command_help(args: &[String]) -> Option<String> {
+ let docs = cli_docs_json();
+ let mut commands = docs["commands"].as_array()?;
+ let mut path = vec!["cua-driver"];
+ let mut found = None;
+ for word in positional_args(args) {
+ let Some(command) = commands.iter().find(|c| c["name"] == word) else {
+ break;
+ };
+ path.push(word);
+ found = Some(command);
+ let Some(subcommands) = command["subcommands"].as_array() else {
+ break;
+ };
+ commands = subcommands;
+ }
+ found.map(|command| render_command_help(command, &path.join(" ")))
+}
+
+/// One `cli_docs_json()` command as terminal help, in the order of its
+/// generated reference page (`scripts/docs-generators/lib/cli-mdx.ts`).
+fn render_command_help(command: &serde_json::Value, path: &str) -> String {
+ use std::fmt::Write as _;
+
+ let list = |key: &str| command[key].as_array().map(Vec::as_slice).unwrap_or(&[]);
+ let text = |value: &serde_json::Value, key: &str| {
+ value[key].as_str().unwrap_or_default().trim().to_owned()
+ };
+ let flag = |value: &serde_json::Value| match value["short_name"].as_str() {
+ Some(short) => format!("-{short}, --{}", text(value, "name")),
+ None => format!("--{}", text(value, "name")),
+ };
+ let (arguments, options, flags, subcommands) = (
+ list("arguments"),
+ list("options"),
+ list("flags"),
+ list("subcommands"),
+ );
+
+ let mut usage = vec![path.to_owned()];
+ if !options.is_empty() || !flags.is_empty() {
+ usage.push("[OPTIONS]".to_owned());
+ }
+ for argument in arguments {
+ let name = format!("<{}>", text(argument, "name"));
+ usage.push(if argument["is_optional"].as_bool().unwrap_or(false) {
+ format!("[{name}]")
+ } else {
+ name
+ });
+ }
+ if !subcommands.is_empty() {
+ let required = command["default_subcommand"].is_null();
+ usage.push(if required { "<COMMAND>" } else { "[COMMAND]" }.to_owned());
+ }
+
+ let mut out = String::new();
+ for key in ["abstract", "discussion"] {
+ let prose = text(command, key);
+ if !prose.is_empty() {
+ let _ = writeln!(out, "{prose}\n");
+ }
+ }
+ let _ = writeln!(out, "Usage: {}", usage.join(" "));
+ if let Some(default) = command["default_subcommand"].as_str() {
+ let _ = writeln!(out, "\nWithout a subcommand, runs {path} {default}.");
+ }
+
+ let mut section = |title: &str, rows: Vec<(String, String)>| {
+ if rows.is_empty() {
+ return;
+ }
+ let width = rows.iter().map(|(label, _)| label.len()).max().unwrap_or(0);
+ let _ = writeln!(out, "\n{title}:");
+ for (label, help) in rows {
+ let _ = writeln!(out, " {label:width$} {help}");
+ }
+ };
+ section(
+ "Arguments",
+ arguments
+ .iter()
+ .map(|a| (format!("<{}>", text(a, "name")), text(a, "help")))
+ .collect(),
+ );
+ section(
+ "Options",
+ options
+ .iter()
+ .map(|o| {
+ let repeat = if o["is_repeatable"].as_bool().unwrap_or(false) {
+ "..."
+ } else {
+ ""
+ };
+ let value = text(o, "type").to_lowercase();
+ (format!("{} <{value}>{repeat}", flag(o)), text(o, "help"))
+ })
+ .chain(flags.iter().map(|f| (flag(f), text(f, "help"))))
+ .collect(),
+ );
+ section(
+ "Commands",
+ subcommands
+ .iter()
+ .map(|s| (text(s, "name"), text(s, "abstract")))
+ .collect(),
+ );
+
+ let examples = list("examples");
+ if !examples.is_empty() {
+ let _ = writeln!(out, "\nExamples:");
+ for example in examples {
+ let description = text(example, "description");
+ if !description.is_empty() {
+ let _ = writeln!(out, " # {description}");
+ }
+ let _ = writeln!(out, " {}", text(example, "command"));
+ }
+ }
+ out
+}
+
/// Command groups that run a default subcommand when given none (the
/// dispatcher's `subcommand.unwrap_or(..)`), for the generated reference.
const CLI_DEFAULT_SUBCOMMANDS: &[(&str, &str)] = &[
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/command_help_cli_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/command_help_cli_test.rs
new file mode 100644
index 0000000000..6d7336016e
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/command_help_cli_test.rs
@@ -0,0 +1,78 @@
+use std::process::{Command, Output};
+
+fn run(home: &std::path::Path, args: &[&str]) -> Output {
+ Command::new(env!("CARGO_BIN_EXE_cua-driver"))
+ .args(args)
+ .env("CUA_DRIVER_RS_HOME", home)
+ .env("CUA_DRIVER_RS_TELEMETRY_ENABLED", "0")
+ .output()
+ .expect("run cua-driver")
+}
+
+fn help(home: &std::path::Path, args: &[&str]) -> String {
+ let output = run(home, args);
+ assert!(
+ output.status.success(),
+ "{args:?} exited {:?}: {}",
+ output.status,
+ String::from_utf8_lossy(&output.stderr)
+ );
+ String::from_utf8(output.stdout).expect("UTF-8 help")
+}
+
+/// `<command> --help` prints that command's reference from `cli_docs_json()`
+/// instead of the top-level help (#4708).
+#[test]
+fn command_help_prints_the_named_commands_reference() {
+ let home = tempfile::tempdir().expect("temp home");
+ let top = help(home.path(), &["--help"]);
+
+ let recording = help(home.path(), &["recording", "--help"]);
+ assert!(
+ recording != top,
+ "recording --help printed the top-level help"
+ );
+ assert!(
+ recording.contains("Usage: cua-driver recording [OPTIONS] [COMMAND]"),
+ "{recording}"
+ );
+ assert!(
+ recording.contains("Without a subcommand, runs cua-driver recording status."),
+ "{recording}"
+ );
+ for sub in ["start", "stop", "status", "render"] {
+ assert!(
+ recording.contains(&format!(" {sub} ")),
+ "missing subcommand {sub}:\n{recording}"
+ );
+ }
+
+ // Nested subcommand, the short flag, and a global value option before the command.
+ let render = help(
+ home.path(),
+ &["--socket", "/nonexistent.sock", "recording", "render", "-h"],
+ );
+ assert!(
+ render.contains("Usage: cua-driver recording render [OPTIONS] <input-dir> <out-mp4>"),
+ "{render}"
+ );
+ assert!(render.contains("--scale <number>"), "{render}");
+ assert!(render.contains("--no-zoom"), "{render}");
+
+ // A word that is not a subcommand (here the <output-dir> value) stops the walk.
+ let start = help(home.path(), &["recording", "start", "mydir", "--help"]);
+ assert!(
+ start.contains("Usage: cua-driver recording start <output-dir>"),
+ "{start}"
+ );
+
+ // An unknown command keeps the top-level help.
+ assert_eq!(help(home.path(), &["bogus", "--help"]), top);
+
+ // A long-lived command still only prints its help and exits.
+ let serve = help(home.path(), &["serve", "--help"]);
+ assert!(
+ serve.contains("Usage: cua-driver serve [OPTIONS]"),
+ "{serve}"
+ );
+}