diff --git a/src/bin/coreutils.rs b/src/bin/coreutils.rs index 3235fefd44a..7945883aa04 100644 --- a/src/bin/coreutils.rs +++ b/src/bin/coreutils.rs @@ -20,10 +20,18 @@ fn matched_utility(name: &str, utils: &UtilityMap) -> Option<&'static str> if name.ends_with("utils") { return None; } - // Prefer stty over tty, and never treat *utils as ls. + // Exact match, delimited prefix (uu-cat, coreutils-cat, x86_64-linux-gnu-cat), + // or a single-letter PROG_PREFIX without a separator (uls, ucat, gcat). + // Rejects false suffix matches such as pwd-symlink -> link. utils .keys() - .filter(|&&util| name.ends_with(util)) + .filter(|&&util| { + name.strip_suffix(util).is_some_and(|prefix| { + prefix.is_empty() + || prefix.ends_with(['-', '_', '.']) + || matches!(prefix.as_bytes(), [b] if b.is_ascii_alphanumeric()) + }) + }) .max_by_key(|util| util.len()) .copied() } diff --git a/tests/test_util_name.rs b/tests/test_util_name.rs index 114feae15d9..da884842c39 100644 --- a/tests/test_util_name.rs +++ b/tests/test_util_name.rs @@ -486,3 +486,38 @@ fn coreutils_prog_diagnostics_use_selected_name() { assert!(!output.status.success()); assert!(String::from_utf8_lossy(&output.stderr).starts_with("ls:")); } + +#[test] +#[cfg(all(unix, feature = "ls"))] +fn test_undelimited_prog_prefix() { + use std::process::Command; + + let scene = TestScenario::new("uls"); + let uls = scene.fixtures.plus("uls"); + symlink_file(&scene.bin_path, &uls).unwrap(); + + let output = Command::new(&uls).arg("--help").output().unwrap(); + assert!(output.status.success(), "{output:?}"); + assert!( + String::from_utf8_lossy(&output.stdout).contains("Usage: ls"), + "{output:?}" + ); +} + +#[test] +#[cfg(all(unix, feature = "link"))] +fn test_delimited_name_does_not_false_match_link() { + use std::process::Command; + + let scene = TestScenario::new("true_symlink"); + let alias = scene.fixtures.plus("true-symlink"); + symlink_file(&scene.bin_path, &alias).unwrap(); + + let output = Command::new(&alias).output().unwrap(); + assert_eq!(output.status.code(), Some(1), "{output:?}"); + assert!(output.stdout.is_empty(), "{output:?}"); + assert_eq!( + output.stderr, b"coreutils: unknown program 'true-symlink'\n", + "{output:?}" + ); +}