Skip to content
Open
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
15 changes: 15 additions & 0 deletions src/uu/dircolors/src/dircolors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,22 @@ fn generate_type_output(fmt: &OutputFmt) -> String {
}
}

/// The built-in database is guarded by `COLORTERM ?*` followed by one `TERM`
/// entry per known terminal. Those entries only take effect when one of them
/// matches the environment, so reproduce that check before emitting anything.
fn builtin_database_applies() -> bool {
if !env::var("COLORTERM").unwrap_or_default().is_empty() {
return true;
}
let term = env::var("TERM").unwrap_or_else(|_| "none".to_owned());
TERMS.iter().any(|pattern| term.fnmatch(pattern))
}

fn generate_ls_colors(fmt: &OutputFmt, sep: &str) -> String {
if !builtin_database_applies() {
let (prefix, suffix) = get_colors_format_strings(fmt);
return format!("{prefix}{suffix}");
}
if let OutputFmt::Display = fmt {
let mut display_parts = vec![];
let type_output = generate_type_output(fmt);
Expand Down
64 changes: 64 additions & 0 deletions tests/by-util/test_dircolors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ fn test_internal_db() {
#[test]
fn test_ls_colors() {
new_ucmd!()
.env("TERM", "screen")
.arg("--print-ls-colors")
.succeeds()
.stdout_is_fixture("ls_colors.expected");
Expand Down Expand Up @@ -249,3 +250,66 @@ fn test_invalid_term_glob() {
.succeeds()
.stdout_only("LS_COLORS='';\nexport LS_COLORS\n");
}

#[test]
fn test_builtin_database_unknown_term() {
for (arg, expected) in [
("-b", "LS_COLORS='';\nexport LS_COLORS\n"),
("-c", "setenv LS_COLORS ''\n"),
] {
new_ucmd!()
.env("TERM", "no-such-terminal")
.arg(arg)
.succeeds()
.stdout_only(expected);
}
}

#[test]
fn test_builtin_database_no_term() {
new_ucmd!()
.arg("-b")
.succeeds()
.stdout_only("LS_COLORS='';\nexport LS_COLORS\n");
}

#[test]
fn test_builtin_database_print_ls_colors_unknown_term() {
new_ucmd!()
.env("TERM", "no-such-terminal")
.arg("--print-ls-colors")
.succeeds()
.stdout_only("\n");
}

#[test]
fn test_builtin_database_known_term() {
let stdout = new_ucmd!()
.env("TERM", "xterm")
.arg("-b")
.succeeds()
.stdout_move_str();
assert!(stdout.contains("di=01;34"), "{stdout}");
}

#[test]
fn test_builtin_database_colorterm_without_term() {
let stdout = new_ucmd!()
.env("TERM", "no-such-terminal")
.env("COLORTERM", "truecolor")
.arg("-b")
.succeeds()
.stdout_move_str();
assert!(stdout.contains("di=01;34"), "{stdout}");
}

#[test]
fn test_print_database_ignores_term() {
// -p dumps the database itself, so it is not filtered by TERM.
let stdout = new_ucmd!()
.env("TERM", "no-such-terminal")
.arg("-p")
.succeeds()
.stdout_move_str();
assert!(stdout.contains("DIR 01;34"), "{stdout}");
}
Loading