Skip to content

Commit 1b2eb7f

Browse files
CopilotKSXGitHub
andcommitted
Replace unsafe set_var in color_always test with LsColors FromStr
Co-authored-by: KSXGitHub <11488886+KSXGitHub@users.noreply.github.com>
1 parent 92cede4 commit 1b2eb7f

2 files changed

Lines changed: 19 additions & 4 deletions

File tree

src/ls_colors.rs

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
use crate::visualizer::coloring::Color;
22
use lscolors::{Indicator, LsColors as LsColorsCrate};
3+
use std::convert::Infallible;
4+
use std::str::FromStr;
35

46
/// ANSI color prefix strings for terminal output, initialized from the `LS_COLORS` environment
57
/// variable.
@@ -14,7 +16,10 @@ pub struct LsColors {
1416
impl LsColors {
1517
/// Initialize by reading the current environment's `LS_COLORS`.
1618
pub fn from_env() -> Self {
17-
let ls_colors = LsColorsCrate::from_env().unwrap_or_default();
19+
Self::from_ls_colors_crate(&LsColorsCrate::from_env().unwrap_or_default())
20+
}
21+
22+
fn from_ls_colors_crate(ls_colors: &LsColorsCrate) -> Self {
1823
let prefix_for = |indicator: Indicator| {
1924
ls_colors
2025
.style_for_indicator(indicator)
@@ -39,3 +44,15 @@ impl LsColors {
3944
}
4045
}
4146
}
47+
48+
impl FromStr for LsColors {
49+
type Err = Infallible;
50+
/// Parse an `LS_COLORS`-format string into an [`LsColors`].
51+
///
52+
/// This never fails; unrecognized or invalid entries are silently ignored.
53+
fn from_str(input: &str) -> Result<Self, Self::Err> {
54+
Ok(Self::from_ls_colors_crate(&LsColorsCrate::from_string(
55+
input,
56+
)))
57+
}
58+
}

tests/usual_cli.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -880,9 +880,7 @@ fn color_always() {
880880
data_tree.par_sort_by(|left, right| left.size().cmp(&right.size()).reverse());
881881
*data_tree.name_mut() = OsStringDisplay::os_string_from(".");
882882

883-
// SAFETY: tests that set LS_COLORS all use the same constant value, so there is no data race.
884-
unsafe { std::env::set_var("LS_COLORS", LS_COLORS) };
885-
let ls_colors = LsColors::from_env();
883+
let ls_colors: LsColors = LS_COLORS.parse().expect("parse LS_COLORS");
886884
let map = HashMap::from([
887885
(
888886
OsStringDisplay::os_string_from("file-a1.txt"),

0 commit comments

Comments
 (0)