Skip to content

Commit

Permalink
Make ruff format output deterministic
Browse files Browse the repository at this point in the history
  • Loading branch information
konstin committed Oct 13, 2023
1 parent 0631f27 commit 61f4914
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 8 deletions.
23 changes: 22 additions & 1 deletion crates/ruff_cli/src/commands/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ pub(crate) fn format(
}

let start = Instant::now();
let (results, errors): (Vec<_>, Vec<_>) = paths
let (mut results, mut errors): (Vec<_>, Vec<_>) = paths
.into_par_iter()
.filter_map(|entry| {
match entry {
Expand Down Expand Up @@ -105,6 +105,27 @@ pub(crate) fn format(
});
let duration = start.elapsed();

// Make output deterministic, at least as long as we have a path
results.sort_by(|x, y| x.path.cmp(&y.path));
errors.sort_by(|x, y| {
fn get_key(error: &FormatCommandError) -> Option<&PathBuf> {
match &error {
FormatCommandError::Ignore(ignore) => {
if let ignore::Error::WithPath { path, .. } = ignore {
Some(path)
} else {
None
}
}
FormatCommandError::Panic(path, _)
| FormatCommandError::Read(path, _)
| FormatCommandError::Format(path, _)
| FormatCommandError::Write(path, _) => path.as_ref(),
}
}
get_key(x).cmp(&get_key(y))
});

debug!(
"Formatted {} files in {:.2?}",
results.len() + errors.len(),
Expand Down
14 changes: 7 additions & 7 deletions crates/ruff_cli/tests/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,13 +227,6 @@ fn test_diff() {
success: false
exit_code: 1
----- stdout -----
--- resources/test/fixtures/unformatted.py
+++ resources/test/fixtures/unformatted.py
@@ -1,3 +1,3 @@
x = 1
-y=2
+y = 2
z = 3
--- resources/test/fixtures/unformatted.ipynb
+++ resources/test/fixtures/unformatted.ipynb
@@ -1,3 +1,4 @@
Expand All @@ -243,6 +236,13 @@ fn test_diff() {
+
+maths = (numpy.arange(100) ** 2).sum()
+stats = numpy.asarray([1, 2, 3, 4]).median()
--- resources/test/fixtures/unformatted.py
+++ resources/test/fixtures/unformatted.py
@@ -1,3 +1,3 @@
x = 1
-y=2
+y = 2
z = 3
----- stderr -----
warning: `ruff format` is not yet stable, and subject to change in future versions.
Expand Down

0 comments on commit 61f4914

Please sign in to comment.