Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
181 changes: 180 additions & 1 deletion pkgs/id/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,10 +82,11 @@
//! - **Stdout output**: `-` as output path, `--stdout` flag, or `cat` command
//! - **Renaming**: Use `source:dest` syntax for any path argument

use std::ffi::OsString;
use std::net::SocketAddr;
use std::path::PathBuf;

use clap::{Args, Parser, Subcommand, ValueEnum};
use clap::{Args, CommandFactory, Parser, Subcommand, ValueEnum};

use crate::groups::Role;
use crate::groups::policy::Delegation;
Expand Down Expand Up @@ -196,6 +197,93 @@ pub struct Cli {
/// Each variant represents a distinct operation mode for the `id` tool.
/// Commands are organized by their primary function: storage, retrieval,
/// search, or system operations.
/// Names and aliases of the top-level subcommands, taken from the clap
/// definition itself so the list can never drift from the real parser.
fn top_level_subcommand_names() -> std::collections::HashSet<String> {
let command = Cli::command();
let mut names = std::collections::HashSet::new();
for sub in command.get_subcommands() {
names.insert(sub.get_name().to_owned());
names.extend(sub.get_aliases().map(str::to_owned));
names.extend(sub.get_visible_aliases().map(str::to_owned));
}
names
}

/// Rewrite raw argv so the space form of `--new` never swallows a
/// subcommand as the instance name (#3144).
///
/// `--new` takes an optional value (`num_args = 0..=1`), so clap greedily
/// consumes the next token: the documented `id --new serve` parsed as
/// instance name `serve` with no subcommand, created `.iroh/serve/`, and
/// started the REPL. When the token after a bare `--new` is a top-level
/// subcommand name (and no subcommand has been seen yet), rewrite that
/// `--new` to `--new=` — the empty value still means "random name", and
/// the token is then parsed as the subcommand. Every other form is
/// passed through untouched: bare `--new`, `--new=<name>`, `--new <name>
/// <command>`, and a trailing `--new` after the subcommand.
pub fn normalize_args<I, T>(args: I) -> Vec<OsString>
where
I: IntoIterator<Item = T>,
T: Into<OsString>,
{
// Global options that take a separate value token: the token after
// one of these is a value even when it spells a subcommand name.
const VALUE_FLAGS: [&str; 5] = [
"--log-level",
"--data-dir",
"-d",
"--groups-log",
"--event-store",
];
let subcommands = top_level_subcommand_names();
let raw: Vec<OsString> = args.into_iter().map(Into::into).collect();
let mut out: Vec<OsString> = Vec::with_capacity(raw.len());
let mut seen_subcommand = false;
let mut expect_value = false;
let mut iter = raw.into_iter().peekable();
// The first token is the program name; copy it verbatim.
if let Some(prog) = iter.next() {
out.push(prog);
}
while let Some(arg) = iter.next() {
if expect_value {
out.push(arg);
expect_value = false;
continue;
}
let text = arg.to_str().map(str::to_owned);
if !seen_subcommand && text.as_deref() == Some("--new") {
match iter.peek().and_then(|next| next.to_str()) {
Some(next) if subcommands.contains(next) => {
out.push(OsString::from("--new="));
}
_ => {
// The next token (if any) is the instance name; do
// not mistake it for a subcommand on the next pass.
out.push(arg);
expect_value = true;
}
}
continue;
}
out.push(arg);
if seen_subcommand {
continue;
}
match text.as_deref() {
// After `--`, every token is a positional value.
Some("--") => seen_subcommand = true,
Some(name) if VALUE_FLAGS.contains(&name) => expect_value = true,
Some(name) if !name.starts_with('-') && subcommands.contains(name) => {
seen_subcommand = true;
}
_ => {}
}
}
out
}

/// Parses a result limit (`--first` / `--last` / peek `--lines`): zero is
/// rejected with a clear error instead of silently producing an empty result
/// or a header-only preview (#3059). Clap names the flag in its error prefix,
Expand Down Expand Up @@ -2387,6 +2475,97 @@ mod tests {
assert!(cli.log_level.is_none());
}

/// Parse via `normalize_args` on a big-stack thread: building this
/// CLI's clap tree is deep enough to overflow the default test
/// thread stack (the #3059 parse tests below spawn a thread for the
/// same reason).
fn parse_normalized(args: &[&str]) -> Cli {
let owned: Vec<OsString> = args.iter().map(OsString::from).collect();
std::thread::Builder::new()
.stack_size(32 * 1024 * 1024)
.spawn(move || Cli::parse_from(normalize_args(owned)))
.unwrap()
.join()
.unwrap()
}

#[test]
fn test_cli_parse_new_space_form_subcommand_not_swallowed() {
// #3144: `id --new serve` must run serve under a random instance
// name, not create an instance literally named "serve".
let cli = parse_normalized(&["id", "--new", "serve"]);
assert_eq!(cli.new.as_deref(), Some(""));
assert!(matches!(cli.command, Some(Command::Serve { .. })));

let cli = parse_normalized(&["id", "--new", "id"]);
assert_eq!(cli.new.as_deref(), Some(""));
assert!(matches!(cli.command, Some(Command::Id { .. })));

let cli = parse_normalized(&["id", "--new", "list"]);
assert_eq!(cli.new.as_deref(), Some(""));
assert!(matches!(cli.command, Some(Command::List { .. })));
}

#[test]
fn test_cli_parse_new_forms_preserved() {
// Named space form: the name is kept and the subcommand still runs.
let cli = parse_normalized(&["id", "--new", "my-dev", "list"]);
assert_eq!(cli.new.as_deref(), Some("my-dev"));
assert!(matches!(cli.command, Some(Command::List { .. })));

// Bare --new: random name, no subcommand.
let cli = parse_normalized(&["id", "--new"]);
assert_eq!(cli.new.as_deref(), Some(""));
assert!(cli.command.is_none());

// Equals form is passed through untouched, even when the name
// spells a subcommand.
let cli = parse_normalized(&["id", "--new=serve", "list"]);
assert_eq!(cli.new.as_deref(), Some("serve"));
assert!(matches!(cli.command, Some(Command::List { .. })));

// Trailing --new after the subcommand keeps working.
let cli = parse_normalized(&["id", "list", "--new"]);
assert_eq!(cli.new.as_deref(), Some(""));
assert!(matches!(cli.command, Some(Command::List { .. })));
}

#[test]
fn test_normalize_args_rewrites_only_the_ambiguous_form() {
// Same big-stack thread as parse_normalized: collecting the
// subcommand names builds the clap tree.
let (rewritten, flag_value) = std::thread::Builder::new()
.stack_size(32 * 1024 * 1024)
.spawn(|| {
(
normalize_args(["id", "--new", "serve"]),
normalize_args(["id", "--log-level", "list", "--new", "id"]),
)
})
.unwrap()
.join()
.unwrap();
assert_eq!(
rewritten,
vec![
OsString::from("id"),
OsString::from("--new="),
OsString::from("serve")
]
);
// A global flag value that spells a subcommand is not a subcommand.
assert_eq!(
flag_value,
vec![
OsString::from("id"),
OsString::from("--log-level"),
OsString::from("list"),
OsString::from("--new="),
OsString::from("id")
]
);
}

#[test]
fn test_cli_parse_debug_flag() {
let cli = Cli::parse_from(["id", "--debug"]);
Expand Down
2 changes: 1 addition & 1 deletion pkgs/id/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ const NOISY_MODULE_FILTERS: &[&str] = &[
#[tokio::main]
async fn main() -> Result<()> {
// Parse CLI first so we can use flags for logging configuration
let cli = Cli::parse();
let cli = Cli::parse_from(id::cli::normalize_args(std::env::args_os()));

// Switch to the data directory if specified.
// All data paths (.iroh-store, .iroh-key, .iroh-serve.lock) are CWD-relative,
Expand Down
66 changes: 66 additions & 0 deletions pkgs/id/tests/cli_integration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3848,6 +3848,72 @@ mod serve_tests {
);
}

/// Test that space-form `--new <subcommand>` does not swallow the
/// subcommand as the instance name (#3144): `id --new id` must run the
/// `id` subcommand under a randomly-named instance, like `--new= id`.
#[test]
fn test_new_flag_space_form_subcommand_not_swallowed() {
let tmp = TempDir::new().unwrap();

let output = run_cmd(&["--new", "id"], tmp.path());
assert!(
output.status.success(),
"id --new id should succeed. stderr: {}",
String::from_utf8_lossy(&output.stderr)
);

let iroh_dir = tmp.path().join(".iroh");
assert!(iroh_dir.exists(), ".iroh/ directory should be created");
assert!(
!iroh_dir.join("id").exists(),
"the subcommand token must not become the instance directory"
);

let entries: Vec<_> = fs::read_dir(&iroh_dir)
.unwrap()
.filter_map(Result::ok)
.collect();
assert_eq!(
entries.len(),
1,
"Should have exactly one auto-generated subdirectory"
);
let name = entries[0].file_name().to_string_lossy().to_string();
assert_eq!(name.len(), 8, "Auto-generated name should be 8 chars");
assert!(
name.chars().all(|c| c.is_ascii_hexdigit()),
"Auto-generated name should be hex: {name}"
);
assert!(
iroh_dir.join(&name).join(".iroh-key").exists(),
"Key file should be created in instance directory"
);
}

/// Test that space-form `--new <name> <subcommand>` still creates the
/// named instance and runs the subcommand (#3144 preserved form).
#[test]
fn test_new_flag_space_form_named() {
let tmp = TempDir::new().unwrap();

let output = run_cmd(&["--new", "space-dev", "id"], tmp.path());
assert!(
output.status.success(),
"id --new space-dev id should succeed. stderr: {}",
String::from_utf8_lossy(&output.stderr)
);

let instance_dir = tmp.path().join(".iroh").join("space-dev");
assert!(
instance_dir.exists(),
".iroh/space-dev/ should be created"
);
assert!(
instance_dir.join(".iroh-key").exists(),
"Key file should be in named instance directory"
);
}

/// Test that --new=NAME rejects a name that already has an existing directory.
#[test]
fn test_new_flag_duplicate_rejects() {
Expand Down
Loading