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;
mod doc_lines;
mod docstrings;
pub mod fix;
pub mod flake8_to_ruff;
pub mod fs;
pub mod jupyter;

View File

@ -1,17 +1,34 @@
use crate::fix;
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)]
pub enum Autofix {
Enabled,
Disabled,
}
impl From<fix::FixMode> for Autofix {
fn from(value: fix::FixMode) -> Self {
impl From<FixMode> for Autofix {
fn from(value: FixMode) -> Self {
match value {
fix::FixMode::Generate | fix::FixMode::Diff | fix::FixMode::Apply => Self::Enabled,
fix::FixMode::None => Self::Disabled,
FixMode::Generate | FixMode::Diff | FixMode::Apply => Self::Enabled,
FixMode::None => Self::Disabled,
}
}
}

View File

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

View File

@ -5,7 +5,7 @@ use anyhow::Result;
use ruff::resolver::PyprojectDiscovery;
use ruff::settings::flags;
use ruff::{fix, packaging, resolver};
use ruff::{packaging, resolver};
use crate::args::Overrides;
use crate::diagnostics::{lint_stdin, Diagnostics};
@ -23,7 +23,7 @@ pub fn run_stdin(
pyproject_strategy: &PyprojectDiscovery,
overrides: &Overrides,
noqa: flags::Noqa,
autofix: fix::FixMode,
autofix: flags::FixMode,
) -> Result<Diagnostics> {
if let Some(filename) = filename {
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 similar::TextDiff;
use ruff::fs;
use ruff::jupyter::{is_jupyter_notebook, JupyterIndex, JupyterNotebook};
use ruff::linter::{lint_fix, lint_only, FixTable, LinterResult};
use ruff::message::Message;
use ruff::settings::{flags, AllSettings, Settings};
use ruff::{fix, fs};
use crate::cache;
@ -100,7 +100,7 @@ pub fn lint_path(
settings: &AllSettings,
cache: flags::Cache,
noqa: flags::Noqa,
autofix: fix::FixMode,
autofix: flags::FixMode,
) -> Result<Diagnostics> {
// Check the cache.
// 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.)
let metadata = if cache.into()
&& noqa.into()
&& matches!(autofix, fix::FixMode::None | fix::FixMode::Generate)
&& matches!(autofix, flags::FixMode::None | flags::FixMode::Generate)
{
let metadata = path.metadata()?;
if let Some(messages) =
@ -143,14 +143,14 @@ pub fn lint_path(
error: parse_error,
},
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(&contents, path, package, noqa, &settings.lib)
{
if !fixed.is_empty() {
if matches!(autofix, fix::FixMode::Apply) {
if matches!(autofix, flags::FixMode::Apply) {
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();
TextDiff::from_lines(contents.as_str(), &transformed)
.unified_diff()
@ -243,7 +243,7 @@ pub fn lint_stdin(
contents: &str,
settings: &Settings,
noqa: flags::Noqa,
autofix: fix::FixMode,
autofix: flags::FixMode,
) -> Result<Diagnostics> {
// Lint the inputs.
let (
@ -252,7 +252,7 @@ pub fn lint_stdin(
error: parse_error,
},
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(
contents,
path.unwrap_or_else(|| Path::new("-")),
@ -260,10 +260,10 @@ pub fn lint_stdin(
noqa,
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.
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.
if !fixed.is_empty() {
let text_diff = TextDiff::from_lines(contents, &transformed);
@ -293,7 +293,7 @@ pub fn lint_stdin(
let fixed = FxHashMap::default();
// 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())?;
}

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::path::PathBuf;
use std::process::ExitCode;
use std::sync::mpsc::channel;
use crate::args::{Args, CheckArgs, Command};
use crate::printer::{Flags as PrinterFlags, Printer};
use anyhow::Result;
use clap::CommandFactory;
use notify::{recommended_watcher, RecursiveMode, Watcher};
use ruff::logging::{set_up_logging, LogLevel};
use ruff::settings::types::SerializationFormat;
use ruff::settings::CliSettings;
use ruff::{fix, fs, warn_user_once};
use ruff::settings::{flags, CliSettings};
use ruff::{fs, warn_user_once};
use crate::args::{Args, CheckArgs, Command};
use crate::printer::{Flags as PrinterFlags, Printer};
pub mod args;
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
// here.
let autofix = if cli.diff {
fix::FixMode::Diff
flags::FixMode::Diff
} else if fix || fix_only {
fix::FixMode::Apply
flags::FixMode::Apply
} else if matches!(format, SerializationFormat::Json) {
fix::FixMode::Generate
flags::FixMode::Generate
} else {
fix::FixMode::None
flags::FixMode::None
};
let cache = !cli.no_cache;
let noqa = !cli.ignore_noqa;
@ -159,7 +160,7 @@ fn check(args: CheckArgs, log_level: LogLevel) -> Result<ExitStatus> {
}
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.");
}
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);
if cli.watch {
if !matches!(autofix, fix::FixMode::None) {
if !matches!(autofix, flags::FixMode::None) {
warn_user_once!("--fix is unsupported in watch mode.");
}
if format != SerializationFormat::Text {
@ -194,7 +195,7 @@ fn check(args: CheckArgs, log_level: LogLevel) -> Result<ExitStatus> {
&overrides,
cache.into(),
noqa.into(),
fix::FixMode::None,
flags::FixMode::None,
)?;
printer.write_continuously(&messages)?;
@ -224,7 +225,7 @@ fn check(args: CheckArgs, log_level: LogLevel) -> Result<ExitStatus> {
&overrides,
cache.into(),
noqa.into(),
fix::FixMode::None,
flags::FixMode::None,
)?;
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),
// unless we're writing fixes via stdin (in which case, the transformed
// 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 {
printer.write_statistics(&diagnostics)?;
} else {

View File

@ -23,9 +23,10 @@ use ruff::jupyter::JupyterIndex;
use ruff::linter::FixTable;
use ruff::logging::LogLevel;
use ruff::message::{Location, Message};
use ruff::notify_user;
use ruff::registry::{AsRule, Rule};
use ruff::settings::flags;
use ruff::settings::types::SerializationFormat;
use ruff::{fix, notify_user};
use crate::diagnostics::Diagnostics;
@ -89,7 +90,7 @@ impl From<Rule> for SerializeRuleAsCode {
pub struct Printer {
format: SerializationFormat,
log_level: LogLevel,
autofix_level: fix::FixMode,
autofix_level: flags::FixMode,
flags: Flags,
}
@ -97,7 +98,7 @@ impl Printer {
pub const fn new(
format: SerializationFormat,
log_level: LogLevel,
autofix_level: fix::FixMode,
autofix_level: flags::FixMode,
flags: Flags,
) -> Self {
Self {
@ -157,9 +158,9 @@ impl Printer {
.sum::<usize>();
if fixed > 0 {
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}.")?;
} 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}.")?;
}
}
@ -639,7 +640,7 @@ fn fingerprint(message: &Message) -> String {
format!("{:x}", hasher.finish())
}
struct CodeAndBody<'a>(&'a Message, fix::FixMode);
struct CodeAndBody<'a>(&'a Message, flags::FixMode);
impl Display for CodeAndBody<'_> {
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.
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 the specific violation were truly fixable, it would've been fixed in
// this pass! (We're occasionally unable to determine whether a specific
// violation is fixable without trying to fix it, so if autofix is not
// 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.
fn print_message<T: Write>(
stdout: &mut T,
message: &Message,
autofix_level: fix::FixMode,
autofix_level: flags::FixMode,
jupyter_index: &FxHashMap<String, JupyterIndex>,
) -> Result<()> {
// 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>(
stdout: &mut T,
message: &Message,
autofix_level: fix::FixMode,
autofix_level: flags::FixMode,
row_length: usize,
column_length: usize,
jupyter_index: Option<&JupyterIndex>,