Skip to content
Merged
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
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ Shared UI components — reuse rather than hand-rolling new ones. The CLI (`apps

Shared (`crates/rocm-core`):

- [`confirm.rs`](crates/rocm-core/src/confirm.rs)'s **`print_prompt`**/**`read_answer`** — the shared `[y/N]` confirmation prompt: `print_prompt` writes and flushes a prompt (callers include their own trailing `[y/N]: `), `read_answer` reads a line and parses it as yes/no. Two fallible calls rather than one, so a caller can choose whether a failed write is fatal: [`fix/consent.rs`](crates/rocm-core/src/fix/consent.rs)'s `confirm()` attempts the read anyway, while [`uninstall_plan.rs`](apps/rocm/src/uninstall_plan.rs)'s `confirm_uninstall` and [`consent.rs`](apps/rocm/src/therock/consent.rs)'s `prompt_yes_no` treat it as fatal. [`uninstall.rs`](apps/rocm/src/uninstall.rs), [`storage.rs`](apps/rocm/src/storage.rs) and [`runtimes_cmd.rs`](apps/rocm/src/runtimes_cmd.rs) reach the prompt only through `confirm_uninstall`, each behind `require_yes_or_interactive` (below); [`fix/consent.rs`](crates/rocm-core/src/fix/consent.rs)'s `confirm()` additionally layers its own non-interactive short-circuit and refusal wording on top
- [`confirm.rs`](crates/rocm-core/src/confirm.rs)'s **`print_prompt`**/**`read_answer`** — the shared `[y/N]` confirmation prompt: `print_prompt` writes and flushes a prompt (callers include their own trailing `[y/N]: `), `read_answer` reads a line and parses it as yes/no, and writes to the stream it is given a newline when the input ended without one and a line saying so when the answer was neither yes nor no (declined either way). Two fallible calls rather than one, so a caller can choose whether a failed write is fatal: [`fix/consent.rs`](crates/rocm-core/src/fix/consent.rs)'s `confirm()` attempts the read anyway, while [`uninstall_plan.rs`](apps/rocm/src/uninstall_plan.rs)'s `confirm_uninstall` and [`consent.rs`](apps/rocm/src/therock/consent.rs)'s `prompt_yes_no` treat it as fatal. [`uninstall.rs`](apps/rocm/src/uninstall.rs), [`storage.rs`](apps/rocm/src/storage.rs) and [`runtimes_cmd.rs`](apps/rocm/src/runtimes_cmd.rs) reach the prompt only through `confirm_uninstall`, each behind `require_yes_or_interactive` (below); [`fix/consent.rs`](crates/rocm-core/src/fix/consent.rs)'s `confirm()` additionally layers its own non-interactive short-circuit and refusal wording on top
- [`confirm.rs`](crates/rocm-core/src/confirm.rs)'s **`require_yes_or_interactive(yes, action)`** — the guard in front of a mutating command that confirms with that `[y/N]` prompt. `Ok(true)` means `--yes` already approved it (skip the prompt), `Ok(false)` means there is no `--yes` but a terminal, so the caller still asks, and otherwise it bails with `"{action} requires --yes outside an interactive terminal"`. A new `--yes`-gated command reuses it instead of re-deriving the `yes` / `interactive_terminal()` / `bail!` sequence. Not for a refusal that deliberately differs: [`therock/consent.rs`](apps/rocm/src/therock/consent.rs)'s `sdk_install_approval` names two consents that are not interchangeable, and [`fix/consent.rs`](crates/rocm-core/src/fix/consent.rs)'s `confirm()` has its own exit code and checks stdin only

CLI:
Expand Down
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1613,8 +1613,11 @@ non-zero too, after printing its log.

`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. There is no `--force`; `--force-dev-binaries`
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`
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
Expand Down
2 changes: 1 addition & 1 deletion apps/rocm/src/therock/consent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -440,7 +440,7 @@ pub(super) fn confirm_overwrite_existing_sdk(
fn prompt_yes_no(prompt: &str) -> Result<bool> {
rocm_core::confirm::print_prompt(&mut std::io::stdout(), prompt)
.context("failed to write confirmation prompt")?;
rocm_core::confirm::read_answer(&mut std::io::stdin().lock())
rocm_core::confirm::read_answer(&mut std::io::stdin().lock(), &mut std::io::stdout())
.context("failed to read confirmation response")
}

Expand Down
2 changes: 1 addition & 1 deletion apps/rocm/src/uninstall_plan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -438,7 +438,7 @@ fn env_path(name: &str) -> Option<PathBuf> {
pub(crate) fn confirm_uninstall() -> Result<bool> {
rocm_core::confirm::print_prompt(&mut io::stdout(), "Proceed with uninstall? [y/N]: ")
.context("failed to write uninstall prompt")?;
rocm_core::confirm::read_answer(&mut io::stdin().lock())
rocm_core::confirm::read_answer(&mut io::stdin().lock(), &mut io::stdout())
.context("failed to read uninstall confirmation")
}

Expand Down
270 changes: 248 additions & 22 deletions crates/rocm-core/src/confirm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,13 @@
//! without a controlled terminal. Real callers pass `std::io::stdout()` and
//! `std::io::stdin().lock()`.
//!
//! [`read_answer`] also tells the user when their answer was not understood, and
//! ends the prompt line when the input ended without a newline. Both go to the
//! `out` stream the caller passes, so every caller gets them and none can forget.
//! `y`/`yes` approve; `n`/`no`/an empty line decline silently (an empty line is
//! the documented default); anything else declines with a line saying so, rather
//! than being mistaken for a deliberate "no".
//!
//! [`interactive_terminal`] answers the question callers ask before prompting at
//! all: whether this process has a terminal on both streams.
//! [`require_yes_or_interactive`] is the guard built on it for a mutating
Expand All @@ -32,9 +39,24 @@
use anyhow::{Result, bail};
use std::io::{BufRead, IsTerminal, Write, stdin, stdout};

/// Parse a user's typed response to a `[y/N]` prompt.
pub fn is_affirmative_answer(line: &str) -> bool {
matches!(line.trim().to_lowercase().as_str(), "y" | "yes")
/// How a typed response to a `[y/N]` prompt reads.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Answer {
/// `y` or `yes`, in any case.
Yes,
/// `n` or `no`, or an empty line: the prompt's default.
No,
/// Anything else. Declined like [`Answer::No`], but worth saying so.
Unrecognized,
}

/// Classify a user's typed response to a `[y/N]` prompt.
pub fn parse_answer(line: &str) -> Answer {
match line.trim().to_lowercase().as_str() {
"y" | "yes" => Answer::Yes,
"" | "n" | "no" => Answer::No,
_ => Answer::Unrecognized,
}
}

/// Write `prompt` to `out` and flush it, so it's visible before a blocking
Expand All @@ -54,10 +76,48 @@ pub fn print_prompt(out: &mut impl Write, prompt: &str) -> std::io::Result<()> {
/// Read one line from `input` and parse it as yes/no. Only errors if the
/// line can't be read; a declined answer — including an empty read at EOF —
/// is `Ok(false)`, not an error.
pub fn read_answer(input: &mut impl BufRead) -> std::io::Result<bool> {
///
/// Two things are written to `out` so the caller's own message lands where the
/// user can read it:
/// - when the line did not end in a newline (EOF, as from Ctrl-D, or piped input
/// with no final newline such as `printf no |`), a newline, ending the prompt
/// line: either way nothing echoed a line end, so the cursor is still on the
/// prompt line and the caller's next line would run into it;
/// - when the answer is [`Answer::Unrecognized`], a line saying it is being
/// treated as no, with the answer shown back quoted and escaped and cut to
/// [`MAX_ECHOED_ANSWER_CHARS`] characters, so a long pasted line does not fill
/// the screen.
///
/// Both writes are best effort: a failure to explain a decline must not turn
/// into an error that replaces the decline, which `fix`'s `confirm()` relies on.
pub fn read_answer(input: &mut impl BufRead, out: &mut impl Write) -> std::io::Result<bool> {
let mut line = String::new();
input.read_line(&mut line)?;
Ok(is_affirmative_answer(&line))
if !line.ends_with('\n') {
let _ = writeln!(out);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This newline is also written for non-terminal input that just lacks a trailing newline (printf y |), where nothing was echoed to explain it. Harmless, but the doc says "EOF, as from Ctrl-D"; maybe say "or piped input without a final newline".

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, you are right that the doc named only Ctrl-D. 05e6ef2 now says "or piped input with no final newline such as printf no |". I kept the newline for that input and documented it: nothing echoed a line end after the prompt there either, so the cursor is still on the prompt line and the caller's next line would run into it. The test for a no without a newline pins it next to the existing one for yes, and the architecture entry for confirm.rs says the same since 335aef2.

}
let answer = parse_answer(&line);
if answer == Answer::Unrecognized {
let _ = writeln!(
out,
"{} is not yes or no; treating it as no.",
echoed_answer(line.trim())
);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The echoed answer is line.trim() with no length bound, so a long pasted line is printed in full. Optional: truncate to the first ~40 chars plus an ellipsis.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, fixed in 467c849. The echoed answer is now cut to its first 40 characters, counted as characters so a multi-byte one is never split, with ... after the closing quote when there was more. It is still quoted with control characters escaped, and the limit is on the typed characters, so a line made of escapes stays bounded too. Four unit tests cover a long answer, an answer exactly at the limit and one over it, 2-byte and 4-byte characters, and a line of escapes, and they fail when the bound is removed.

The review body has no thread, so the missing unit test for a partial no is here. It is added in 05e6ef2 as read_answer_for_a_no_without_a_newline_declines_and_only_ends_the_prompt_line: it feeds no with no newline and expects the decline and a lone newline, and it fails when the newline write is removed.

}
Ok(answer == Answer::Yes)
}

/// The most characters of a typed answer that the "not understood" line shows.
const MAX_ECHOED_ANSWER_CHARS: usize = 40;

/// `answer` as shown back to the user: quoted with control characters escaped, and
/// cut to [`MAX_ECHOED_ANSWER_CHARS`] characters (never in the middle of one), with
/// `...` after the closing quote when there was more.
fn echoed_answer(answer: &str) -> String {
let mut chars = answer.chars();
let shown: String = chars.by_ref().take(MAX_ECHOED_ANSWER_CHARS).collect();
let more = if chars.next().is_some() { "..." } else { "" };
format!("{shown:?}{more}")
}

/// Whether this process can hold an interactive exchange with a user.
Expand Down Expand Up @@ -112,21 +172,34 @@ mod tests {
use std::io::{Error, Result};

#[test]
fn is_affirmative_answer_accepts_only_y_and_yes() {
fn parse_answer_accepts_only_y_and_yes() {
for accepted in ["y", "Y", "yes", "YES", "Yes", " y ", " yes\n"] {
assert!(
is_affirmative_answer(accepted),
assert_eq!(
parse_answer(accepted),
Answer::Yes,
"expected {accepted:?} to be treated as a yes"
);
}
}

#[test]
fn is_affirmative_answer_rejects_everything_else() {
for declined in ["n", "no", "", "\n", "yep", "ye"] {
assert!(
!is_affirmative_answer(declined),
"expected {declined:?} to be treated as a decline"
fn parse_answer_reads_n_no_and_an_empty_line_as_the_default_no() {
for declined in ["n", "N", "no", "NO", " no ", "", "\n", " \n"] {
assert_eq!(
parse_answer(declined),
Answer::No,
"expected {declined:?} to be the default no"
);
}
}

#[test]
fn parse_answer_flags_everything_else_as_unrecognized() {
for odd in ["maybe", "yep", "ye", "yes please", "nope", "1", "y n"] {
assert_eq!(
parse_answer(odd),
Answer::Unrecognized,
"expected {odd:?} to be unrecognized"
);
}
}
Expand Down Expand Up @@ -189,19 +262,170 @@ mod tests {
);
}

/// Run `read_answer` over `typed` and return the verdict and everything it
/// wrote to the output stream.
fn answer_and_output(typed: &[u8]) -> (bool, String) {
let mut input = typed;
let mut out = Vec::new();
let verdict =
read_answer(&mut input, &mut out).expect("read from a byte slice cannot fail");
(
verdict,
String::from_utf8(out).expect("the helper writes UTF-8"),
)
}

#[test]
fn read_answer_approves_y_and_yes_without_writing_anything() {
for typed in [&b"y\n"[..], b"yes\n", b"YES\n"] {
let (verdict, written) = answer_and_output(typed);
assert!(verdict, "{typed:?} must approve");
assert_eq!(written, "", "an approval needs no comment");
}
}

#[test]
fn read_answer_declines_n_no_and_enter_without_writing_anything() {
for typed in [&b"n\n"[..], b"no\n", b"\n"] {
let (verdict, written) = answer_and_output(typed);
assert!(!verdict, "{typed:?} must decline");
assert_eq!(
written, "",
"a deliberate no (or the default) must not be commented on"
);
}
}

#[test]
fn read_answer_declines_an_unrecognized_answer_and_says_so() {
let (verdict, written) = answer_and_output(b"maybe\n");
assert!(!verdict, "an unrecognized answer must decline");
assert_eq!(written, "\"maybe\" is not yes or no; treating it as no.\n");
}

#[test]
fn read_answer_at_eof_declines_and_ends_the_prompt_line() {
let (verdict, written) = answer_and_output(b"");
assert!(!verdict, "EOF is Ok(false), not an error");
assert_eq!(written, "\n", "EOF leaves the cursor on the prompt line");
}

#[test]
fn read_answer_for_a_partial_line_ends_the_prompt_line_then_says_so() {
// Typed text and then EOF, with no newline: the terminal echoed the text
// but no newline, so the line must be ended before the feedback line.
let (verdict, written) = answer_and_output(b"maybe");
assert!(!verdict);
assert_eq!(
written,
"\n\"maybe\" is not yes or no; treating it as no.\n"
);
}

#[test]
fn read_answer_for_a_yes_without_a_newline_still_approves() {
let (verdict, written) = answer_and_output(b"yes");
assert!(verdict, "a yes is a yes with or without the final newline");
assert_eq!(written, "\n", "the unfinished prompt line is still ended");
}

#[test]
fn read_answer_cuts_a_long_answer_short_and_marks_the_cut() {
let typed = format!("{}\n", "a".repeat(100));
let (verdict, written) = answer_and_output(typed.as_bytes());
assert!(!verdict);
assert_eq!(
written,
format!(
"\"{}\"... is not yes or no; treating it as no.\n",
"a".repeat(MAX_ECHOED_ANSWER_CHARS)
)
);
}

#[test]
fn read_answer_shows_an_answer_of_exactly_the_limit_whole() {
let answer = "b".repeat(MAX_ECHOED_ANSWER_CHARS);
let (_, written) = answer_and_output(format!("{answer}\n").as_bytes());
assert_eq!(
written,
format!("\"{answer}\" is not yes or no; treating it as no.\n"),
"an answer that fits is not marked as cut"
);
let (_, written) = answer_and_output(format!("{answer}c\n").as_bytes());
assert_eq!(
written,
format!("\"{answer}\"... is not yes or no; treating it as no.\n"),
"one character over the limit is cut"
);
}

#[test]
fn read_answer_cuts_between_characters_not_inside_one() {
// 2-byte and 4-byte characters: a cut by bytes would split one and panic
// or write invalid UTF-8; the limit counts characters.
for ch in ['é', '🦀'] {
let typed = format!("{}\n", ch.to_string().repeat(MAX_ECHOED_ANSWER_CHARS + 5));
let (_, written) = answer_and_output(typed.as_bytes());
assert_eq!(
written,
format!(
"\"{}\"... is not yes or no; treating it as no.\n",
ch.to_string().repeat(MAX_ECHOED_ANSWER_CHARS)
),
"answer of {ch:?}"
);
}
}

#[test]
fn read_answer_bounds_the_line_even_when_every_character_is_escaped() {
// An escaped control character is longer than itself, so the limit is on
// the typed characters and the line stays bounded by it.
let typed = format!("{}\n", "\x1b".repeat(100));
let (_, written) = answer_and_output(typed.as_bytes());
assert_eq!(
written,
format!(
"\"{}\"... is not yes or no; treating it as no.\n",
"\\u{1b}".repeat(MAX_ECHOED_ANSWER_CHARS)
)
);
assert!(
!written.contains('\x1b'),
"no raw escape reaches the terminal"
);
}

#[test]
fn read_answer_parses_a_typed_line() {
let mut input: &[u8] = b"yes\n";
assert!(read_answer(&mut input).expect("read from a byte slice cannot fail"));
fn read_answer_for_a_no_without_a_newline_declines_and_only_ends_the_prompt_line() {
// Piped input such as `printf no |` has no final newline either. The
// verdict is the decline `no\n` gives and nothing explains it, but the
// prompt line is still ended: no newline was echoed after the prompt.
let (verdict, written) = answer_and_output(b"no");
assert!(!verdict, "a no is a no with or without the final newline");
assert_eq!(written, "\n", "only the unfinished prompt line is ended");
}

let mut input: &[u8] = b"n\n";
assert!(!read_answer(&mut input).expect("read from a byte slice cannot fail"));
#[test]
fn read_answer_quotes_an_answer_that_holds_control_characters() {
// The answer is echoed back, so it is escaped rather than written raw.
let (_, written) = answer_and_output(b"\x1b[31mred\n");
assert_eq!(
written,
"\"\\u{1b}[31mred\" is not yes or no; treating it as no.\n"
);
}

#[test]
fn read_answer_at_eof_declines_without_erroring() {
let mut input: &[u8] = b"";
assert!(!read_answer(&mut input).expect("EOF is Ok(false), not an error"));
fn read_answer_keeps_the_verdict_when_the_feedback_cannot_be_written() {
// The explanation is best effort: a closed stdout must not turn a
// decline into an error, which `fix`'s `confirm()` relies on.
let mut input: &[u8] = b"maybe\n";
let mut out = FailingWriter;
let verdict = read_answer(&mut input, &mut out)
.expect("a failed feedback write must not replace the verdict");
assert!(!verdict);
}

/// A reader whose `read_line` always fails, so a real I/O failure on the
Expand All @@ -224,7 +448,9 @@ mod tests {
#[test]
fn read_answer_surfaces_a_read_failure_as_an_error() {
let mut input = FailingReader;
read_answer(&mut input).expect_err("a failing reader must return Err");
let mut out = Vec::new();
read_answer(&mut input, &mut out).expect_err("a failing reader must return Err");
assert!(out.is_empty(), "nothing is written for a failed read");
}

#[test]
Expand Down
4 changes: 3 additions & 1 deletion crates/rocm-core/src/fix/consent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,9 @@ pub(super) fn confirm(prompt: &str, assume_yes: bool) -> bool {
return verdict;
}
let _ = crate::confirm::print_prompt(&mut std::io::stdout(), &format!("{prompt} [y/N]: "));
let confirmed = crate::confirm::read_answer(&mut std::io::stdin().lock()).unwrap_or(false);
let confirmed =
crate::confirm::read_answer(&mut std::io::stdin().lock(), &mut std::io::stdout())
.unwrap_or(false);
if !confirmed {
fail!("Not confirmed; refusing to apply.");
}
Expand Down
Loading
Loading