Skip to content

Commit

Permalink
Merge branch 'main' of https://github.com/sno2/ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
sno2 committed Oct 25, 2023
2 parents 410f157 + 6f31e9c commit 599047c
Show file tree
Hide file tree
Showing 12 changed files with 502 additions and 165 deletions.
121 changes: 72 additions & 49 deletions crates/ruff_cli/src/commands/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ pub(crate) fn format(
};

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

// Make output deterministic, at least as long as we have a path
results.sort_unstable_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 All @@ -198,15 +177,21 @@ pub(crate) fn format(
caches.persist()?;

// Report on any errors.
errors.sort_unstable_by(|a, b| a.path().cmp(&b.path()));

for error in &errors {
error!("{error}");
}

results.sort_unstable_by(|a, b| a.path.cmp(&b.path));
let results = FormatResults::new(results.as_slice(), mode);

if mode.is_diff() {
results.write_diff(&mut stdout().lock())?;
match mode {
FormatMode::Write => {}
FormatMode::Check => {
results.write_changed(&mut stdout().lock())?;
}
FormatMode::Diff => {
results.write_diff(&mut stdout().lock())?;
}
}

// Report on the formatting changes.
Expand Down Expand Up @@ -470,42 +455,62 @@ impl<'a> FormatResults<'a> {
})
}

/// Write a diff of the formatting changes to the given writer.
fn write_diff(&self, f: &mut impl Write) -> io::Result<()> {
for result in self.results {
if let FormatResult::Diff {
unformatted,
formatted,
} = &result.result
{
let text_diff =
TextDiff::from_lines(unformatted.source_code(), formatted.source_code());
let mut unified_diff = text_diff.unified_diff();
unified_diff.header(
&fs::relativize_path(&result.path),
&fs::relativize_path(&result.path),
);
unified_diff.to_writer(&mut *f)?;
}
for (path, unformatted, formatted) in self
.results
.iter()
.filter_map(|result| {
if let FormatResult::Diff {
unformatted,
formatted,
} = &result.result
{
Some((result.path.as_path(), unformatted, formatted))
} else {
None
}
})
.sorted_unstable_by_key(|(path, _, _)| *path)
{
let text_diff =
TextDiff::from_lines(unformatted.source_code(), formatted.source_code());
let mut unified_diff = text_diff.unified_diff();
unified_diff.header(&fs::relativize_path(path), &fs::relativize_path(path));
unified_diff.to_writer(&mut *f)?;
}

Ok(())
}

/// Write a list of the files that would be changed to the given writer.
fn write_changed(&self, f: &mut impl Write) -> io::Result<()> {
for path in self
.results
.iter()
.filter_map(|result| {
if result.result.is_formatted() {
Some(result.path.as_path())
} else {
None
}
})
.sorted_unstable()
{
writeln!(f, "Would reformat: {}", fs::relativize_path(path).bold())?;
}

Ok(())
}

/// Write a summary of the formatting results to the given writer.
fn write_summary(&self, f: &mut impl Write) -> io::Result<()> {
// Compute the number of changed and unchanged files.
let mut changed = 0u32;
let mut unchanged = 0u32;
for result in self.results {
match &result.result {
FormatResult::Formatted => {
// If we're running in check mode, report on any files that would be formatted.
if self.mode.is_check() {
writeln!(
f,
"Would reformat: {}",
fs::relativize_path(&result.path).bold()
)?;
}
changed += 1;
}
FormatResult::Unchanged => unchanged += 1,
Expand Down Expand Up @@ -564,6 +569,24 @@ pub(crate) enum FormatCommandError {
Write(Option<PathBuf>, SourceError),
}

impl FormatCommandError {
fn path(&self) -> Option<&Path> {
match self {
Self::Ignore(err) => {
if let ignore::Error::WithPath { path, .. } = err {
Some(path.as_path())
} else {
None
}
}
Self::Panic(path, _)
| Self::Read(path, _)
| Self::Format(path, _)
| Self::Write(path, _) => path.as_deref(),
}
}
}

impl Display for FormatCommandError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Expand Down
3 changes: 3 additions & 0 deletions crates/ruff_linter/resources/test/fixtures/ruff/RUF100_0.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ def f() -> None:
# Invalid (but external)
d = 1 # noqa: F841, V101

# Invalid (but external)
d = 1 # noqa: V500

# fmt: off
# Invalid - no space before #
d = 1# noqa: E501
Expand Down
5 changes: 4 additions & 1 deletion crates/ruff_linter/src/checkers/noqa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,10 @@ pub(crate) fn check_noqa(
}

if line.matches.iter().any(|match_| *match_ == code)
|| settings.external.contains(code)
|| settings
.external
.iter()
.any(|external| code.starts_with(external))
{
valid_codes.push(code);
} else {
Expand Down
21 changes: 20 additions & 1 deletion crates/ruff_linter/src/rules/ruff/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,26 @@ mod tests {
let diagnostics = test_path(
Path::new("ruff/RUF100_0.py"),
&settings::LinterSettings {
external: FxHashSet::from_iter(vec!["V101".to_string()]),
external: vec!["V101".to_string()],
..settings::LinterSettings::for_rules(vec![
Rule::UnusedNOQA,
Rule::LineTooLong,
Rule::UnusedImport,
Rule::UnusedVariable,
Rule::TabIndentation,
])
},
)?;
assert_messages!(diagnostics);
Ok(())
}

#[test]
fn ruf100_0_prefix() -> Result<()> {
let diagnostics = test_path(
Path::new("ruff/RUF100_0.py"),
&settings::LinterSettings {
external: vec!["V".to_string()],
..settings::LinterSettings::for_rules(vec![
Rule::UnusedNOQA,
Rule::LineTooLong,
Expand Down
3 changes: 3 additions & 0 deletions crates/ruff_linter/src/rules/ruff/rules/unused_noqa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ pub struct UnusedCodes {
/// foo.bar()
/// ```
///
/// ## Options
/// - `external`
///
/// ## References
/// - [Ruff error suppression](https://docs.astral.sh/ruff/linter/#error-suppression)
#[violation]
Expand Down

0 comments on commit 599047c

Please sign in to comment.