From f703e88e9f82dc5d5ecfca89eb2dc4cc66bdd9e0 Mon Sep 17 00:00:00 2001 From: Jeffrey Finkelstein Date: Sat, 4 Jan 2025 22:51:36 -0500 Subject: [PATCH] tsort: split edge data on any whitespace chars Make `tsort` split on any whitespace character instead of just whitespace within a single line. This allows edge information to be split with the source node on one line and the target node on another. For example, after this commit $ printf "a\nb\n" | tsort a b whereas before this would print an error message. Closes #7077 --- src/uu/tsort/src/tsort.rs | 16 +++++----------- tests/by-util/test_tsort.rs | 8 ++++++++ 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/src/uu/tsort/src/tsort.rs b/src/uu/tsort/src/tsort.rs index 98d3c6f78..ea5084a34 100644 --- a/src/uu/tsort/src/tsort.rs +++ b/src/uu/tsort/src/tsort.rs @@ -74,18 +74,12 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { std::fs::read_to_string(path)? }; + // Create the directed graph from pairs of tokens in the input data. let mut g = Graph::default(); - - for line in data.lines() { - let tokens: Vec<_> = line.split_whitespace().collect(); - if tokens.is_empty() { - break; - } - for ab in tokens.chunks(2) { - match ab.len() { - 2 => g.add_edge(ab[0], ab[1]), - _ => return Err(TsortError::NumTokensOdd(input.to_string()).into()), - } + for ab in data.split_whitespace().collect::>().chunks(2) { + match ab { + [a, b] => g.add_edge(a, b), + _ => return Err(TsortError::NumTokensOdd(input.to_string()).into()), } } diff --git a/tests/by-util/test_tsort.rs b/tests/by-util/test_tsort.rs index 49809e0df..f86add294 100644 --- a/tests/by-util/test_tsort.rs +++ b/tests/by-util/test_tsort.rs @@ -75,3 +75,11 @@ fn test_error_on_dir() { .fails() .stderr_contains("tsort: tsort_test_dir: read error: Is a directory"); } + +#[test] +fn test_split_on_any_whitespace() { + new_ucmd!() + .pipe_in("a\nb\n") + .succeeds() + .stdout_only("a\nb\n"); +}