1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-07-29 12:07:46 +00:00

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
This commit is contained in:
Jeffrey Finkelstein 2025-01-04 22:51:36 -05:00
parent 5cf5acb4a2
commit f703e88e9f
2 changed files with 13 additions and 11 deletions

View file

@ -74,18 +74,12 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
std::fs::read_to_string(path)? std::fs::read_to_string(path)?
}; };
// Create the directed graph from pairs of tokens in the input data.
let mut g = Graph::default(); let mut g = Graph::default();
for ab in data.split_whitespace().collect::<Vec<&str>>().chunks(2) {
for line in data.lines() { match ab {
let tokens: Vec<_> = line.split_whitespace().collect(); [a, b] => g.add_edge(a, b),
if tokens.is_empty() { _ => return Err(TsortError::NumTokensOdd(input.to_string()).into()),
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()),
}
} }
} }

View file

@ -75,3 +75,11 @@ fn test_error_on_dir() {
.fails() .fails()
.stderr_contains("tsort: tsort_test_dir: read error: Is a directory"); .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");
}