diff --git a/src/uu/tsort/src/tsort.rs b/src/uu/tsort/src/tsort.rs index 145383e9f..4b52e1e45 100644 --- a/src/uu/tsort/src/tsort.rs +++ b/src/uu/tsort/src/tsort.rs @@ -236,8 +236,8 @@ impl<'input> Graph<'input> { for &node in &cycle { show!(LoopNode(node)); } - let u = cycle[0]; - let v = cycle[1]; + let u = *cycle.last().expect("cycle must be non-empty"); + let v = cycle[0]; self.remove_edge(u, v); if self.indegree(v).unwrap() == 0 { frontier.push_back(v); @@ -245,7 +245,6 @@ impl<'input> Graph<'input> { } fn detect_cycle(&self) -> Vec<&'input str> { - // Sort the nodes just to make this function deterministic. let mut nodes: Vec<_> = self.nodes.keys().collect(); nodes.sort_unstable(); @@ -253,11 +252,8 @@ impl<'input> Graph<'input> { let mut stack = Vec::with_capacity(self.nodes.len()); for node in nodes { if self.dfs(node, &mut visited, &mut stack) { - // last element in the stack appears twice: at the begin - // and at the end of the loop let (loop_entry, _) = stack.pop().expect("loop is not empty"); - // skip the prefix which doesn't belong to the loop return stack .into_iter() .map(|(node, _)| node) diff --git a/test_keys2 b/test_keys2 new file mode 100755 index 000000000..efdf87e83 Binary files /dev/null and b/test_keys2 differ diff --git a/tests/by-util/test_tsort.rs b/tests/by-util/test_tsort.rs index 9033ea4a7..077fd26b7 100644 --- a/tests/by-util/test_tsort.rs +++ b/tests/by-util/test_tsort.rs @@ -103,7 +103,7 @@ fn test_cycle() { new_ucmd!() .pipe_in("a b b c c d c b") .fails_with_code(1) - .stdout_is("a\nc\nd\nb\n") + .stdout_is("a\nb\nc\nd\n") .stderr_is("tsort: -: input contains a loop:\ntsort: b\ntsort: c\n"); } @@ -119,7 +119,7 @@ fn test_two_cycles() { new_ucmd!() .pipe_in("a b b c c b b d d b") .fails_with_code(1) - .stdout_is("a\nc\nd\nb\n") + .stdout_is("a\nb\nc\nd\n") .stderr_is("tsort: -: input contains a loop:\ntsort: b\ntsort: c\ntsort: -: input contains a loop:\ntsort: b\ntsort: d\n"); }