diff --git a/README.md b/README.md index f87198aad..c979e71dc 100644 --- a/README.md +++ b/README.md @@ -1727,7 +1727,7 @@ rocm services logs [--follow] rocm uninstall [--yes] [--dry-run] [--keep-binaries] [--keep-config] [--keep-data] [--keep-cache] - [--force-dev-binaries] + [--allow-dev-binaries] ``` `--follow` (`-f`) keeps printing a server's new log output, such as a model @@ -1745,7 +1745,7 @@ do and asks `[y/N]` (default: no) before doing it. Only `y` or `yes` proceeds. Enter, `n` and `no` cancel: it prints `uninstall cancelled`, removes nothing and exits with code 0. Any other answer cancels the same way, after a line saying that the answer was not understood and is treated as no. Use `--dry-run` to only -list, and `--yes` to skip the confirmation. There is no `--force`; `--force-dev-binaries` +list, and `--yes` to skip the confirmation. There is no `--force`; `--allow-dev-binaries` is a separate opt-in for development builds. At a terminal, a dry run that finds something to remove ends by saying to run the same command again without `--dry-run`; with nothing to remove, or when stdin or stdout is not a terminal @@ -1801,9 +1801,13 @@ If `rocm uninstall` cannot check whether one of those folders is there (for example, a link on the way loops back on itself), it stops with an error naming the folder before anything is removed. -When you run `rocm` from a cargo `target` build, `uninstall` skips binary -removal. Pass `--force-dev-binaries` to remove the ROCm CLI binaries in that build -directory. +When you run `rocm` from a cargo `target/debug` or `target/release` folder, +`uninstall` keeps the binaries and says so under `Left alone:`. Pass +`--allow-dev-binaries` to remove the ROCm CLI binaries in that folder (`rocm`, +`rocmd`, `rocm-codex` and `rocm-engine-*`; the rest of the build is left alone). +It overrides nothing else: `--keep-binaries` still keeps them, `--dry-run` still +removes nothing, and the run still needs confirming. `--force-dev-binaries`, the +older spelling, still works. Before removing anything, `uninstall` prints warnings about two situations: diff --git a/apps/rocm/src/cli.rs b/apps/rocm/src/cli.rs index 7cf55ed5c..0c4dbcb18 100644 --- a/apps/rocm/src/cli.rs +++ b/apps/rocm/src/cli.rs @@ -726,12 +726,18 @@ rocm uninstall --keep-data --yes")] /// which lives under the data directory; use --keep-data for that. #[arg(long)] keep_cache: bool, - /// Allow removing development binaries inside the current build tree. - #[arg(long)] - force_dev_binaries: bool, + /// Also remove the ROCm CLI binaries in the cargo `target/debug` or + /// `target/release` folder `rocm` runs from, which uninstall otherwise + /// keeps. Overrides nothing else: `--keep-binaries`, `--dry-run` and the + /// confirmation still apply. + // `--force-dev-binaries` is the older spelling, kept working and out of + // the help and the completions. + #[arg(long, alias = "force-dev-binaries")] + allow_dev_binaries: bool, /// Not an option; accepted only to say so. Without it clap answers a /// mistyped `--force` (a likely guess for skipping the confirmation) - /// with `--force-dev-binaries`, which removes development binaries. + /// with `--force-dev-binaries`, the older spelling of + /// `--allow-dev-binaries`, which removes development binaries. #[arg(long, hide = true, num_args = 0..=1, default_missing_value = "")] force: Option, }, @@ -2348,7 +2354,9 @@ mod tests { /// `--force` is a likely guess for "skip the confirmation", and without a /// declared `--force` clap answers it, and every near miss of it, with - /// `--force-dev-binaries`, which removes the binaries of a development build. + /// `--force-dev-binaries`, the older spelling of `--allow-dev-binaries`, which + /// removes the binaries of a development build. Neither spelling may be + /// offered for a `--force` near miss. /// The scenario `uninstall-mistyped-force-is-not-answered-with-a-destructive-flag` /// proves the real binary's output; this pins the parse behind it. #[test] @@ -2357,17 +2365,17 @@ mod tests { let cli = Cli::try_parse_from(["rocm", "uninstall", "--force"]).unwrap(); let Some(Command::Uninstall { force, - force_dev_binaries, + allow_dev_binaries, .. }) = cli.command else { panic!("not an uninstall command"); }; - assert!(force.is_some() && !force_dev_binaries); + assert!(force.is_some() && !allow_dev_binaries); let refusal = reject_force(force.is_some()).unwrap_err().to_string(); assert!(refusal.contains("`--force` is not an option"), "{refusal}"); assert!(refusal.contains("--yes"), "{refusal}"); - assert!(!refusal.contains("force-dev-binaries"), "{refusal}"); + assert!(!refusal.contains("dev-binaries"), "{refusal}"); assert!(reject_force(false).is_ok()); // `--force=x` is the same mistake, and gets the same answer rather than // a usage line that lists every flag. @@ -2391,7 +2399,7 @@ mod tests { .unwrap_err(); let rendered = error.render().to_string(); assert!( - !rendered.contains("force-dev-binaries"), + !rendered.contains("dev-binaries"), "{args:?} was answered with the destructive flag:\n{rendered}" ); assert_eq!(error.exit_code(), 2, "{args:?}"); @@ -2414,18 +2422,25 @@ mod tests { .render() .to_string(); assert!( - rendered.contains("--force") && !rendered.contains("force-dev-binaries"), + rendered.contains("--force") && !rendered.contains("dev-binaries"), "{args:?} must be steered to the declared `--force`, not the destructive flag:\n{rendered}" ); } - // The whole flag misspelled is still met with the flag it was meant to be. - let error = cli_command() - .try_get_matches_from(["rocm", "uninstall", "--force-dev-binary"]) - .unwrap_err() - .render() - .to_string(); - assert!(error.contains("--force-dev-binaries"), "{error}"); + // The whole flag misspelled is still met with the flag it was meant to + // be. The older spelling is a hidden alias, which clap still offers as + // a suggestion, so a misspelling of it is answered with it. + for (typed, meant) in [ + ("--allow-dev-binary", "--allow-dev-binaries"), + ("--force-dev-binary", "--force-dev-binaries"), + ] { + let error = cli_command() + .try_get_matches_from(["rocm", "uninstall", typed]) + .unwrap_err() + .render() + .to_string(); + assert!(error.contains(meant), "{typed}: {error}"); + } // It stays out of the help. let mut command = cli_command(); @@ -2437,6 +2452,57 @@ mod tests { assert!(!help.contains("Not an option"), "{help}"); } + /// `--allow-dev-binaries` and its older spelling `--force-dev-binaries` set + /// the same option, and only the new name is advertised. This pins the parse + /// and the help text; what the option does, and that it overrides nothing + /// else, is proven by `a_development_build_keeps_its_binaries_unless_allowed` + /// in `uninstall_plan.rs` and by the scenario + /// `uninstall-development-build-keeps-its-binaries-unless-allowed`. + #[test] + fn both_spellings_allow_dev_binaries_and_only_the_new_one_is_advertised() { + for flag in ["--allow-dev-binaries", "--force-dev-binaries"] { + let cli = Cli::try_parse_from(["rocm", "uninstall", flag]).unwrap(); + let Some(Command::Uninstall { + allow_dev_binaries, + force, + .. + }) = cli.command + else { + panic!("not an uninstall command"); + }; + assert!(allow_dev_binaries && force.is_none(), "{flag}"); + } + let cli = Cli::try_parse_from(["rocm", "uninstall"]).unwrap(); + let Some(Command::Uninstall { + allow_dev_binaries, .. + }) = cli.command + else { + panic!("not an uninstall command"); + }; + assert!(!allow_dev_binaries, "off unless asked for"); + + let mut command = cli_command(); + let help = command + .find_subcommand_mut("uninstall") + .unwrap() + .render_long_help() + .to_string(); + assert!(help.contains("--allow-dev-binaries"), "{help}"); + assert!(help.contains("Overrides nothing else"), "{help}"); + assert!(!help.contains("force-dev-binaries"), "{help}"); + + let mut completions = Vec::new(); + clap_complete::generate( + clap_complete::Shell::Bash, + &mut crate::completion_command(), + "rocm", + &mut completions, + ); + let completions = String::from_utf8(completions).unwrap(); + assert!(completions.contains("--allow-dev-binaries")); + assert!(!completions.contains("force-dev-binaries")); + } + /// The help leads with the safe preview, then the real run, as the tip a /// person reads before running a command that deletes things. #[test] diff --git a/apps/rocm/src/main.rs b/apps/rocm/src/main.rs index 776590c87..0d7182e38 100644 --- a/apps/rocm/src/main.rs +++ b/apps/rocm/src/main.rs @@ -931,7 +931,7 @@ fn dispatch(cli: Cli) -> Result<()> { keep_config, keep_data, keep_cache, - force_dev_binaries, + allow_dev_binaries, force, }) => { uninstall::reject_force(force.is_some())?; @@ -942,7 +942,7 @@ fn dispatch(cli: Cli) -> Result<()> { keep_config, keep_data, keep_cache, - force_dev_binaries, + allow_dev_binaries, }) } Some(Command::Completions { shell }) => { diff --git a/apps/rocm/src/uninstall.rs b/apps/rocm/src/uninstall.rs index 28007a0c4..0a5200aee 100644 --- a/apps/rocm/src/uninstall.rs +++ b/apps/rocm/src/uninstall.rs @@ -68,9 +68,10 @@ impl PathEdit { /// `rocm uninstall` has no `--force`; the flag is declared (hidden) only so this /// can answer it. Left undeclared, clap's nearest-name guess for `--force` is -/// `--force-dev-binaries`, which removes development binaries, and a near miss -/// such as `--forc` gets that same suggestion. Declared, those guesses land here -/// instead, before anything is planned or removed. +/// `--force-dev-binaries` (the older spelling of `--allow-dev-binaries`, still +/// accepted and so still a candidate), which removes development binaries, and +/// a near miss such as `--forc` gets that same suggestion. Declared, those +/// guesses land here instead, before anything is planned or removed. pub(crate) fn reject_force(force: bool) -> Result<()> { if force { bail!( diff --git a/apps/rocm/src/uninstall_plan.rs b/apps/rocm/src/uninstall_plan.rs index 3c3da4e6d..8613636ae 100644 --- a/apps/rocm/src/uninstall_plan.rs +++ b/apps/rocm/src/uninstall_plan.rs @@ -62,7 +62,7 @@ pub(crate) struct UninstallOptions { pub(crate) keep_config: bool, pub(crate) keep_data: bool, pub(crate) keep_cache: bool, - pub(crate) force_dev_binaries: bool, + pub(crate) allow_dev_binaries: bool, } #[derive(Debug, Clone)] @@ -217,9 +217,9 @@ pub(crate) fn plan_installed_binaries( return Ok(()); } let current_exe = current_exe()?; - if is_dev_binary_layout(¤t_exe) && !options.force_dev_binaries { + if is_dev_binary_layout(¤t_exe) && !options.allow_dev_binaries { plan.skipped.push(format!( - "binary removal skipped because {} looks like a cargo target build; pass --force-dev-binaries to remove sibling debug/release binaries", + "binary removal skipped because {} looks like a cargo target build; pass --allow-dev-binaries to remove the ROCm CLI binaries in that folder", current_exe.display() )); return Ok(()); @@ -596,6 +596,79 @@ mod tests { } } + /// A `rocm` run from a cargo build folder keeps that folder's binaries + /// unless `--allow-dev-binaries` is given, and says which flag removes + /// them; given, it plans the ROCm CLI binaries there and nothing else in + /// the folder; `--keep-binaries` still wins over it. The scenario + /// `uninstall-development-build-keeps-its-binaries-unless-allowed` runs the + /// real binary from such a folder. + #[test] + fn a_development_build_keeps_its_binaries_unless_allowed() -> Result<()> { + let root = tempfile::tempdir()?; + let build = root.path().join("target").join("debug"); + fs::create_dir_all(build.join("deps"))?; + let exe = build.join(if cfg!(windows) { "rocm.exe" } else { "rocm" }); + let daemon = build.join(if cfg!(windows) { "rocmd.exe" } else { "rocmd" }); + for file in [&exe, &daemon, &build.join("rocm.d")] { + fs::write(file, "built")?; + } + let plan_with = |allow_dev_binaries, keep_binaries| -> Result { + let mut plan = UninstallPlan::default(); + let options = UninstallOptions { + keep_binaries, + allow_dev_binaries, + ..UninstallOptions::default() + }; + plan_installed_binaries(&mut plan, &options, || Ok(exe.clone()), None)?; + Ok(plan) + }; + // The running binary is planned as an action, except on Windows, + // where it is deleted as the command exits. + let planned = |plan: &UninstallPlan| { + let mut binaries: Vec = plan + .actions + .iter() + .filter(|entry| entry.kind == "binary") + .map(|entry| entry.path.clone()) + .chain(plan.self_delete.clone()) + .collect(); + binaries.sort(); + binaries + }; + + let kept = plan_with(false, false)?; + assert!(planned(&kept).is_empty(), "{kept:?}"); + assert!( + kept.actions.is_empty() && kept.path_edits.is_empty(), + "{kept:?}" + ); + assert_eq!( + kept.skipped, + [format!( + "binary removal skipped because {} looks like a cargo target build; pass \ + --allow-dev-binaries to remove the ROCm CLI binaries in that folder", + exe.display() + )] + ); + + let allowed = plan_with(true, false)?; + let mut expected = vec![exe.clone(), daemon]; + expected.sort(); + assert_eq!(planned(&allowed), expected, "{allowed:?}"); + assert!(allowed.skipped.is_empty(), "{allowed:?}"); + + let still_kept = plan_with(true, true)?; + assert!(planned(&still_kept).is_empty(), "{still_kept:?}"); + assert!( + still_kept + .skipped + .iter() + .any(|note| note.starts_with("binary removal disabled by --keep-binaries")), + "{still_kept:?}" + ); + Ok(()) + } + /// A person at a terminal who dry-runs is told to run the same command again /// without `--dry-run`: the next step is a rerun, not a control the command /// line lacks. The scenario `uninstall-07` runs it again at a terminal and diff --git a/docs/manual-testing.md b/docs/manual-testing.md index d199f2f78..97c4407f3 100644 --- a/docs/manual-testing.md +++ b/docs/manual-testing.md @@ -1433,9 +1433,19 @@ Expected result: - Passing `--force` to `rocm uninstall` is refused with a message that says it is not an option and points to `--yes`; a near miss such as `--forc` is an unknown-argument error (exit 2). Neither - suggests `--force-dev-binaries` (scenario `uninstall-10`). + suggests `--allow-dev-binaries` or its older spelling `--force-dev-binaries` + (scenario `uninstall-10`). `rocm uninstall --help` ends with examples that start with a dry run (scenario `uninstall-11`). +- Run from a cargo build, `HOME=$(mktemp -d) ./target/debug/rocm uninstall + --keep-config --keep-data --keep-cache --dry-run` lists nothing to remove and, + under `Left alone:`, says the binaries are kept and to pass + `--allow-dev-binaries`. Adding `--allow-dev-binaries` (or its older spelling + `--force-dev-binaries`) lists `rocm`, `rocmd` and the other ROCm CLI programs + in `target/debug`, and nothing else from the build; without `--dry-run` it + still needs `--yes` or a `y` at the prompt (scenario `uninstall-16`). Do the + real run only with `rocm` copied into a scratch `target/debug` folder, not on + your working build. - 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 6fc8e6992..371b9d21e 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -1806,7 +1806,7 @@ ends by saying to run it again without `--dry-run`, and `uninstall-07` does that and checks the listed folder goes; a run whose stdin or stdout is not a terminal, and an empty plan even at one, name no next step (`uninstall-08`, `uninstall-09`). A mistyped `--force` is refused with a pointer to `--yes`, and a near miss of it -is not answered with `--force-dev-binaries` (`uninstall-10`); the help starts +is not answered with either spelling of `--allow-dev-binaries` (`uninstall-10`); the help starts its examples with a dry run (`uninstall-11`). The assistant's uninstall preview ends differently, since it has no flag to offer: it says removal needs approval, which `lifecycle_read_mutate_split_is_honest` in [tool_policy.rs](../apps/rocm/src/tool_policy.rs) backs. @@ -1817,6 +1817,15 @@ with Ctrl-D, and for a plain no, each together with the config folder being left in place. They run on the default mock lane; the helper's other callers (`rocm fix`, the SDK-overwrite prompt) share it and are covered by its unit tests in [confirm.rs](../crates/rocm-core/src/confirm.rs). +`uninstall-16` (Linux) runs a copy of the binary from a `target/debug` folder in +the scenario's own folder: a dry run keeps that folder's binaries and names +`--allow-dev-binaries`, the older spelling `--force-dev-binaries` lists them, +allowing them without `--yes` outside a terminal is still refused and removes +nothing, and with `--yes` they are removed. It is Linux-only because Windows +deletes the running `rocm.exe` only after the command exits. The plan behind it +is unit-tested by `a_development_build_keeps_its_binaries_unless_allowed` in +[uninstall_plan.rs](../apps/rocm/src/uninstall_plan.rs), including +`--keep-binaries` winning over the flag. The `uninstall` command does not start the file logger, which would otherwise create the data folder's `logs` folder before the plan is built: diff --git a/tests/e2e-cucumber/features/uninstall.feature b/tests/e2e-cucumber/features/uninstall.feature index 147f0455e..7c9046792 100644 --- a/tests/e2e-cucumber/features/uninstall.feature +++ b/tests/e2e-cucumber/features/uninstall.feature @@ -6,9 +6,12 @@ Feature: Uninstall # cover what the plan does with the folders it is pointed at, so they run on # the mock lane every PR. # - # Every scenario passes --keep-binaries (the binary under test must survive) - # and points HOME, the uv cache and the Hugging Face cache at the scenario's - # own folder, so an uninstall can never reach the runner's shared caches. + # Every scenario passes --keep-binaries (the binary under test must survive), + # except the assistant's preview (uninstall-12), which removes nothing, and + # uninstall-16, which runs a copy of the binary under test placed in the + # scenario's own folder. All of them point HOME, the uv cache and the Hugging + # Face cache at the scenario's own folder, so an uninstall can never reach the + # runner's shared caches. # # The link scenarios are Linux-only, and the behaviour they pin is only # claimed for Linux: on Windows a directory symlink or junction needs @@ -123,9 +126,10 @@ Feature: Uninstall And the config folder still holds the user's files # `--force` is a natural guess for skipping the confirmation, and the nearest - # real flag by name is `--force-dev-binaries`, which removes the binaries of a - # development build. `--force` is refused with the flag to use instead, a near - # miss of it never suggests the destructive flag, and nothing is removed. + # real flag by name is `--force-dev-binaries`, the older spelling of + # `--allow-dev-binaries`, which removes the binaries of a development build. + # `--force` is refused with the flag to use instead, a near miss of it never + # suggests either spelling of the destructive flag, and nothing is removed. @id:uninstall-mistyped-force-is-not-answered-with-a-destructive-flag Scenario: uninstall-10 - A mistyped --force is refused without pointing at the flag that removes development binaries Given the config folder holds the user's files @@ -187,3 +191,31 @@ Feature: Uninstall Then the uninstall is reported as cancelled And the user is not told the answer was misunderstood And the config folder still holds the user's files + + # A `rocm` run from a cargo build folder (`target/debug` or `target/release`) + # keeps the ROCm CLI binaries in that folder, so uninstalling from a checkout + # does not delete the developer's build, and says which flag removes them. + # `--allow-dev-binaries` removes them and overrides nothing else: it still + # needs confirming. `--force-dev-binaries`, its older spelling, still works. + # + # The development build here is a copy of the binary under test, placed in a + # build folder inside the scenario's own folder beside a stand-in daemon, and + # every run keeps the config, data and cache, so the copy and the stand-in are + # all a run can remove. Linux-only: Windows cannot delete the running + # `rocm.exe`, so it is removed only after the command exits, and whether it is + # gone when the next step looks would be a race. + @id:uninstall-development-build-keeps-its-binaries-unless-allowed @requires-os:linux + Scenario: uninstall-16 - A development build keeps its binaries unless the user allows removing them, which still needs confirming + Given ROCm CLI is run from a development build folder + When the user dry-runs an uninstall from the development build + Then the uninstall succeeds + And the dry run keeps the development build's binaries and names the flag that removes them + When the user dry-runs an uninstall from the development build, allowing its binaries with the older spelling of the flag + Then the uninstall succeeds + And the dry run lists the development build's binaries + When the user allows removing the development build's binaries without confirming + Then the uninstall is refused until it is confirmed, after listing the development build's binaries + And the development build's binaries are still there + When the user allows removing the development build's binaries and confirms + Then the uninstall succeeds + And the development build's binaries are gone diff --git a/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs b/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs index 49a16b943..d61415ded 100644 --- a/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs +++ b/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs @@ -7,7 +7,9 @@ //! Black-box against the real binary. Every run is confined to the scenario's //! isolated root: `--keep-binaries` so the binary under test survives, and HOME, //! `UV_CACHE_DIR` and `HF_HOME` pointed inside the root so no uninstall can reach -//! a shared cache the runner keeps between scenarios. +//! a shared cache the runner keeps between scenarios. The one run that removes +//! binaries (`uninstall-16`) runs a copy of the binary under test placed in the +//! root, and removes only that copy; see `run_dev_build_uninstall`. use std::path::{Path, PathBuf}; @@ -874,8 +876,9 @@ async fn refused_and_told_to_use_yes(world: &mut E2eWorld) { && stderr.contains("use `--yes` to skip the confirmation"), "expected the refusal to name --yes:\n{stderr}" ); + // Neither spelling of the flag that removes development binaries. assert!( - !stderr.contains("force-dev-binaries"), + !stderr.contains("dev-binaries"), "the refusal must not name the destructive flag:\n{stderr}" ); } @@ -892,8 +895,9 @@ async fn error_does_not_suggest_dev_binaries(world: &mut E2eWorld) { stderr.contains("unexpected argument"), "expected the unknown-argument error on stderr:\n{stderr}" ); + // Neither spelling of the flag that removes development binaries. assert!( - !stderr.contains("force-dev-binaries"), + !stderr.contains("dev-binaries"), "the error must not name the destructive flag:\n{stderr}" ); } @@ -928,3 +932,208 @@ async fn help_shows_dry_run_first(world: &mut E2eWorld) { "the examples must also show the real run:\n{examples}" ); } + +// --------------------------------------------------------------------------- +// A development build's binaries (uninstall-16) +// --------------------------------------------------------------------------- + +/// The cargo build folder inside the scenario's own folder that the copy of +/// the binary under test runs from. Spelled as the running copy reports its own +/// path, with every link resolved, since that is how the plan names it. +fn dev_build_dir(world: &E2eWorld) -> PathBuf { + root(world) + .canonicalize() + .expect("failed to resolve the scenario's folder") + .join("target") + .join("debug") +} + +/// The ROCm CLI binaries in that folder: the copy of `rocm` under test and a +/// stand-in `rocmd` beside it. +fn dev_build_binaries(world: &E2eWorld) -> [PathBuf; 2] { + let dir = dev_build_dir(world); + [dir.join("rocm"), dir.join("rocmd")] +} + +/// The binary under test as a file: `ROCM_CLI_BINARY` when it names a path, +/// otherwise the `rocm` that `PATH` finds. +fn binary_under_test() -> PathBuf { + let binary = crate::rocm_binary(); + let found = if e2e_cucumber::binary_path::names_a_path(&binary) { + Some(PathBuf::from(&binary)) + } else { + std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()) + .map(|dir| dir.join(&binary)) + .find(|path| path.is_file()) + }; + let found = found.unwrap_or_else(|| panic!("cannot find the binary under test ({binary})")); + found + .canonicalize() + .unwrap_or_else(|error| panic!("failed to resolve {}: {error}", found.display())) +} + +#[given("ROCm CLI is run from a development build folder")] +async fn run_from_dev_build(world: &mut E2eWorld) { + let [rocm, rocmd] = dev_build_binaries(world); + let contents = + std::fs::read(binary_under_test()).expect("failed to read the binary under test"); + std::fs::create_dir_all(dev_build_dir(world)).expect("failed to create the build folder"); + rocm_core::fake_executable::write_fake_executable(&rocm, contents) + .expect("failed to copy the binary under test into the build folder"); + std::fs::write(&rocmd, "stand-in daemon").expect("failed to write the stand-in rocmd"); +} + +/// Run the copy in the scenario's build folder as `rocm uninstall`, keeping the +/// config, data and cache, so the only thing a run can remove is that folder's +/// binaries. +/// +/// This is the documented exception to [`assert_keeps_binaries`]: the binaries +/// are what the scenario is about. What makes it safe is checked here, before +/// every run: the program started is the copy, inside the scenario's own folder, +/// and the config, data and cache are all kept. +fn run_dev_build_uninstall(world: &mut E2eWorld, flags: &[&str]) { + let mut args = vec!["uninstall", "--keep-config", "--keep-data", "--keep-cache"]; + args.extend_from_slice(flags); + let program = dev_build_binaries(world)[0] + .canonicalize() + .expect("the copy of the binary under test is missing"); + let scenario_root = root(world) + .canonicalize() + .expect("failed to resolve the scenario's folder"); + assert!( + program.starts_with(&scenario_root) && program != binary_under_test(), + "an uninstall that may remove binaries must run the copy inside the scenario's folder \ + ({}), not {}", + scenario_root.display(), + program.display() + ); + for kept in ["--keep-config", "--keep-data", "--keep-cache"] { + assert!(args.contains(&kept), "missing {kept}: {args:?}"); + } + + let mut cmd = std::process::Command::new(&program); + cmd.args(&args); + world.isolate_cmd(&mut cmd); + for (name, value) in isolated_env(world) { + cmd.env(name, value); + } + let output = cmd + .output() + .unwrap_or_else(|error| panic!("failed to run {}: {error}", program.display())); + let stdout = String::from_utf8_lossy(&output.stdout).into_owned(); + let rc = output.status.code().unwrap_or(-1); + crate::record_command(world.current_scenario.as_deref(), &args, rc, &stdout); + world.cli_output = Some(stdout); + world.cli_stderr = Some(String::from_utf8_lossy(&output.stderr).into_owned()); + world.cli_rc = Some(rc); +} + +#[when("the user dry-runs an uninstall from the development build")] +async fn dry_run_from_dev_build(world: &mut E2eWorld) { + run_dev_build_uninstall(world, &["--dry-run"]); +} + +#[when( + "the user dry-runs an uninstall from the development build, allowing its binaries with the older spelling of the flag" +)] +async fn dry_run_from_dev_build_older_spelling(world: &mut E2eWorld) { + run_dev_build_uninstall(world, &["--force-dev-binaries", "--dry-run"]); +} + +#[when("the user allows removing the development build's binaries without confirming")] +async fn allow_dev_binaries_unconfirmed(world: &mut E2eWorld) { + run_dev_build_uninstall(world, &["--allow-dev-binaries"]); +} + +#[when("the user allows removing the development build's binaries and confirms")] +async fn allow_dev_binaries_confirmed(world: &mut E2eWorld) { + run_dev_build_uninstall(world, &["--allow-dev-binaries", "--yes"]); +} + +fn listed_binary(path: &Path) -> String { + format!(" - binary: {}", path.display()) +} + +#[then("the dry run keeps the development build's binaries and names the flag that removes them")] +async fn dry_run_keeps_dev_binaries(world: &mut E2eWorld) { + let stdout = output(world); + let note = format!( + "binary removal skipped because {} looks like a cargo target build; pass \ + --allow-dev-binaries to remove the ROCm CLI binaries in that folder", + dev_build_binaries(world)[0].display() + ); + assert!( + stdout + .lines() + .any(|line| line.trim_start_matches(" - ") == note), + "expected the note `{note}`:\n{stdout}" + ); + for binary in dev_build_binaries(world) { + assert!( + !stdout.contains(&listed_binary(&binary)), + "a development build's binary must not be listed for removal:\n{stdout}" + ); + } + // The older spelling works, but is not the one the user is told about. + assert!(!stdout.contains("force-dev-binaries"), "{stdout}"); +} + +#[then("the dry run lists the development build's binaries")] +async fn dry_run_lists_dev_binaries(world: &mut E2eWorld) { + let stdout = output(world); + for binary in dev_build_binaries(world) { + let line = listed_binary(&binary); + assert!( + stdout.lines().any(|l| l == line), + "expected a `{line}` line:\n{stdout}" + ); + } +} + +#[then( + "the uninstall is refused until it is confirmed, after listing the development build's binaries" +)] +async fn refused_after_listing_dev_binaries(world: &mut E2eWorld) { + let stderr = world.cli_stderr.as_deref().unwrap_or(""); + assert_eq!( + world.cli_rc, + Some(1), + "an unconfirmed uninstall outside a terminal exits 1\nstdout:\n{}\nstderr:\n{stderr}", + output(world) + ); + assert!( + stderr.contains("uninstall requires --yes outside an interactive terminal"), + "expected the --yes refusal on stderr:\n{stderr}" + ); + dry_run_lists_dev_binaries(world).await; +} + +#[then("the development build's binaries are still there")] +async fn dev_binaries_still_there(world: &mut E2eWorld) { + for binary in dev_build_binaries(world) { + assert!( + binary.is_file(), + "{} was removed:\n{}", + binary.display(), + output(world) + ); + } +} + +#[then("the development build's binaries are gone")] +async fn dev_binaries_gone(world: &mut E2eWorld) { + for binary in dev_build_binaries(world) { + assert!( + std::fs::symlink_metadata(&binary).is_err(), + "{} must be removed:\n{}", + binary.display(), + output(world) + ); + let line = format!("removed binary {}", binary.display()); + assert!( + output(world).lines().any(|l| l == line), + "expected a `{line}` line:\n{}", + output(world) + ); + } +}