Move `fix::FixMode` to `flags::FixMode` (#3753)

This commit is contained in:
Charlie Marsh 2023-03-26 17:40:06 -04:00 committed by GitHub
parent cd75b57036
commit 6ed6da3e82
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 67 additions and 66 deletions

View File

@ -1,17 +0,0 @@
#[derive(Debug, Copy, Clone, Hash)]
pub enum FixMode {
Generate,
Apply,
Diff,
None,
}
impl From<bool> for FixMode {
fn from(value: bool) -> Self {
if value {
Self::Apply
} else {
Self::None
}
}
}

View File

@ -17,7 +17,6 @@ mod cst;
pub mod directives; pub mod directives;
mod doc_lines; mod doc_lines;
mod docstrings; mod docstrings;
pub mod fix;
pub mod flake8_to_ruff; pub mod flake8_to_ruff;
pub mod fs; pub mod fs;
pub mod jupyter; pub mod jupyter;

View File

@ -1,17 +1,34 @@
use crate::fix;
use ruff_macros::CacheKey; use ruff_macros::CacheKey;
#[derive(Debug, Copy, Clone, Hash)]
pub enum FixMode {
Generate,
Apply,
Diff,
None,
}
impl From<bool> for FixMode {
fn from(value: bool) -> Self {
if value {
Self::Apply
} else {
Self::None
}
}
}
#[derive(Debug, Copy, Clone, CacheKey, result_like::BoolLike)] #[derive(Debug, Copy, Clone, CacheKey, result_like::BoolLike)]
pub enum Autofix { pub enum Autofix {
Enabled, Enabled,
Disabled, Disabled,
} }
impl From<fix::FixMode> for Autofix { impl From<FixMode> for Autofix {
fn from(value: fix::FixMode) -> Self { fn from(value: FixMode) -> Self {
match value { match value {
fix::FixMode::Generate | fix::FixMode::Diff | fix::FixMode::Apply => Self::Enabled, FixMode::Generate | FixMode::Diff | FixMode::Apply => Self::Enabled,
fix::FixMode::None => Self::Disabled, FixMode::None => Self::Disabled,
} }
} }
} }

View File

@ -14,7 +14,7 @@ use ruff::message::{Location, Message};
use ruff::registry::Rule; use ruff::registry::Rule;
use ruff::resolver::PyprojectDiscovery; use ruff::resolver::PyprojectDiscovery;
use ruff::settings::{flags, AllSettings}; use ruff::settings::{flags, AllSettings};
use ruff::{fix, fs, packaging, resolver, warn_user_once, IOError, Range}; use ruff::{fs, packaging, resolver, warn_user_once, IOError, Range};
use ruff_diagnostics::Diagnostic; use ruff_diagnostics::Diagnostic;
use crate::args::Overrides; use crate::args::Overrides;
@ -28,7 +28,7 @@ pub fn run(
overrides: &Overrides, overrides: &Overrides,
cache: flags::Cache, cache: flags::Cache,
noqa: flags::Noqa, noqa: flags::Noqa,
autofix: fix::FixMode, autofix: flags::FixMode,
) -> Result<Diagnostics> { ) -> Result<Diagnostics> {
// Collect all the Python files to check. // Collect all the Python files to check.
let start = Instant::now(); let start = Instant::now();
@ -153,7 +153,7 @@ fn lint_path(
settings: &AllSettings, settings: &AllSettings,
cache: flags::Cache, cache: flags::Cache,
noqa: flags::Noqa, noqa: flags::Noqa,
autofix: fix::FixMode, autofix: flags::FixMode,
) -> Result<Diagnostics> { ) -> Result<Diagnostics> {
let result = catch_unwind(|| { let result = catch_unwind(|| {
crate::diagnostics::lint_path(path, package, settings, cache, noqa, autofix) crate::diagnostics::lint_path(path, package, settings, cache, noqa, autofix)
@ -190,10 +190,10 @@ mod test {
use anyhow::Result; use anyhow::Result;
use path_absolutize::Absolutize; use path_absolutize::Absolutize;
use ruff::fix::FixMode;
use ruff::logging::LogLevel; use ruff::logging::LogLevel;
use ruff::resolver::PyprojectDiscovery; use ruff::resolver::PyprojectDiscovery;
use ruff::settings::configuration::{Configuration, RuleSelection}; use ruff::settings::configuration::{Configuration, RuleSelection};
use ruff::settings::flags::FixMode;
use ruff::settings::flags::{Cache, Noqa}; use ruff::settings::flags::{Cache, Noqa};
use ruff::settings::types::SerializationFormat; use ruff::settings::types::SerializationFormat;
use ruff::settings::AllSettings; use ruff::settings::AllSettings;

View File

@ -5,7 +5,7 @@ use anyhow::Result;
use ruff::resolver::PyprojectDiscovery; use ruff::resolver::PyprojectDiscovery;
use ruff::settings::flags; use ruff::settings::flags;
use ruff::{fix, packaging, resolver}; use ruff::{packaging, resolver};
use crate::args::Overrides; use crate::args::Overrides;
use crate::diagnostics::{lint_stdin, Diagnostics}; use crate::diagnostics::{lint_stdin, Diagnostics};
@ -23,7 +23,7 @@ pub fn run_stdin(
pyproject_strategy: &PyprojectDiscovery, pyproject_strategy: &PyprojectDiscovery,
overrides: &Overrides, overrides: &Overrides,
noqa: flags::Noqa, noqa: flags::Noqa,
autofix: fix::FixMode, autofix: flags::FixMode,
) -> Result<Diagnostics> { ) -> Result<Diagnostics> {
if let Some(filename) = filename { if let Some(filename) = filename {
if !resolver::python_file_at_path(filename, pyproject_strategy, overrides)? { if !resolver::python_file_at_path(filename, pyproject_strategy, overrides)? {

View File

@ -12,11 +12,11 @@ use log::{debug, error};
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use similar::TextDiff; use similar::TextDiff;
use ruff::fs;
use ruff::jupyter::{is_jupyter_notebook, JupyterIndex, JupyterNotebook}; use ruff::jupyter::{is_jupyter_notebook, JupyterIndex, JupyterNotebook};
use ruff::linter::{lint_fix, lint_only, FixTable, LinterResult}; use ruff::linter::{lint_fix, lint_only, FixTable, LinterResult};
use ruff::message::Message; use ruff::message::Message;
use ruff::settings::{flags, AllSettings, Settings}; use ruff::settings::{flags, AllSettings, Settings};
use ruff::{fix, fs};
use crate::cache; use crate::cache;
@ -100,7 +100,7 @@ pub fn lint_path(
settings: &AllSettings, settings: &AllSettings,
cache: flags::Cache, cache: flags::Cache,
noqa: flags::Noqa, noqa: flags::Noqa,
autofix: fix::FixMode, autofix: flags::FixMode,
) -> Result<Diagnostics> { ) -> Result<Diagnostics> {
// Check the cache. // Check the cache.
// TODO(charlie): `fixer::Mode::Apply` and `fixer::Mode::Diff` both have // TODO(charlie): `fixer::Mode::Apply` and `fixer::Mode::Diff` both have
@ -110,7 +110,7 @@ pub fn lint_path(
// to reason about. We need to come up with a better solution here.) // to reason about. We need to come up with a better solution here.)
let metadata = if cache.into() let metadata = if cache.into()
&& noqa.into() && noqa.into()
&& matches!(autofix, fix::FixMode::None | fix::FixMode::Generate) && matches!(autofix, flags::FixMode::None | flags::FixMode::Generate)
{ {
let metadata = path.metadata()?; let metadata = path.metadata()?;
if let Some(messages) = if let Some(messages) =
@ -143,14 +143,14 @@ pub fn lint_path(
error: parse_error, error: parse_error,
}, },
fixed, fixed,
) = if matches!(autofix, fix::FixMode::Apply | fix::FixMode::Diff) { ) = if matches!(autofix, flags::FixMode::Apply | flags::FixMode::Diff) {
if let Ok((result, transformed, fixed)) = if let Ok((result, transformed, fixed)) =
lint_fix(&contents, path, package, noqa, &settings.lib) lint_fix(&contents, path, package, noqa, &settings.lib)
{ {
if !fixed.is_empty() { if !fixed.is_empty() {
if matches!(autofix, fix::FixMode::Apply) { if matches!(autofix, flags::FixMode::Apply) {
write(path, transformed.as_bytes())?; write(path, transformed.as_bytes())?;
} else if matches!(autofix, fix::FixMode::Diff) { } else if matches!(autofix, flags::FixMode::Diff) {
let mut stdout = io::stdout().lock(); let mut stdout = io::stdout().lock();
TextDiff::from_lines(contents.as_str(), &transformed) TextDiff::from_lines(contents.as_str(), &transformed)
.unified_diff() .unified_diff()
@ -243,7 +243,7 @@ pub fn lint_stdin(
contents: &str, contents: &str,
settings: &Settings, settings: &Settings,
noqa: flags::Noqa, noqa: flags::Noqa,
autofix: fix::FixMode, autofix: flags::FixMode,
) -> Result<Diagnostics> { ) -> Result<Diagnostics> {
// Lint the inputs. // Lint the inputs.
let ( let (
@ -252,7 +252,7 @@ pub fn lint_stdin(
error: parse_error, error: parse_error,
}, },
fixed, fixed,
) = if matches!(autofix, fix::FixMode::Apply | fix::FixMode::Diff) { ) = if matches!(autofix, flags::FixMode::Apply | flags::FixMode::Diff) {
if let Ok((result, transformed, fixed)) = lint_fix( if let Ok((result, transformed, fixed)) = lint_fix(
contents, contents,
path.unwrap_or_else(|| Path::new("-")), path.unwrap_or_else(|| Path::new("-")),
@ -260,10 +260,10 @@ pub fn lint_stdin(
noqa, noqa,
settings, settings,
) { ) {
if matches!(autofix, fix::FixMode::Apply) { if matches!(autofix, flags::FixMode::Apply) {
// Write the contents to stdout, regardless of whether any errors were fixed. // Write the contents to stdout, regardless of whether any errors were fixed.
io::stdout().write_all(transformed.as_bytes())?; io::stdout().write_all(transformed.as_bytes())?;
} else if matches!(autofix, fix::FixMode::Diff) { } else if matches!(autofix, flags::FixMode::Diff) {
// But only write a diff if it's non-empty. // But only write a diff if it's non-empty.
if !fixed.is_empty() { if !fixed.is_empty() {
let text_diff = TextDiff::from_lines(contents, &transformed); let text_diff = TextDiff::from_lines(contents, &transformed);
@ -293,7 +293,7 @@ pub fn lint_stdin(
let fixed = FxHashMap::default(); let fixed = FxHashMap::default();
// Write the contents to stdout anyway. // Write the contents to stdout anyway.
if matches!(autofix, fix::FixMode::Apply) { if matches!(autofix, flags::FixMode::Apply) {
io::stdout().write_all(contents.as_bytes())?; io::stdout().write_all(contents.as_bytes())?;
} }

View File

@ -1,18 +1,19 @@
use anyhow::Result;
use clap::CommandFactory;
use notify::{recommended_watcher, RecursiveMode, Watcher};
use std::io::{self, BufWriter}; use std::io::{self, BufWriter};
use std::path::PathBuf; use std::path::PathBuf;
use std::process::ExitCode; use std::process::ExitCode;
use std::sync::mpsc::channel; use std::sync::mpsc::channel;
use crate::args::{Args, CheckArgs, Command}; use anyhow::Result;
use crate::printer::{Flags as PrinterFlags, Printer}; use clap::CommandFactory;
use notify::{recommended_watcher, RecursiveMode, Watcher};
use ruff::logging::{set_up_logging, LogLevel}; use ruff::logging::{set_up_logging, LogLevel};
use ruff::settings::types::SerializationFormat; use ruff::settings::types::SerializationFormat;
use ruff::settings::CliSettings; use ruff::settings::{flags, CliSettings};
use ruff::{fix, fs, warn_user_once}; use ruff::{fs, warn_user_once};
use crate::args::{Args, CheckArgs, Command};
use crate::printer::{Flags as PrinterFlags, Printer};
pub mod args; pub mod args;
mod cache; mod cache;
@ -133,13 +134,13 @@ fn check(args: CheckArgs, log_level: LogLevel) -> Result<ExitStatus> {
// but not apply fixes. That would allow us to avoid special-casing JSON // but not apply fixes. That would allow us to avoid special-casing JSON
// here. // here.
let autofix = if cli.diff { let autofix = if cli.diff {
fix::FixMode::Diff flags::FixMode::Diff
} else if fix || fix_only { } else if fix || fix_only {
fix::FixMode::Apply flags::FixMode::Apply
} else if matches!(format, SerializationFormat::Json) { } else if matches!(format, SerializationFormat::Json) {
fix::FixMode::Generate flags::FixMode::Generate
} else { } else {
fix::FixMode::None flags::FixMode::None
}; };
let cache = !cli.no_cache; let cache = !cli.no_cache;
let noqa = !cli.ignore_noqa; let noqa = !cli.ignore_noqa;
@ -159,7 +160,7 @@ fn check(args: CheckArgs, log_level: LogLevel) -> Result<ExitStatus> {
} }
if cli.add_noqa { if cli.add_noqa {
if !matches!(autofix, fix::FixMode::None) { if !matches!(autofix, flags::FixMode::None) {
warn_user_once!("--fix is incompatible with --add-noqa."); warn_user_once!("--fix is incompatible with --add-noqa.");
} }
let modifications = let modifications =
@ -177,7 +178,7 @@ fn check(args: CheckArgs, log_level: LogLevel) -> Result<ExitStatus> {
let printer = Printer::new(format, log_level, autofix, printer_flags); let printer = Printer::new(format, log_level, autofix, printer_flags);
if cli.watch { if cli.watch {
if !matches!(autofix, fix::FixMode::None) { if !matches!(autofix, flags::FixMode::None) {
warn_user_once!("--fix is unsupported in watch mode."); warn_user_once!("--fix is unsupported in watch mode.");
} }
if format != SerializationFormat::Text { if format != SerializationFormat::Text {
@ -194,7 +195,7 @@ fn check(args: CheckArgs, log_level: LogLevel) -> Result<ExitStatus> {
&overrides, &overrides,
cache.into(), cache.into(),
noqa.into(), noqa.into(),
fix::FixMode::None, flags::FixMode::None,
)?; )?;
printer.write_continuously(&messages)?; printer.write_continuously(&messages)?;
@ -224,7 +225,7 @@ fn check(args: CheckArgs, log_level: LogLevel) -> Result<ExitStatus> {
&overrides, &overrides,
cache.into(), cache.into(),
noqa.into(), noqa.into(),
fix::FixMode::None, flags::FixMode::None,
)?; )?;
printer.write_continuously(&messages)?; printer.write_continuously(&messages)?;
} }
@ -258,7 +259,7 @@ fn check(args: CheckArgs, log_level: LogLevel) -> Result<ExitStatus> {
// Always try to print violations (the printer itself may suppress output), // Always try to print violations (the printer itself may suppress output),
// unless we're writing fixes via stdin (in which case, the transformed // unless we're writing fixes via stdin (in which case, the transformed
// source code goes to stdout). // source code goes to stdout).
if !(is_stdin && matches!(autofix, fix::FixMode::Apply | fix::FixMode::Diff)) { if !(is_stdin && matches!(autofix, flags::FixMode::Apply | flags::FixMode::Diff)) {
if cli.statistics { if cli.statistics {
printer.write_statistics(&diagnostics)?; printer.write_statistics(&diagnostics)?;
} else { } else {

View File

@ -23,9 +23,10 @@ use ruff::jupyter::JupyterIndex;
use ruff::linter::FixTable; use ruff::linter::FixTable;
use ruff::logging::LogLevel; use ruff::logging::LogLevel;
use ruff::message::{Location, Message}; use ruff::message::{Location, Message};
use ruff::notify_user;
use ruff::registry::{AsRule, Rule}; use ruff::registry::{AsRule, Rule};
use ruff::settings::flags;
use ruff::settings::types::SerializationFormat; use ruff::settings::types::SerializationFormat;
use ruff::{fix, notify_user};
use crate::diagnostics::Diagnostics; use crate::diagnostics::Diagnostics;
@ -89,7 +90,7 @@ impl From<Rule> for SerializeRuleAsCode {
pub struct Printer { pub struct Printer {
format: SerializationFormat, format: SerializationFormat,
log_level: LogLevel, log_level: LogLevel,
autofix_level: fix::FixMode, autofix_level: flags::FixMode,
flags: Flags, flags: Flags,
} }
@ -97,7 +98,7 @@ impl Printer {
pub const fn new( pub const fn new(
format: SerializationFormat, format: SerializationFormat,
log_level: LogLevel, log_level: LogLevel,
autofix_level: fix::FixMode, autofix_level: flags::FixMode,
flags: Flags, flags: Flags,
) -> Self { ) -> Self {
Self { Self {
@ -157,9 +158,9 @@ impl Printer {
.sum::<usize>(); .sum::<usize>();
if fixed > 0 { if fixed > 0 {
let s = if fixed == 1 { "" } else { "s" }; let s = if fixed == 1 { "" } else { "s" };
if matches!(self.autofix_level, fix::FixMode::Apply) { if matches!(self.autofix_level, flags::FixMode::Apply) {
writeln!(stdout, "Fixed {fixed} error{s}.")?; writeln!(stdout, "Fixed {fixed} error{s}.")?;
} else if matches!(self.autofix_level, fix::FixMode::Diff) { } else if matches!(self.autofix_level, flags::FixMode::Diff) {
writeln!(stdout, "Would fix {fixed} error{s}.")?; writeln!(stdout, "Would fix {fixed} error{s}.")?;
} }
} }
@ -639,7 +640,7 @@ fn fingerprint(message: &Message) -> String {
format!("{:x}", hasher.finish()) format!("{:x}", hasher.finish())
} }
struct CodeAndBody<'a>(&'a Message, fix::FixMode); struct CodeAndBody<'a>(&'a Message, flags::FixMode);
impl Display for CodeAndBody<'_> { impl Display for CodeAndBody<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
@ -663,20 +664,20 @@ impl Display for CodeAndBody<'_> {
} }
/// Return `true` if the [`Printer`] should indicate that a rule is fixable. /// Return `true` if the [`Printer`] should indicate that a rule is fixable.
fn show_fix_status(autofix_level: fix::FixMode) -> bool { fn show_fix_status(autofix_level: flags::FixMode) -> bool {
// If we're in application mode, avoid indicating that a rule is fixable. // If we're in application mode, avoid indicating that a rule is fixable.
// If the specific violation were truly fixable, it would've been fixed in // If the specific violation were truly fixable, it would've been fixed in
// this pass! (We're occasionally unable to determine whether a specific // this pass! (We're occasionally unable to determine whether a specific
// violation is fixable without trying to fix it, so if autofix is not // violation is fixable without trying to fix it, so if autofix is not
// enabled, we may inadvertently indicate that a rule is fixable.) // enabled, we may inadvertently indicate that a rule is fixable.)
!matches!(autofix_level, fix::FixMode::Apply) !matches!(autofix_level, flags::FixMode::Apply)
} }
/// Print a single `Message` with full details. /// Print a single `Message` with full details.
fn print_message<T: Write>( fn print_message<T: Write>(
stdout: &mut T, stdout: &mut T,
message: &Message, message: &Message,
autofix_level: fix::FixMode, autofix_level: flags::FixMode,
jupyter_index: &FxHashMap<String, JupyterIndex>, jupyter_index: &FxHashMap<String, JupyterIndex>,
) -> Result<()> { ) -> Result<()> {
// Check if we're working on a jupyter notebook and translate positions with cell accordingly // Check if we're working on a jupyter notebook and translate positions with cell accordingly
@ -796,7 +797,7 @@ fn print_fixed<T: Write>(stdout: &mut T, fixed: &FxHashMap<String, FixTable>) ->
fn print_grouped_message<T: Write>( fn print_grouped_message<T: Write>(
stdout: &mut T, stdout: &mut T,
message: &Message, message: &Message,
autofix_level: fix::FixMode, autofix_level: flags::FixMode,
row_length: usize, row_length: usize,
column_length: usize, column_length: usize,
jupyter_index: Option<&JupyterIndex>, jupyter_index: Option<&JupyterIndex>,