From cbd79ff28027824cb83bbc016bbfca537be58251 Mon Sep 17 00:00:00 2001 From: Simon Klee Date: Thu, 5 Nov 2026 00:26:08 +0100 Subject: [PATCH] feat(cli-rs): add the --wizard command wizard Port Effect CLI's wizard: it asks for the selected command's flags and arguments, or for a subcommand, with Effect's select, confirm, toggle, integer, and text prompts, prints the command line, and runs it after a confirmation by running the binary again with it. Required arguments are not checked next to --wizard, so it can ask for them. The prompts share the Clack kit's raw mode and key decoding. --- packages/cli-rs/crates/cli/src/args.rs | 10 +- packages/cli-rs/crates/cli/src/main.rs | 29 +- packages/cli-rs/crates/cli/src/prompt/core.rs | 8 + packages/cli-rs/crates/cli/src/prompt/mod.rs | 7 +- packages/cli-rs/crates/cli/src/prompt/term.rs | 6 + packages/cli-rs/crates/cli/src/wizard.rs | 615 ++++++++++++- .../cli-rs/crates/cli/src/wizard/prompt.rs | 814 ++++++++++++++++++ packages/cli-rs/docs/C.0.md | 3 +- .../parity/deviations/C40-handler-errors.md | 7 + .../parity/deviations/G10-usage-errors.md | 3 +- .../cli-rs/parity/deviations/G15-wizard.md | 9 - 11 files changed, 1490 insertions(+), 21 deletions(-) create mode 100644 packages/cli-rs/crates/cli/src/wizard/prompt.rs delete mode 100644 packages/cli-rs/parity/deviations/G15-wizard.md diff --git a/packages/cli-rs/crates/cli/src/args.rs b/packages/cli-rs/crates/cli/src/args.rs index 2dc61ec72da..7470972b406 100644 --- a/packages/cli-rs/crates/cli/src/args.rs +++ b/packages/cli-rs/crates/cli/src/args.rs @@ -1035,6 +1035,10 @@ fn push_bool(out: &mut Vec, node: &clap::Command, arg: &clap::Arg, ena } } +/// The repeatable flags with `Flag.atMost(100)` in commands.ts, by command name and flag. +pub const AT_MOST_100: [(&str, &str); 3] = + [("api", "header"), ("login", "answer"), ("run", "file")]; + /// Checks Effect CLI rules clap does not know, after clap parsed `matches` of `command` (built). Returns the /// `--standalone` and `--server` that apply to the selected command: the root's own, or those of the /// command that declares them, which may be given before the subcommand (`opencode --server URL session list`). @@ -1092,8 +1096,10 @@ pub fn validate(command: &clap::Command, matches: &ArgMatches) -> Result ExitCode { return ExitCode::from(askpass::run(&port)); } let command = help::command(); - let argv = match args::normalize(&command, std::env::args_os().collect()) { + let raw: Vec<_> = std::env::args_os().collect(); + let argv = match args::normalize(&command, raw.clone()) { Ok(argv) => argv, Err(message) => return usage_error(&message), }; - let matches = match command.clone().try_get_matches_from(argv) { + // Effect CLI runs its action flags before it checks for missing arguments, so the wizard can ask for them. + let wizard = wizard::requested(&argv); + let parser = match wizard { + true => wizard::lenient(command.clone()), + false => command.clone(), + }; + let matches = match parser.try_get_matches_from(argv) { Ok(matches) => matches, Err(error) => { // Effect CLI exits 1 on a usage error; clap would exit 2. Help output (`--help`) exits 0. @@ -39,6 +46,19 @@ fn main() -> ExitCode { return ExitCode::from(u8::from(error.use_stderr())); } }; + if wizard { + let global = match args::GlobalArgs::from_arg_matches(&matches) { + Ok(global) => global, + Err(error) => return usage_error(&error.to_string()), + }; + // `--version` comes before `--wizard`. + if global.version { + return exit(help::version()); + } + signals::install(); + let _terminal = signals::on_shutdown("restore the terminal", prompt::restore_terminal); + return exit(wizard::run(&command, &matches, &raw)); + } let cli = match args::Cli::from_arg_matches(&matches) { Ok(cli) => cli, Err(error) => return usage_error(&error.to_string()), @@ -50,7 +70,6 @@ fn main() -> ExitCode { let result = match &cli.global { // Effect CLI runs the first action flag given, in this order, instead of the command. global if global.version => help::version(), - global if global.wizard => wizard::run(), args::GlobalArgs { completions: Some(shell), .. @@ -95,6 +114,10 @@ fn main() -> ExitCode { result } }; + exit(result) +} + +fn exit(result: anyhow::Result<()>) -> ExitCode { let code = match result { Ok(()) => ExitCode::SUCCESS, Err(error) => ExitCode::from(output::fail(error)), diff --git a/packages/cli-rs/crates/cli/src/prompt/core.rs b/packages/cli-rs/crates/cli/src/prompt/core.rs index 9f76cba356f..8981f40ace0 100644 --- a/packages/cli-rs/crates/cli/src/prompt/core.rs +++ b/packages/cli-rs/crates/cli/src/prompt/core.rs @@ -89,6 +89,14 @@ const ERASE_LINE: &str = "\x1b[2K\x1b[G"; /// Keypresses that arrived after the last prompt finished wait here for the next one. static KEYS: Mutex> = Mutex::new(None); +/// Runs `read` with stdin in raw mode and the keypresses the prompts share, for prompts drawn elsewhere (the +/// wizard draws Effect CLI's prompts, not Clack's). +pub fn with_keys(read: impl FnOnce(&mut Keys) -> R) -> R { + let _raw = Raw::enable(); + let mut keys = KEYS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + read(keys.get_or_insert_with(Keys::new)) +} + /// Runs a prompt until it is submitted or cancelled. pub fn run( prompt: &mut dyn Prompt, diff --git a/packages/cli-rs/crates/cli/src/prompt/mod.rs b/packages/cli-rs/crates/cli/src/prompt/mod.rs index 34cc79fac2d..7f9351172b6 100644 --- a/packages/cli-rs/crates/cli/src/prompt/mod.rs +++ b/packages/cli-rs/crates/cli/src/prompt/mod.rs @@ -19,8 +19,9 @@ //! prompt whose input ends is cancelled. // What no command uses yet: `note`, the box-drawing symbols, the spinner's options and `message`, and builder -// options (`output`, `max_items`, `placeholder`, `default_value`, `mask`, `cursor_at`, ...) that C.8, C.9 and -// C.15 may need. The builder types and `limit_options` are not re-exported until a caller names them. +// options (`output`, `max_items`, `placeholder`, `default_value`, `mask`, `cursor_at`, ...) that C.8 and C.9 +// may need. The builder types and `limit_options` are not re-exported until a caller names them. The wizard +// (C.15) draws Effect CLI's prompts and uses only `with_keys`, `Keys`, `Press`, and `stdout_size`. #![allow(dead_code)] mod autocomplete; @@ -36,9 +37,11 @@ mod wrap; pub use autocomplete::{View, autocomplete}; pub use confirm::confirm; +pub use core::with_keys; pub use select::{Choice, multiselect, select}; pub use spinner::spinner; pub use style::*; +pub use term::{Keys, Press}; pub use text::{password, text}; /// The user cancelled a prompt. diff --git a/packages/cli-rs/crates/cli/src/prompt/term.rs b/packages/cli-rs/crates/cli/src/prompt/term.rs index c67c130f5a0..774b8b2439a 100644 --- a/packages/cli-rs/crates/cli/src/prompt/term.rs +++ b/packages/cli-rs/crates/cli/src/prompt/term.rs @@ -223,6 +223,12 @@ impl Keys { } } + /// Drops what was read but not delivered yet. Effect CLI's prompts lose the rest of a chunk when one ends. + pub fn discard(&mut self) { + self.chars.clear(); + self.bytes.clear(); + } + /// The next keypress, or `None` at the end of input. pub fn next(&mut self) -> Option { loop { diff --git a/packages/cli-rs/crates/cli/src/wizard.rs b/packages/cli-rs/crates/cli/src/wizard.rs index 94471eb8bed..6cdec5c3d5e 100644 --- a/packages/cli-rs/crates/cli/src/wizard.rs +++ b/packages/cli-rs/crates/cli/src/wizard.rs @@ -1,5 +1,614 @@ -//! `--wizard`. Step C.15; until then the flag is accepted and reports that it is not supported (O-11). +//! `--wizard`, Effect CLI's command wizard (`effect/src/cli/internal/wizard.ts` and `Command.ts`): asks for the +//! selected command's flags and arguments, or for a subcommand, prints the command line, and runs it after a +//! confirmation. Step C.15. -pub fn run() -> anyhow::Result<()> { - anyhow::bail!("--wizard is not supported yet (plan step C.15)") +mod prompt; + +use std::ffi::OsString; + +use clap::{ArgAction, ArgMatches}; + +use crate::args::AT_MOST_100; +use crate::help; +use prompt::{ + BLACK_BRIGHT, BOLD, CYAN_BRIGHT, Confirm, GREEN, Int, MAGENTA, Quit, RED, Select, Text, Toggle, + WHITE, annotate, log, +}; + +/// Whether the normalized `argv` asks for the wizard: `--wizard` before any `--`. +pub fn requested(argv: &[OsString]) -> bool { + argv.iter() + .skip(1) + .take_while(|arg| *arg != "--") + .any(|arg| arg == "--wizard") +} + +/// `command` without required arguments, to parse the command line the wizard starts from. +pub fn lenient(command: clap::Command) -> clap::Command { + command + .mut_args(|arg| arg.required(false)) + .mut_subcommands(lenient) +} + +/// Runs the wizard for the command `matches` selected in `command` (built), started with `argv`, then the command +/// line it built, unless the user cancelled or declined. +pub fn run(command: &clap::Command, matches: &ArgMatches, argv: &[OsString]) -> anyhow::Result<()> { + let Some(line) = build(command, matches, argv)? else { + return Ok(()); + }; + // Effect CLI runs the command line as if it had been typed. Running this binary again with it lets + // everything that reads the process arguments (delegation to TypeScript, `run`'s words after `--`) see it. + let mut process = std::process::Command::new(std::env::current_exe()?); + process.args(line); + #[cfg(unix)] + { + use std::os::unix::process::CommandExt; + if let Some(arg0) = argv.first() { + process.arg0(arg0); + } + Err(process.exec().into()) + } + #[cfg(not(unix))] + std::process::exit(process.status()?.code().unwrap_or(1)) +} + +/// Asks for the command line. Returns its arguments after the program name, or `None` when the user cancelled or +/// declined. +fn build( + command: &clap::Command, + matches: &ArgMatches, + argv: &[OsString], +) -> anyhow::Result>> { + let name = help::name(); + log(&introduction( + &name, + command.get_about().map(|about| about.to_string()), + )); + let mut node = command; + let mut leaf = matches; + while let Some((sub, sub_matches)) = leaf.subcommand() { + node = node.find_subcommand(sub).expect("clap matched it"); + leaf = sub_matches; + } + let mut line: Vec = std::iter::once(name) + .chain( + argv.iter() + .skip(1) + .map(|arg| arg.to_string_lossy().into_owned()) + .filter(|arg| arg != "--wizard" && !arg.starts_with("--wizard=")), + ) + .collect(); + let section = match std::ptr::eq(node, command) { + true => "ROOT".to_string(), + false => node.get_name().to_string(), + }; + let outcome = (|| -> Result>, Stop> { + log_command("Current command", &line, MAGENTA, WHITE); + prompt_command(node, &mut line, §ion)?; + log_command("Command ready", &line, CYAN_BRIGHT, GREEN); + let run = Toggle { + message: "Run this command?".into(), + active: "yes", + inactive: "no", + } + .prompt()?; + if !run { + return Ok(None); + } + log(""); + Ok(Some(line)) + })(); + match outcome { + Ok(line) => Ok(line.map(|line| line.into_iter().skip(1).collect())), + Err(Stop::Quit) => { + log(&format!("\n{}", annotate("Wizard cancelled.", &[RED]))); + Ok(None) + } + Err(Stop::Invalid(message)) => Err(anyhow::anyhow!(message)), + } +} + +enum Stop { + Quit, + Invalid(String), +} + +impl From for Stop { + fn from(_: Quit) -> Stop { + Stop::Quit + } +} + +fn prompt_command(node: &clap::Command, line: &mut Vec, section: &str) -> Result<(), Stop> { + let subcommands: Vec<&clap::Command> = node + .get_subcommands() + .filter(|sub| !sub.is_hide_set()) + .collect(); + // Effect asks for a group's shared flags only, and no command here has any. + let (flags, arguments) = match subcommands.is_empty() { + true => ( + flags(node), + node.get_positionals().map(|arg| param(node, arg)).collect(), + ), + false => (Vec::new(), Vec::new()), + }; + if !flags.is_empty() { + log(&render_section(section, "FLAGS")); + for flag in &flags { + line.extend(prompt_param(flag)?); + } + if !arguments.is_empty() || !subcommands.is_empty() { + log_command("Current command", line, MAGENTA, WHITE); + } + } + if !arguments.is_empty() { + log(&render_section(section, "ARGUMENTS")); + for argument in &arguments { + line.extend(prompt_param(argument)?); + } + if !subcommands.is_empty() { + log_command("Current command", line, MAGENTA, WHITE); + } + } + if subcommands.is_empty() { + return Ok(()); + } + let index = Select { + message: "Command".into(), + choices: subcommands + .iter() + .map(|sub| { + ( + sub.get_name().to_string(), + sub.get_about().map(|about| about.to_string()), + ) + }) + .collect(), + } + .prompt()?; + log(""); + let child = subcommands[index]; + line.push(child.get_name().to_string()); + let steps = child.get_subcommands().any(|sub| !sub.is_hide_set()) + || child + .get_arguments() + .any(|arg| !arg.is_global_set() && !is_negation(child, arg)); + if steps { + log_command("Current command", line, MAGENTA, WHITE); + } + prompt_command(child, line, child.get_name()) +} + +/// A flag or argument as the wizard sees it: Effect's `getParamMetadata` and primitive type. +struct Param<'a> { + arg: &'a clap::Arg, + name: String, + flag: bool, + kind: Kind, + optional: bool, + /// Asks for a count first, with these bounds. + variadic: Option<(i64, Option)>, +} + +enum Kind { + Boolean, + Choice(Vec), + Int, + Text, +} + +/// The command's own flags in declaration order: not the globals, and not the hidden `--no-` helpers. +fn flags(node: &clap::Command) -> Vec> { + node.get_arguments() + .filter(|arg| !arg.is_positional() && !arg.is_global_set() && !is_negation(node, arg)) + .map(|arg| param(node, arg)) + .collect() +} + +fn param<'a>(node: &clap::Command, arg: &'a clap::Arg) -> Param<'a> { + let action = arg.get_action(); + let value_name = arg + .get_value_names() + .and_then(|names| names.first()) + .map(|name| name.to_string()) + .unwrap_or_default(); + let choices: Vec = arg + .get_possible_values() + .iter() + .map(|value| value.get_name().to_string()) + .collect(); + let kind = match () { + _ if matches!(action, ArgAction::SetTrue) => Kind::Boolean, + _ if !choices.is_empty() => Kind::Choice(choices), + _ if value_name == "integer" => Kind::Int, + _ => Kind::Text, + }; + let range = arg.get_num_args(); + if arg.is_positional() { + let variadic = matches!(action, ArgAction::Append) + || range.is_some_and(|range| range.max_values() > 1); + let min = match arg.is_required_set() { + true => range.map_or(1, |range| range.min_values()) as i64, + false => 0, + }; + let max = range + .map(|range| range.max_values()) + .filter(|max| *max != usize::MAX); + return Param { + arg, + name: value_name, + flag: false, + kind, + optional: !variadic && !arg.is_required_set(), + variadic: variadic.then_some((min, max.map(|max| max as i64))), + }; + } + let long = arg.get_long().unwrap_or_default().to_string(); + // Flag.KeyValuePair is optional and repeatable at least once; other repeatable flags are Flag.atMost(100) or + // Flag.atLeast(0). + let (optional, variadic) = match action { + ArgAction::Append if value_name == "key=value" => (true, Some((1, None))), + ArgAction::Append => { + let limited = AT_MOST_100.contains(&(node.get_name(), long.as_str())); + (false, Some((0, limited.then_some(100)))) + } + _ => (!arg.is_required_set(), None), + }; + Param { + arg, + name: long, + flag: true, + kind, + optional, + variadic, + } +} + +// `--no-replay` is the hidden negation that `args::normalize` emits; Effect CLI has it built into `--replay`. +fn is_negation(command: &clap::Command, arg: &clap::Arg) -> bool { + arg.is_hide_set() + && arg + .get_long() + .and_then(|long| long.strip_prefix("no-")) + .is_some_and(|long| { + command + .get_arguments() + .any(|other| other.get_long() == Some(long)) + }) +} + +fn prompt_param(param: &Param) -> Result, Stop> { + let label = label(param); + if param.optional && !Confirm::new(format!("Set {label}?")).prompt()? { + log(""); + return Ok(Vec::new()); + } + let count = match param.variadic { + None => 1, + Some((min, max)) => Int { + message: format!("{label} count"), + default: Some(min), + min: Some(min), + max, + } + .prompt()?, + }; + let mut values = Vec::new(); + for _ in 0..count { + values.push(prompt_single(param, &label)?); + } + if !matches!(param.kind, Kind::Boolean) { + for value in &values { + parse(param, value).map_err(|error| Stop::Invalid(invalid(param, value, &error)))?; + } + } + log(""); + if !param.flag { + return Ok(values); + } + // Option-looking values go inline so the parser cannot read them as flags; a flag with an optional value + // only takes an inline one. + let optional_value = param.arg.is_require_equals_set(); + Ok(values + .into_iter() + .flat_map( + |value| match optional_value || (value.starts_with('-') && value.len() > 1) { + true => vec![format!("--{}={value}", param.name)], + false => vec![format!("--{}", param.name), value], + }, + ) + .collect()) +} + +fn prompt_single(param: &Param, label: &str) -> Result { + let message = label.to_string(); + Ok(match ¶m.kind { + Kind::Boolean => Confirm { + message, + labels: ("true", "false"), + placeholders: ("(T/f)", "(t/F)"), + } + .prompt()? + .to_string(), + Kind::Choice(choices) => { + let index = Select { + message, + choices: choices + .iter() + .map(|choice| (choice.clone(), None)) + .collect(), + } + .prompt()?; + choices[index].clone() + } + Kind::Int => Int { + message, + default: None, + min: None, + max: None, + } + .prompt()? + .to_string(), + Kind::Text => Text { message }.prompt()?, + }) +} + +/// Parses one value with the argument's own value parser, as Effect parses each param after its prompts. +fn parse(param: &Param, value: &str) -> Result<(), clap::Error> { + let arg = param + .arg + .clone() + .required(false) + .global(false) + .action(ArgAction::Set); + let (arg, word) = match param.flag { + true => (arg, format!("--{}={value}", param.name)), + false => ( + arg.index(1).num_args(1).allow_hyphen_values(true), + value.to_string(), + ), + }; + clap::Command::new("wizard") + .no_binary_name(true) + .arg(arg) + .try_get_matches_from([word]) + .map(drop) +} + +/// The first line of Effect's `InvalidValue`, with clap's reason in place of Effect's schema message. +fn invalid(param: &Param, value: &str, error: &clap::Error) -> String { + let message = error.to_string(); + let line = message.lines().next().unwrap_or_default(); + // "error: invalid value '0' for '--max-count ': 0 is not in 1..=4294967295" + let reason = line.rsplit_once("': ").map_or(line, |(_, reason)| reason); + let kind = if param.flag { "flag --" } else { "argument " }; + format!( + "Invalid value for {kind}{}: \"{value}\". Expected: {reason}", + param.name + ) +} + +/// `renderParamLabel`: a flag's description when it is short, else its humanized name. +fn label(param: &Param) -> String { + let description = param + .arg + .get_help() + .map(|help| help.to_string().trim().to_string()); + let label = match description { + Some(description) if param.flag && description.encode_utf16().count() <= 32 => description, + _ => humanize(¶m.name), + }; + match param.flag { + true => format!("{label} (--{})", param.name), + false => label, + } +} + +fn humanize(name: &str) -> String { + let words: Vec<&str> = name + .split(['-', '_']) + .filter(|word| !word.is_empty()) + .collect(); + let Some((first, rest)) = words.split_first() else { + return name.to_string(); + }; + let mut chars = first.chars(); + let head: String = chars + .next() + .map(|char| char.to_uppercase().collect()) + .unwrap_or_default(); + std::iter::once(head + chars.as_str()) + .chain(rest.iter().map(|word| word.to_string())) + .collect::>() + .join(" ") +} + +fn introduction(name: &str, summary: Option) -> String { + let title = format!( + "{} {} {}", + annotate(name, &[BOLD, CYAN_BRIGHT]), + annotate(&format!("v{}", help::VERSION), &[WHITE]), + annotate("· Command wizard", &[BOLD, WHITE]) + ); + std::iter::once(title) + .chain(summary.filter(|summary| !summary.is_empty())) + .chain([ + annotate( + "Build a command interactively. Press Ctrl+C to cancel.", + &[BLACK_BRIGHT], + ), + String::new(), + ]) + .collect::>() + .join("\n") +} + +fn render_section(name: &str, section: &str) -> String { + format!( + "{} {} {}", + annotate(&name.to_uppercase(), &[BOLD, CYAN_BRIGHT]), + annotate("·", &[BLACK_BRIGHT]), + annotate(section, &[BOLD, WHITE]) + ) +} + +fn log_command(label: &str, line: &[String], color: &str, label_color: &str) { + let lines = std::iter::once(annotate(label, &[BOLD, label_color])) + .chain( + wrap_command(line) + .iter() + .map(|line| annotate(line, &[color])), + ) + .chain(std::iter::once(String::new())) + .collect::>(); + log(&lines.join("\n")); +} + +/// `wrapCommand`: shell words on lines of at most 88 columns, continued with a backslash. +fn wrap_command(line: &[String]) -> Vec { + const WIDTH: usize = 88; + const FIRST: &str = " $ "; + const CONTINUATION: &str = " "; + let mut lines = Vec::new(); + let mut current = FIRST.to_string(); + for arg in line.iter().map(|arg| shell_word(arg)) { + let separator = if current == FIRST || current == CONTINUATION { + "" + } else { + " " + }; + let length = |text: &str| text.encode_utf16().count(); + if length(¤t) + separator.len() + length(&arg) > WIDTH && current != FIRST { + lines.push(format!("{current} \\")); + current = format!("{CONTINUATION}{arg}"); + } else { + current += separator; + current += &arg; + } + } + if current != FIRST { + lines.push(current); + } + lines +} + +fn shell_word(arg: &str) -> String { + let plain = !arg.is_empty() + && arg + .chars() + .all(|char| char.is_ascii_alphanumeric() || "_./:@%+=,-".contains(char)); + match plain { + true => arg.to_string(), + false => format!("'{}'", arg.replace('\'', "'\"'\"'")), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::Value; + + #[test] + fn shell_words_quote_like_effect() { + assert_eq!(shell_word("--format"), "--format"); + assert_eq!(shell_word("a b"), "'a b'"); + assert_eq!(shell_word(""), "''"); + assert_eq!(shell_word("it's"), "'it'\"'\"'s'"); + } + + #[test] + fn long_commands_wrap_at_88_columns() { + let line: Vec = std::iter::once("opencode".to_string()) + .chain((0..12).map(|index| format!("--flag-{index:02}"))) + .collect(); + let lines = wrap_command(&line); + assert_eq!( + lines[0], + " $ opencode --flag-00 --flag-01 --flag-02 --flag-03 --flag-04 --flag-05 --flag-06 \\" + ); + assert_eq!( + lines[1], + " --flag-07 --flag-08 --flag-09 --flag-10 --flag-11" + ); + } + + #[test] + fn humanize_capitalizes_the_first_word() { + assert_eq!( + humanize("dangerously-skip-permissions"), + "Dangerously skip permissions" + ); + assert_eq!(humanize("sessionID"), "SessionID"); + assert_eq!( + humanize("operation | method path"), + "Operation | method path" + ); + assert_eq!(humanize("--"), "--"); + } + + // The wizard reads Effect's param metadata from the clap tree; the TypeScript dump has the real values. + #[test] + fn params_match_the_typescript_metadata() { + let fixture: Value = + serde_json::from_str(include_str!("../tests/fixtures/commands.json")).unwrap(); + let command = help::command(); + let mut checked = 0; + walk(&fixture["root"], &command, &mut checked); + assert!(checked > 60, "checked {checked} params"); + } + + fn walk(ts: &Value, node: &clap::Command, checked: &mut usize) { + let path = node.get_name(); + let names: Vec = flags(node).iter().map(|flag| flag.name.clone()).collect(); + let expected: Vec = ts["flags"] + .as_array() + .unwrap() + .iter() + .map(|flag| flag["name"].as_str().unwrap().to_string()) + .collect(); + assert_eq!(names, expected, "{path}: flag order"); + for (flag, ts) in flags(node).iter().zip(ts["flags"].as_array().unwrap()) { + check(path, flag, ts); + *checked += 1; + } + let arguments: Vec = node.get_positionals().map(|arg| param(node, arg)).collect(); + for (argument, ts) in arguments.iter().zip(ts["arguments"].as_array().unwrap()) { + check(path, argument, ts); + *checked += 1; + } + for (ts, sub) in ts["commands"] + .as_array() + .unwrap() + .iter() + .zip(node.get_subcommands()) + { + walk(ts, sub, checked); + } + } + + fn check(path: &str, param: &Param, ts: &Value) { + let what = format!("{path} {}", param.name); + assert_eq!(param.name, ts["name"].as_str().unwrap(), "{what}: name"); + let kind = match ¶m.kind { + Kind::Boolean => "Boolean", + Kind::Choice(_) => "Choice", + Kind::Int => "Int", + Kind::Text => "String", + }; + let expected = match ts["type"].as_str().unwrap() { + "KeyValuePair" | "name" => "String", + kind => kind, + }; + assert_eq!(kind, expected, "{what}: type"); + let repeated = ts["repeated"] + .as_bool() + .or(ts["variadic"].as_bool()) + .unwrap(); + let variadic = repeated.then(|| (ts["min"].as_i64().unwrap_or(0), ts["max"].as_i64())); + assert_eq!(param.variadic, variadic, "{what}: count bounds"); + // The dump calls a repeatable flag optional when it parses to `[]` without input; Effect's metadata does not. + let optional = + ts["optional"].as_bool().unwrap() && !(repeated && ts["type"] != "KeyValuePair"); + assert_eq!(param.optional, optional, "{what}: optional"); + } } diff --git a/packages/cli-rs/crates/cli/src/wizard/prompt.rs b/packages/cli-rs/crates/cli/src/wizard/prompt.rs new file mode 100644 index 00000000000..5f073781d6c --- /dev/null +++ b/packages/cli-rs/crates/cli/src/wizard/prompt.rs @@ -0,0 +1,814 @@ +//! The prompts of Effect CLI (`effect/src/cli/Prompt.ts`) that the wizard uses: select, confirm, toggle, +//! integer, and text. They look different from the Clack prompts in `crate::prompt`, whose raw mode and key +//! decoding they share. + +use std::io::Write; +use std::sync::OnceLock; + +use crate::prompt::{self, Keys, Press}; + +/// Esc, Ctrl+C, or Ctrl+D ended the input (`Terminal.QuitError`). +#[derive(Debug)] +pub struct Quit; + +pub const RESET: &str = "\x1b[0m"; +pub const BOLD: &str = "\x1b[1m"; +const ITALIC: &str = "\x1b[3m"; +const UNDERLINE: &str = "\x1b[4m"; +pub const RED: &str = "\x1b[31m"; +pub const GREEN: &str = "\x1b[32m"; +pub const MAGENTA: &str = "\x1b[35m"; +pub const WHITE: &str = "\x1b[37m"; +pub const BLACK_BRIGHT: &str = "\x1b[90m"; +pub const CYAN_BRIGHT: &str = "\x1b[96m"; + +const SHOW: &str = "\x1b[?25h"; +const HIDE: &str = "\x1b[?25l"; +const SAVE: &str = "\x1b[s"; +const RESTORE: &str = "\x1b[u"; +const ERASE_LINE: &str = "\x1b[2K"; +const CURSOR_LEFT: &str = "\x1b[G"; +const BEEP: &str = "\x07"; + +// The default (non-Windows) theme. +const PREFIX: &str = "?"; +const ARROW_UP: &str = "↑"; +const ARROW_DOWN: &str = "↓"; +const TICK: &str = "✔"; +const ELLIPSIS: &str = "…"; +const POINTER_SMALL: &str = "›"; +const POINTER: &str = "❯"; +const DESCRIPTION_SEPARATOR: &str = "- "; +const TOGGLE_SEPARATOR: &str = "/"; +const PRIMARY: &str = CYAN_BRIGHT; +const MUTED: &str = BLACK_BRIGHT; +const SUCCESS: &str = GREEN; +const ERROR: &str = RED; +const SUBMITTED: &str = WHITE; + +/// `Ansi.detectColors`: stdout is a terminal and `NO_COLOR` is unset or empty. +pub fn colors() -> bool { + static COLORS: OnceLock = OnceLock::new(); + *COLORS.get_or_init(|| { + use std::io::IsTerminal; + std::io::stdout().is_terminal() + && std::env::var_os("NO_COLOR").is_none_or(|value| value.is_empty()) + }) +} + +/// `Ansi.annotate`: the styles, the text, and a reset, or the text alone without colors. +pub fn annotate(text: &str, styles: &[&str]) -> String { + match colors() { + true => format!("{}{text}{RESET}", styles.concat()), + false => text.to_string(), + } +} + +/// `Console.log`. +pub fn log(text: &str) { + write(&format!("{text}\n")); +} + +fn write(text: &str) { + let mut stdout = std::io::stdout().lock(); + let _ = stdout + .write_all(text.as_bytes()) + .and_then(|()| stdout.flush()); +} + +fn columns() -> usize { + prompt::stdout_size().1.unwrap_or(0) +} + +/// JavaScript's `length`, in UTF-16 units. +fn length(text: &str) -> usize { + text.encode_utf16().count() +} + +fn symbol(symbol: &str, styles: &[&str]) -> String { + match symbol.is_empty() { + true => String::new(), + false => annotate(symbol, styles), + } +} + +fn separate(symbol: &str, text: &str) -> String { + match symbol.is_empty() { + true => text.to_string(), + false => format!("{symbol} {text}"), + } +} + +/// `renderPrompt`: the symbol, the message, the trailing symbol, and the value, on one line. +fn render_prompt(value: &str, message: &str, leading: &str, trailing: &str, plain: bool) -> String { + let lines: Vec = message + .split('\n') + .map(|line| line.strip_suffix('\r').unwrap_or(line)) + .map(|line| match plain { + true => line.to_string(), + false => annotate(line, &[BOLD]), + }) + .collect(); + let mut output = match leading.is_empty() { + true => String::new(), + false => format!("{leading} "), + }; + output += &lines.join("\n"); + if !trailing.is_empty() { + output += &format!(" {trailing}"); + } + if !value.is_empty() { + output += &format!(" {value}"); + } else if !trailing.is_empty() { + output += " "; + } + output +} + +fn active_symbols() -> (String, String) { + (symbol(PREFIX, &[PRIMARY]), symbol(POINTER_SMALL, &[MUTED])) +} + +fn submitted_symbols() -> (String, String) { + (symbol(TICK, &[SUCCESS]), symbol(ELLIPSIS, &[MUTED])) +} + +/// `eraseText`: erases the rows `text` takes. +fn erase_text(text: &str, columns: usize) -> String { + if columns == 0 { + return format!("{ERASE_LINE}\x1b[1G"); + } + let rows: usize = text + .split('\n') + .map(|line| 1 + length(line).saturating_sub(1) / columns) + .sum(); + erase_lines(rows) +} + +fn erase_lines(rows: usize) -> String { + let mut command = String::new(); + for index in 0..rows { + command += ERASE_LINE; + if index + 1 < rows { + command += "\x1b[1A"; + } + } + if rows > 0 { + command += CURSOR_LEFT; + } + command +} + +fn lines(text: &str, columns: usize) -> usize { + match columns { + 0 => text.split('\n').count(), + _ => text + .split('\n') + .map(|line| length(line).div_ceil(columns)) + .sum(), + } +} + +fn clear_with_error(output: &str, columns: usize, error: &str) -> String { + if error.is_empty() { + return erase_text(output, columns); + } + format!( + "\x1b[{}B{}{}", + lines(error, columns), + erase_text(&format!("\n{error}"), columns), + erase_text(output, columns) + ) +} + +fn render_error(error: Option<&str>, plain: bool) -> String { + let Some(error) = error else { + return String::new(); + }; + let lines: Vec<&str> = error.split('\n').collect(); + if plain { + return separate(POINTER_SMALL, &lines.join("\n")); + } + let lines: Vec = lines + .iter() + .map(|line| annotate(line, &[ITALIC, ERROR])) + .collect(); + format!( + "{SAVE}\n{}{RESTORE}", + separate(&symbol(POINTER_SMALL, &[ERROR]), &lines.join("\n")) + ) +} + +enum Action { + Beep, + Next(S), + Submit(O), +} + +trait Prompt { + type State: Clone; + type Output; + fn next(&self, state: &Self::State) -> String; + fn submitted(&self, state: &Self::State, value: &Self::Output) -> String; + fn process(&self, press: &Press, state: &Self::State) -> Action; + fn clear(&self, state: &Self::State, columns: usize) -> String; +} + +/// `runLoop`: draws a frame, reads a key, and acts on it, until a submit or the end of input. +fn run(prompt: &P, initial: P::State) -> Result { + let result = prompt::with_keys(|keys: &mut Keys| { + let mut state = initial; + write(&prompt.next(&state)); + loop { + let press = keys.next().ok_or(Quit)?; + match prompt.process(&press, &state) { + Action::Beep => write(BEEP), + Action::Next(next) => { + let clear = prompt.clear(&state, columns()); + state = next; + write(&(clear + &prompt.next(&state))); + } + Action::Submit(value) => { + let clear = prompt.clear(&state, columns()); + write(&(clear + &prompt.submitted(&state, &value))); + // Each prompt reads from a queue of its own, which goes away with the keys left in it. + keys.discard(); + return Ok(value); + } + } + // NodeTerminal ends the input after delivering a quit key. + let key = &press.key; + if key.is("escape") || (key.ctrl && (key.is("c") || key.is("d"))) { + return Err(Quit); + } + } + }); + write(SHOW); + result +} + +fn name(press: &Press) -> &str { + press.key.name.as_deref().unwrap_or("") +} + +fn input(press: &Press) -> &str { + press.char.as_deref().unwrap_or("") +} + +pub struct Select { + pub message: String, + /// The titles and their descriptions. + pub choices: Vec<(String, Option)>, +} + +const MAX_PER_PAGE: usize = 10; + +impl Select { + /// The index of the chosen choice. + pub fn prompt(&self) -> Result { + run(self, 0) + } + + fn header(&self, leading: &str, trailing: &str, plain: bool) -> String { + render_prompt("", &self.message, leading, trailing, plain) + } + + fn choices(&self, cursor: usize, plain: bool) -> String { + let total = self.choices.len(); + let (start, end) = entries_to_display(cursor, total, MAX_PER_PAGE); + (start..end) + .map(|index| { + let paging = match index { + _ if index == start && start > 0 => ARROW_UP, + _ if index + 1 == end && end < total => ARROW_DOWN, + _ => " ", + }; + let selected = index == cursor; + let prefix = match (selected, plain) { + (true, true) => format!("{POINTER}{paging}"), + (true, false) => format!("{}{paging}", symbol(POINTER, &[PRIMARY])), + (false, _) => format!("{paging} "), + }; + let (title, description) = &self.choices[index]; + let title = match selected && !plain { + true => annotate(title, &[UNDERLINE, PRIMARY]), + false => title.clone(), + }; + let description = match description { + Some(description) if selected => { + let text = format!("{DESCRIPTION_SEPARATOR}{description}"); + match plain { + true => text, + false => annotate(&text, &[MUTED]), + } + } + _ => String::new(), + }; + format!("{prefix}{title} {description}") + }) + .collect::>() + .join("\n") + } +} + +impl Prompt for Select { + type State = usize; + type Output = usize; + + fn next(&self, state: &usize) -> String { + let (leading, trailing) = active_symbols(); + format!( + "{HIDE}{}\n{}", + self.header(&leading, &trailing, false), + self.choices(*state, false) + ) + } + + fn submitted(&self, state: &usize, _: &usize) -> String { + let (leading, trailing) = submitted_symbols(); + format!( + "{} {}\n", + self.header(&leading, &trailing, false), + annotate(&self.choices[*state].0, &[SUBMITTED]) + ) + } + + fn process(&self, press: &Press, state: &usize) -> Action { + let total = self.choices.len(); + match name(press) { + "k" | "up" => Action::Next(if *state == 0 { total - 1 } else { state - 1 }), + "j" | "down" => Action::Next(if *state + 1 == total { 0 } else { state + 1 }), + "tab" => Action::Next((state + 1) % total), + "enter" | "return" => Action::Submit(*state), + _ => Action::Beep, + } + } + + fn clear(&self, state: &usize, columns: usize) -> String { + let text = format!( + "{}\n{}", + self.header(PREFIX, POINTER_SMALL, true), + self.choices(*state, true) + ); + erase_text(&text, columns) + ERASE_LINE + CURSOR_LEFT + } +} + +fn entries_to_display(cursor: usize, total: usize, max: usize) -> (usize, usize) { + let start = (total as i64 - max as i64) + .min(cursor as i64 - (max / 2) as i64) + .max(0) as usize; + (start, (start + max).min(total)) +} + +pub struct Confirm { + pub message: String, + pub labels: (&'static str, &'static str), + pub placeholders: (&'static str, &'static str), +} + +impl Confirm { + /// `Confirm` with its default labels and `initial: false`. + pub fn new(message: String) -> Confirm { + Confirm { + message, + labels: ("yes", "no"), + placeholders: ("(Y/n)", "(y/N)"), + } + } + + pub fn prompt(&self) -> Result { + run(self, false) + } +} + +impl Prompt for Confirm { + type State = bool; + type Output = bool; + + fn next(&self, state: &bool) -> String { + let (leading, trailing) = active_symbols(); + let placeholder = if *state { + self.placeholders.0 + } else { + self.placeholders.1 + }; + let value = annotate(placeholder, &[MUTED]); + format!( + "{HIDE}{}", + render_prompt(&value, &self.message, &leading, &trailing, false) + ) + } + + fn submitted(&self, _: &bool, value: &bool) -> String { + let (leading, trailing) = submitted_symbols(); + let label = if *value { self.labels.0 } else { self.labels.1 }; + render_prompt(label, &self.message, &leading, &trailing, false) + "\n" + } + + fn process(&self, press: &Press, state: &bool) -> Action { + let value = input(press).to_lowercase(); + match name(press) { + "enter" | "return" => Action::Submit(*state), + // /^y|t$/ and /^n|f$/. + _ if value.starts_with('y') || value.ends_with('t') => Action::Submit(true), + _ if value.starts_with('n') || value.ends_with('f') => Action::Submit(false), + _ => Action::Beep, + } + } + + fn clear(&self, state: &bool, columns: usize) -> String { + let placeholder = if *state { + self.placeholders.0 + } else { + self.placeholders.1 + }; + let text = render_prompt(placeholder, &self.message, PREFIX, POINTER_SMALL, true); + erase_text(&text, columns) + ERASE_LINE + CURSOR_LEFT + } +} + +pub struct Toggle { + pub message: String, + pub active: &'static str, + pub inactive: &'static str, +} + +impl Toggle { + /// Starts on the active value. + pub fn prompt(&self) -> Result { + run(self, true) + } + + fn toggle(&self, value: bool, submitted: bool) -> String { + let separator = symbol(TOGGLE_SEPARATOR, &[MUTED]); + let selected = [UNDERLINE, if submitted { SUBMITTED } else { PRIMARY }]; + let (active, inactive) = match value { + true => (annotate(self.active, &selected), self.inactive.to_string()), + false => (self.active.to_string(), annotate(self.inactive, &selected)), + }; + format!("{active} {}", separate(&separator, &inactive)) + } +} + +impl Prompt for Toggle { + type State = bool; + type Output = bool; + + fn next(&self, state: &bool) -> String { + let (leading, trailing) = active_symbols(); + let toggle = self.toggle(*state, false); + format!( + "{HIDE}{}", + render_prompt(&toggle, &self.message, &leading, &trailing, false) + ) + } + + fn submitted(&self, state: &bool, _: &bool) -> String { + let (leading, trailing) = submitted_symbols(); + render_prompt( + &self.toggle(*state, true), + &self.message, + &leading, + &trailing, + false, + ) + "\n" + } + + fn process(&self, press: &Press, state: &bool) -> Action { + // Node names the space key "space", so Effect's `" "` case never matches. + match name(press) { + "0" | "j" | "delete" | "right" | "down" => Action::Next(false), + "1" | "k" | "left" | "up" => Action::Next(true), + "tab" => Action::Next(!state), + "enter" | "return" => Action::Submit(*state), + _ => Action::Beep, + } + } + + fn clear(&self, _: &bool, columns: usize) -> String { + let toggle = format!( + "{} {}", + self.active, + separate(TOGGLE_SEPARATOR, self.inactive) + ); + let text = render_prompt(&toggle, &self.message, PREFIX, POINTER_SMALL, true); + erase_text(&text, columns) + ERASE_LINE + CURSOR_LEFT + } +} + +#[derive(Clone)] +struct Field { + cursor: usize, + value: String, + error: Option, +} + +impl Field { + fn new(value: String) -> Field { + Field { + cursor: value.chars().count(), + value, + error: None, + } + } + + fn with(&self, value: String) -> Field { + Field { + value, + error: None, + ..self.clone() + } + } +} + +pub struct Int { + pub message: String, + pub default: Option, + pub min: Option, + pub max: Option, +} + +impl Int { + pub fn prompt(&self) -> Result { + let initial = self + .default + .map(|value| value.to_string()) + .unwrap_or_default(); + run(self, Field::new(initial)) + } + + fn output( + &self, + state: &Field, + leading: &str, + trailing: &str, + plain: bool, + submitted: bool, + ) -> String { + let value = match submitted || plain { + true => state.value.clone(), + false if state.error.is_some() => annotate(&state.value, &[ERROR]), + false => annotate(&state.value, &[UNDERLINE, PRIMARY]), + }; + render_prompt(&value, &self.message, leading, trailing, plain) + } +} + +impl Prompt for Int { + type State = Field; + type Output = i64; + + fn next(&self, state: &Field) -> String { + let (leading, trailing) = active_symbols(); + self.output(state, &leading, &trailing, false, false) + + &render_error(state.error.as_deref(), false) + } + + fn submitted(&self, state: &Field, _: &i64) -> String { + let (leading, trailing) = submitted_symbols(); + self.output(state, &leading, &trailing, false, true) + "\n" + } + + fn process(&self, press: &Press, state: &Field) -> Action { + if press.key.ctrl && press.key.is("u") { + return Action::Next(Field::new(String::new())); + } + match name(press) { + "backspace" => match state.value.is_empty() { + true => Action::Beep, + false => { + let mut value = state.value.clone(); + value.pop(); + Action::Next(state.with(value)) + } + }, + "k" | "up" => Action::Next(state.with(match state.value.as_str() { + "" | "-" => "1".into(), + value => (parse_int(value).unwrap_or(0) + 1).to_string(), + })), + "j" | "down" => Action::Next(state.with(match state.value.as_str() { + "" | "-" => "-1".into(), + value => (parse_int(value).unwrap_or(0) - 1).to_string(), + })), + "enter" | "return" => { + let Some(value) = parse_int(&state.value) else { + return Action::Next(Field { + error: Some("Must provide an integer value".into()), + ..state.clone() + }); + }; + let error = match (self.min, self.max) { + (Some(min), _) if value < min => { + Some(format!("{value} must be greater than or equal to {min}")) + } + (_, Some(max)) if value > max => { + Some(format!("{value} must be less than or equal to {max}")) + } + _ => None, + }; + match error { + Some(error) => Action::Next(Field { + error: Some(error), + ..state.clone() + }), + None => Action::Submit(value), + } + } + _ => { + let input = input(press); + if state.value.is_empty() && input == "-" { + return Action::Next(state.with("-".into())); + } + match parse_int(&format!("{}{input}", state.value)) { + Some(value) => Action::Next(state.with(value.to_string())), + None => Action::Beep, + } + } + } + } + + fn clear(&self, state: &Field, columns: usize) -> String { + let error = render_error(state.error.as_deref(), true); + let output = self.output(state, PREFIX, POINTER_SMALL, true, false); + clear_with_error(&output, columns, &error) + ERASE_LINE + CURSOR_LEFT + } +} + +/// JavaScript's `parseInt(text)`: optional whitespace and sign, then the leading digits. +fn parse_int(text: &str) -> Option { + let text = text.trim_start(); + let (negative, rest) = match text.as_bytes().first() { + Some(b'-') => (true, &text[1..]), + Some(b'+') => (false, &text[1..]), + _ => (false, text), + }; + let digits: String = rest.chars().take_while(char::is_ascii_digit).collect(); + let value = digits.parse::().ok()?; + Some(if negative { -value } else { value }) +} + +pub struct Text { + pub message: String, +} + +impl Text { + pub fn prompt(&self) -> Result { + run(self, Field::new(String::new())) + } + + fn output( + &self, + state: &Field, + leading: &str, + trailing: &str, + plain: bool, + submitted: bool, + ) -> String { + let value = match plain || state.value.is_empty() { + true => state.value.clone(), + false if state.error.is_some() => annotate(&state.value, &[ERROR]), + false if submitted => annotate(&state.value, &[SUBMITTED]), + false => annotate(&state.value, &[UNDERLINE, PRIMARY]), + }; + render_prompt(&value, &self.message, leading, trailing, plain) + } +} + +impl Prompt for Text { + type State = Field; + type Output = String; + + fn next(&self, state: &Field) -> String { + let (leading, trailing) = active_symbols(); + let offset = state.cursor as i64 - state.value.chars().count() as i64; + let moved = match offset { + 0 => String::new(), + offset if offset > 0 => format!("\x1b[{offset}C"), + offset => format!("\x1b[{}D", -offset), + }; + self.output(state, &leading, &trailing, false, false) + + &render_error(state.error.as_deref(), false) + + &moved + } + + fn submitted(&self, state: &Field, _: &String) -> String { + let (leading, trailing) = submitted_symbols(); + self.output(state, &leading, &trailing, false, true) + "\n" + } + + fn process(&self, press: &Press, state: &Field) -> Action { + let at = |field: &Field, cursor: usize| Field { + cursor, + error: None, + ..field.clone() + }; + let length = state.value.chars().count(); + if press.key.ctrl { + return match name(press) { + "u" => Action::Next(Field::new(String::new())), + "a" => Action::Next(at(state, 0)), + "e" => Action::Next(at(state, length)), + _ => Action::Beep, + }; + } + match name(press) { + "backspace" => match state.cursor { + 0 => Action::Beep, + cursor => { + let mut chars: Vec = state.value.chars().collect(); + chars.remove(cursor - 1); + Action::Next(Field { + cursor: cursor - 1, + value: chars.into_iter().collect(), + error: None, + }) + } + }, + "left" => match state.cursor { + 0 => Action::Beep, + cursor => Action::Next(at(state, cursor - 1)), + }, + "right" => match state.cursor >= length { + true => Action::Beep, + false => Action::Next(at(state, state.cursor + 1)), + }, + "home" => Action::Next(at(state, 0)), + "end" => Action::Next(at(state, length)), + "enter" | "return" => Action::Submit(state.value.clone()), + // The default value is "", so Tab only redraws a non-empty value. + "tab" => match state.value.is_empty() { + true => Action::Beep, + false => Action::Next(at(state, length)), + }, + _ => { + let input = input(press); + let before: String = state.value.chars().take(state.cursor).collect(); + let after: String = state.value.chars().skip(state.cursor).collect(); + Action::Next(Field { + cursor: state.cursor + input.chars().count(), + value: format!("{before}{input}{after}"), + error: None, + }) + } + } + } + + fn clear(&self, state: &Field, columns: usize) -> String { + let error = render_error(state.error.as_deref(), true); + let output = self.output(state, PREFIX, POINTER_SMALL, true, false); + clear_with_error(&output, columns, &error) + ERASE_LINE + CURSOR_LEFT + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_int_reads_like_javascript() { + let cases = [ + ("", None), + ("-", None), + ("--1", None), + ("a", None), + ("05", Some(5)), + ("5a", Some(5)), + ("-12", Some(-12)), + (" 7", Some(7)), + ("+3", Some(3)), + ]; + for (text, expected) in cases { + assert_eq!(parse_int(text), expected, "parseInt({text:?})"); + } + } + + #[test] + fn select_pages_like_effect() { + // entriesToDisplay(cursor, total, 10) + let cases = [ + (0, 3, (0, 3)), + (0, 12, (0, 10)), + (5, 12, (0, 10)), + (6, 12, (1, 11)), + (11, 12, (2, 12)), + ]; + for (cursor, total, expected) in cases { + assert_eq!( + entries_to_display(cursor, total, 10), + expected, + "cursor {cursor} of {total}" + ); + } + } + + #[test] + fn erase_counts_wrapped_rows() { + assert_eq!(erase_text("abc", 0), "\x1b[2K\x1b[1G"); + assert_eq!( + erase_text("abcd\nx", 2), + "\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[G" + ); + assert_eq!(lines("abc\n\nx", 2), 3); + } +} diff --git a/packages/cli-rs/docs/C.0.md b/packages/cli-rs/docs/C.0.md index d76d020cfe6..d97ab8f218e 100644 --- a/packages/cli-rs/docs/C.0.md +++ b/packages/cli-rs/docs/C.0.md @@ -50,4 +50,5 @@ reports the errors above. It leaves every other token alone. - Parse errors go to stderr and exit 1, as in the TypeScript CLI (clap exits 2 by default). - Handler errors print to stderr and exit 1. Handlers that are not built yet say so and exit 1. - Writes to stdout ignore a closed pipe (EPIPE), like `packages/cli/src/node/index.ts:4-7`. -- `--wizard` is accepted and reports that it is not supported yet (O-11). +- `--wizard` runs Effect CLI's command wizard (`src/wizard.rs`, step C.15). Required arguments are not + checked on a line with `--wizard`, so the wizard can ask for them. diff --git a/packages/cli-rs/parity/deviations/C40-handler-errors.md b/packages/cli-rs/parity/deviations/C40-handler-errors.md index bdc78bd80d3..37928c2f149 100644 --- a/packages/cli-rs/parity/deviations/C40-handler-errors.md +++ b/packages/cli-rs/parity/deviations/C40-handler-errors.md @@ -26,3 +26,10 @@ an OpenAPI document that does not load, a request that cannot be sent), TS print `UnknownError: An error occurred in Effect.tryPromise` and keeps the real message in the `[cause]` below the stack. Rust prints the real message: `Error: Operation not found: `. P-CLI compares the exit code and the requests of those cases, not stderr. + +`--wizard` (G15) parses each param after its prompts. A value that fails (`session list --wizard` with a +max count of 0) escapes in TS as `~effect/cli/CliError/InvalidValue: Invalid value for flag --max-count: "0". +Expected: Schema validation failed: Expected a value greater than or equal to 1` with a stack trace, exit 1. +Rust prints `Error: Invalid value for flag --max-count: "0". Expected: 0 is not in 1..=4294967295` (the +reason is clap's), exit 1. P-PTY compares the screens before the error and the exit code +(`C.15/invalid`). diff --git a/packages/cli-rs/parity/deviations/G10-usage-errors.md b/packages/cli-rs/parity/deviations/G10-usage-errors.md index c57da5bf533..4fae7729fa3 100644 --- a/packages/cli-rs/parity/deviations/G10-usage-errors.md +++ b/packages/cli-rs/parity/deviations/G10-usage-errors.md @@ -9,7 +9,8 @@ Rust: a usage error prints the message and a short usage line to stderr, then ex Messages for the rules `args::normalize` and `args::validate` keep (`2 occurrences`, `omit the value`, `Unrecognized flag: --x in command ...`, `key=value`) use the TypeScript wording. Other errors (unknown flag, missing argument, invalid choice or number, a repeated value flag) use clap's wording and suggestions. A parse -error wins over an action flag, and `--version false` does not print the version. +error wins over an action flag, and `--version false` does not print the version. The exception is a missing +required argument next to `--wizard`, which the wizard then asks for (`session delete --wizard`), as in TS. Reason: the layout of help and errors may differ (Q12 b). The exit code and the stream of the error are the same, which is what scripts check. The action-flag cases need a malformed line and are not worth a second diff --git a/packages/cli-rs/parity/deviations/G15-wizard.md b/packages/cli-rs/parity/deviations/G15-wizard.md deleted file mode 100644 index 1abcff553c4..00000000000 --- a/packages/cli-rs/parity/deviations/G15-wizard.md +++ /dev/null @@ -1,9 +0,0 @@ -# G15: `--wizard` - -TypeScript: `--wizard` on any command walks through its arguments and flags with prompts, prints the resulting -command line, and runs it after confirmation. - -Rust: `--wizard` is accepted on every command and exits 1 with "--wizard is not supported yet (plan step -C.15)". - -Reason: orchestrator decision O-11 defers the wizard to C.15, which needs the C.p prompt kit.