diff --git a/README.md b/README.md index 340d3c8a52..9422093d24 100644 --- a/README.md +++ b/README.md @@ -1393,9 +1393,11 @@ rocm uninstall [--yes] [--dry-run] `rocm uninstall` removes four categories of files that ROCm CLI manages on this computer: its binaries, configuration, data, and caches. It lists what it will do and asks `[y/N]` (default: no) before doing it. Use `--dry-run` to only list, -and `--yes` to skip the confirmation. Outside an interactive terminal, when there -is something to remove, it refuses with exit code 1 and removes nothing unless -you pass `--yes`. Each `--keep-*` flag skips the removal of one category: +and `--yes` to skip the confirmation. It does not create the folders it reports +on: with `--keep-binaries`, on a computer where ROCm CLI never ran, it says there +is nothing to remove. Outside an interactive terminal, when there is something +to remove, it refuses with exit code 1 and removes nothing unless you pass +`--yes`. Each `--keep-*` flag skips the removal of one category: - `--keep-binaries` keeps the installed ROCm CLI binaries. - `--keep-config` keeps your saved settings. diff --git a/apps/rocm/src/cli.rs b/apps/rocm/src/cli.rs index 50f3caa662..059212eafc 100644 --- a/apps/rocm/src/cli.rs +++ b/apps/rocm/src/cli.rs @@ -50,6 +50,9 @@ Commands marked [preview] work but are outside the Tech Preview's supported\n\ scope: treat them as unfinished and do not depend on their behaviour yet.\n\n\ Run `rocm --help` for details and examples on any command." )] +// No global flags, no subcommand aliases and no abbreviations: the logger gate in +// `logging::is_enabled_for` reads the subcommand as `argv[1]` and relies on that +// (guarded by `uninstall_stays_the_first_argument_the_logger_gate_reads`). pub(crate) struct Cli { #[command(subcommand)] pub(crate) command: Option, @@ -2093,6 +2096,42 @@ mod tests { assert_eq!(error.kind(), clap::error::ErrorKind::ValueValidation); } + /// `logging::is_enabled_for` decides that `rocm uninstall` skips the client + /// log by looking at the first raw argument. That is only right while the + /// subcommand is always `argv[1]`: a global flag in front of it, an alias + /// for `uninstall`, or an abbreviated name would start the logger again and + /// a dry run would list a `logs` folder it had just made. The e2e scenario + /// `uninstall-06` proves the behaviour; this fails earlier, naming the cause. + #[test] + fn uninstall_stays_the_first_argument_the_logger_gate_reads() { + let command = Cli::command(); + let global_args: Vec<_> = command + .get_arguments() + .map(|arg| arg.get_id().as_str()) + .filter(|id| !matches!(*id, "help" | "version")) + .collect(); + assert!( + global_args.is_empty(), + "a top-level argument {global_args:?} can come before the subcommand, so \ + logging::is_enabled_for no longer sees `uninstall` as the first argument" + ); + let aliased: Vec<_> = command + .get_subcommands() + .filter(|sub| sub.get_all_aliases().any(|alias| alias == "uninstall")) + .map(clap::Command::get_name) + .collect(); + assert!( + aliased.is_empty(), + "{aliased:?} answers to `uninstall`, which logging::is_enabled_for does not check" + ); + let uninstall = command + .find_subcommand("uninstall") + .expect("uninstall subcommand exists"); + assert_eq!(uninstall.get_all_aliases().count(), 0); + Cli::try_parse_from(["rocm", "uninstal"]) + .expect_err("an abbreviated subcommand name must not reach uninstall"); + } + #[test] fn update_rejects_zero_timeout_secs() { let error = Cli::try_parse_from(["rocm", "update", "--json", "--timeout-secs", "0"]) diff --git a/apps/rocm/src/logging.rs b/apps/rocm/src/logging.rs index d6f92624a6..b6174f5af1 100644 --- a/apps/rocm/src/logging.rs +++ b/apps/rocm/src/logging.rs @@ -34,6 +34,18 @@ const MAX_RETAINED_LOGS: usize = 7; /// else (dependency noise stays out of the file). const DEFAULT_FILTER: &str = "warn,rocm=info,rocm_dash_tui=info,rocm_dash_daemon=info"; +/// Whether this invocation opens the client log file at all. +/// +/// `rocm uninstall` does not: it inspects and deletes the folders the logger +/// would create, so starting the logger first made a dry run list a `logs` +/// folder it had just made. In a direct invocation the subcommand is the first +/// argument, because `rocm` has no global flags and does not abbreviate +/// subcommand names; an uninstall reached from `rocm chat` or a freeform +/// request runs under a logger that was already started. +pub fn is_enabled_for(raw_args: &[String]) -> bool { + raw_args.first().is_none_or(|arg| arg != "uninstall") +} + /// Initialize the process-wide `tracing` subscriber, writing to a daily- /// rotated file under `paths.client_log_dir()`. /// @@ -167,6 +179,25 @@ mod tests { ) } + fn args(list: &[&str]) -> Vec { + list.iter().map(|arg| (*arg).to_string()).collect() + } + + #[test] + fn uninstall_is_the_only_invocation_that_skips_the_log_file() { + // The scenario `uninstall-06` proves the behavior (a dry run creates and + // lists nothing); this pins which invocations that applies to. + assert!(!is_enabled_for(&args(&["uninstall"]))); + assert!(!is_enabled_for(&args(&["uninstall", "--dry-run"]))); + assert!(is_enabled_for(&args(&[]))); + assert!(is_enabled_for(&args(&["examine"]))); + assert!(is_enabled_for(&args(&["--help"]))); + // `runtimes uninstall` removes one runtime, not the folders the logger + // writes to, and a longer word is not the subcommand. + assert!(is_enabled_for(&args(&["runtimes", "uninstall", "x"]))); + assert!(is_enabled_for(&args(&["uninstall-all"]))); + } + #[test] fn temp_paths_gives_each_call_its_own_root_even_for_one_label() { crate::test_support::assert_each_call_gets_its_own_root(|| temp_paths("same-label").0); diff --git a/apps/rocm/src/main.rs b/apps/rocm/src/main.rs index 47326bc90d..0946ef5dcf 100644 --- a/apps/rocm/src/main.rs +++ b/apps/rocm/src/main.rs @@ -330,14 +330,15 @@ fn run() -> Result<()> { // non-blocking file writer, so an early drop would silently truncate the // log. A failed/missing `AppPaths::discover()` degrades to no logging // rather than a startup failure. - let _log_guard = AppPaths::discover() - .ok() + let raw_args: Vec = std::env::args().skip(1).collect(); + let _log_guard = logging::is_enabled_for(&raw_args) + .then(AppPaths::discover) + .and_then(Result::ok) .and_then(|paths| logging::init(&paths)); maybe_migrate_legacy_dashboard_config(); maybe_notice_legacy_uv_cache(); - let raw_args: Vec = std::env::args().skip(1).collect(); if raw_args.is_empty() { return launch_default(); } diff --git a/docs/manual-testing.md b/docs/manual-testing.md index 6b18e694a1..35407e69d6 100644 --- a/docs/manual-testing.md +++ b/docs/manual-testing.md @@ -1071,6 +1071,11 @@ Expected result: `PATH change left in place` and names it, and the `PATH` change stays. - With `rocm uninstall --keep-binaries`, the review says the `PATH` change stays too, and it does. +- On a home folder ROCm CLI never touched, the dry run says + `Nothing managed by rocm-cli would be removed.` and leaves the home folder + empty (scenario `uninstall-06`): run + `HOME=$(mktemp -d) rocm uninstall --keep-binaries --dry-run`, then `ls -A` + on that folder. - Without `--yes` and without a terminal, the command prints the same review, then refuses with `uninstall requires --yes outside an interactive terminal` and exit code 1, and removes nothing. On Linux or WSL, check it with no diff --git a/docs/testing.md b/docs/testing.md index b3242c38b4..cd9ea9eea0 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -953,7 +953,10 @@ symlinks. The `uninstall-NN` E2E scenarios (`features/uninstall.feature`) check the same behaviour through the built binary, confined to the scenario's own folder, including a folder that cannot be checked stopping the uninstall before -anything is removed: +anything is removed, and a dry run on a machine ROCm CLI never touched +(`uninstall-06`) reporting nothing to remove and creating no folder. The +`uninstall` command does not start the file logger, which would otherwise create +the data folder's `logs` folder before the plan is built: ```bash cargo xtask e2e -- -n "uninstall-" diff --git a/tests/e2e-cucumber/features/uninstall.feature b/tests/e2e-cucumber/features/uninstall.feature index 3e06a03efe..286a59c0c2 100644 --- a/tests/e2e-cucumber/features/uninstall.feature +++ b/tests/e2e-cucumber/features/uninstall.feature @@ -66,3 +66,17 @@ Feature: Uninstall And the uninstall does not name the default install's cache folder And the data folder's own cache folder is gone And the default install's cache folder still holds the user's files + + # `rocm uninstall --dry-run` shows what would be removed without changing + # anything. It once started the file logger first, which created the data + # folder's `logs` folder, and then listed that folder as the one thing to + # remove, so a machine ROCm CLI had never touched looked installed. The + # promise is two-sided: the plan says there is nothing to remove, and the + # folders it would have removed are still absent afterwards. + @id:uninstall-dry-run-on-an-untouched-machine-creates-nothing + Scenario: uninstall-06 - A dry run on a machine ROCm CLI never touched reports nothing to remove and creates nothing + Given ROCm CLI has never created its folders in the user's home + When the user dry-runs an uninstall + Then the uninstall succeeds + And the uninstall reports that nothing would be removed + And ROCm CLI has still not created its folders diff --git a/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs b/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs index 13871a4cbe..3b818cffb5 100644 --- a/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs +++ b/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs @@ -283,6 +283,64 @@ async fn default_cache_intact(world: &mut E2eWorld) { ); } +/// Every place the CLI keeps state when only the config and data folders are +/// set: those two, the cache folder inside the data folder, and the default +/// `~/.rocm` that a stray write would land in. The harness's own cache folder +/// is left out because a runner may share it between scenarios. +fn state_folders(world: &E2eWorld) -> Vec { + let paths = world.app_paths(); + vec![ + paths.config_dir, + paths.data_dir.clone(), + paths.data_dir.join("cache"), + home_dir(world).join(".rocm"), + ] +} + +#[given("ROCm CLI has never created its folders in the user's home")] +async fn no_folders_yet(world: &mut E2eWorld) { + // The harness creates the config, data and cache folders empty before each + // scenario; a machine ROCm CLI never touched has none of them. + for sub in ["config", "data", "cache"] { + let folder = root(world).join(sub); + std::fs::remove_dir(&folder) + .unwrap_or_else(|e| panic!("failed to remove the empty {}: {e}", folder.display())); + } + for folder in state_folders(world) { + assert!( + std::fs::symlink_metadata(&folder).is_err(), + "the scenario must start without {}", + folder.display() + ); + } +} + +#[when("the user dry-runs an uninstall")] +async fn dry_run_uninstall(world: &mut E2eWorld) { + run_without_cache_setting(world, &["uninstall", "--keep-binaries", "--dry-run"]); +} + +#[then("the uninstall reports that nothing would be removed")] +async fn reports_nothing_to_remove(world: &mut E2eWorld) { + let stdout = output(world); + assert!( + stdout.contains("Nothing managed by rocm-cli would be removed."), + "a machine with no folders has nothing to remove:\n{stdout}" + ); +} + +#[then("ROCm CLI has still not created its folders")] +async fn still_no_folders(world: &mut E2eWorld) { + for folder in state_folders(world) { + assert!( + std::fs::symlink_metadata(&folder).is_err(), + "the dry run created {}:\n{}", + folder.display(), + output(world) + ); + } +} + fn output(world: &E2eWorld) -> &str { world .cli_output