Rename Autofix to Fix (#7657)

**Summary** Mostly mechanical symbol rename and search-and-replace, with
small changes to the markdown docs to read better
This commit is contained in:
konsti 2023-09-28 12:53:05 +02:00 committed by GitHub
parent 8028de8956
commit 1e173f7909
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
231 changed files with 943 additions and 960 deletions

1
.github/release.yml vendored
View file

@ -12,7 +12,6 @@ changelog:
- title: Rules - title: Rules
labels: labels:
- rule - rule
- autofix
- title: Settings - title: Settings
labels: labels:
- configuration - configuration

View file

@ -204,7 +204,7 @@ As such, rule names should...
For example, `AssertFalse` guards against `assert False` statements. For example, `AssertFalse` guards against `assert False` statements.
- _Not_ contain instructions on how to fix the violation, which instead belong in the rule - _Not_ contain instructions on how to fix the violation, which instead belong in the rule
documentation and the `autofix_title`. documentation and the `fix_title`.
- _Not_ contain a redundant prefix, like `Disallow` or `Banned`, which are already implied by the - _Not_ contain a redundant prefix, like `Disallow` or `Banned`, which are already implied by the
convention. convention.

View file

@ -29,7 +29,7 @@ An extremely fast Python linter, written in Rust.
- 🛠️ `pyproject.toml` support - 🛠️ `pyproject.toml` support
- 🤝 Python 3.11 compatibility - 🤝 Python 3.11 compatibility
- 📦 Built-in caching, to avoid re-analyzing unchanged files - 📦 Built-in caching, to avoid re-analyzing unchanged files
- 🔧 Autofix support, for automatic error correction (e.g., automatically remove unused imports) - 🔧 Fix support, for automatic error correction (e.g., automatically remove unused imports)
- 📏 Over [700 built-in rules](https://docs.astral.sh/ruff/rules/) - 📏 Over [700 built-in rules](https://docs.astral.sh/ruff/rules/)
- ⚖️ [Near-parity](https://docs.astral.sh/ruff/faq/#how-does-ruff-compare-to-flake8) with the - ⚖️ [Near-parity](https://docs.astral.sh/ruff/faq/#how-does-ruff-compare-to-flake8) with the
built-in Flake8 rule set built-in Flake8 rule set
@ -176,7 +176,7 @@ If left unspecified, the default configuration is equivalent to:
select = ["E", "F"] select = ["E", "F"]
ignore = [] ignore = []
# Allow autofix for all enabled rules (when `--fix`) is provided. # Allow fix for all enabled rules (when `--fix`) is provided.
fixable = ["A", "B", "C", "D", "E", "F", "G", "I", "N", "Q", "S", "T", "W", "ANN", "ARG", "BLE", "COM", "DJ", "DTZ", "EM", "ERA", "EXE", "FBT", "ICN", "INP", "ISC", "NPY", "PD", "PGH", "PIE", "PL", "PT", "PTH", "PYI", "RET", "RSE", "RUF", "SIM", "SLF", "TCH", "TID", "TRY", "UP", "YTT"] fixable = ["A", "B", "C", "D", "E", "F", "G", "I", "N", "Q", "S", "T", "W", "ANN", "ARG", "BLE", "COM", "DJ", "DTZ", "EM", "ERA", "EXE", "FBT", "ICN", "INP", "ISC", "NPY", "PD", "PGH", "PIE", "PL", "PT", "PTH", "PYI", "RET", "RSE", "RUF", "SIM", "SLF", "TCH", "TID", "TRY", "UP", "YTT"]
unfixable = [] unfixable = []

View file

@ -88,7 +88,7 @@ pub struct CheckCommand {
show_source: bool, show_source: bool,
#[clap(long, overrides_with("show_source"), hide = true)] #[clap(long, overrides_with("show_source"), hide = true)]
no_show_source: bool, no_show_source: bool,
/// Show an enumeration of all autofixed lint violations. /// Show an enumeration of all fixed lint violations.
/// Use `--no-show-fixes` to disable. /// Use `--no-show-fixes` to disable.
#[arg(long, overrides_with("no_show_fixes"))] #[arg(long, overrides_with("no_show_fixes"))]
show_fixes: bool, show_fixes: bool,
@ -202,7 +202,7 @@ pub struct CheckCommand {
help_heading = "File selection" help_heading = "File selection"
)] )]
pub extend_exclude: Option<Vec<FilePattern>>, pub extend_exclude: Option<Vec<FilePattern>>,
/// List of rule codes to treat as eligible for autofix. Only applicable when autofix itself is enabled (e.g., via `--fix`). /// List of rule codes to treat as eligible for fix. Only applicable when fix itself is enabled (e.g., via `--fix`).
#[arg( #[arg(
long, long,
value_delimiter = ',', value_delimiter = ',',
@ -212,7 +212,7 @@ pub struct CheckCommand {
hide_possible_values = true hide_possible_values = true
)] )]
pub fixable: Option<Vec<RuleSelector>>, pub fixable: Option<Vec<RuleSelector>>,
/// List of rule codes to treat as ineligible for autofix. Only applicable when autofix itself is enabled (e.g., via `--fix`). /// List of rule codes to treat as ineligible for fix. Only applicable when fix itself is enabled (e.g., via `--fix`).
#[arg( #[arg(
long, long,
value_delimiter = ',', value_delimiter = ',',
@ -288,7 +288,7 @@ pub struct CheckCommand {
conflicts_with = "exit_non_zero_on_fix" conflicts_with = "exit_non_zero_on_fix"
)] )]
pub exit_zero: bool, pub exit_zero: bool,
/// Exit with a non-zero status code if any files were modified via autofix, even if no lint violations remain. /// Exit with a non-zero status code if any files were modified via fix, even if no lint violations remain.
#[arg(long, help_heading = "Miscellaneous", conflicts_with = "exit_zero")] #[arg(long, help_heading = "Miscellaneous", conflicts_with = "exit_zero")]
pub exit_non_zero_on_fix: bool, pub exit_non_zero_on_fix: bool,
/// Show counts for every rule with at least one violation. /// Show counts for every rule with at least one violation.

View file

@ -35,7 +35,7 @@ pub(crate) fn check(
overrides: &CliOverrides, overrides: &CliOverrides,
cache: flags::Cache, cache: flags::Cache,
noqa: flags::Noqa, noqa: flags::Noqa,
autofix: flags::FixMode, fix_mode: 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();
@ -119,7 +119,7 @@ pub(crate) fn check(
} }
}); });
lint_path(path, package, &settings.linter, cache, noqa, autofix).map_err(|e| { lint_path(path, package, &settings.linter, cache, noqa, fix_mode).map_err(|e| {
(Some(path.to_owned()), { (Some(path.to_owned()), {
let mut error = e.to_string(); let mut error = e.to_string();
for cause in e.chain() { for cause in e.chain() {
@ -198,10 +198,10 @@ fn lint_path(
settings: &LinterSettings, settings: &LinterSettings,
cache: Option<&Cache>, cache: Option<&Cache>,
noqa: flags::Noqa, noqa: flags::Noqa,
autofix: flags::FixMode, fix_mode: 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, fix_mode)
}); });
match result { match result {

View file

@ -16,7 +16,7 @@ pub(crate) fn check_stdin(
pyproject_config: &PyprojectConfig, pyproject_config: &PyprojectConfig,
overrides: &CliOverrides, overrides: &CliOverrides,
noqa: flags::Noqa, noqa: flags::Noqa,
autofix: flags::FixMode, fix_mode: flags::FixMode,
) -> Result<Diagnostics> { ) -> Result<Diagnostics> {
if let Some(filename) = filename { if let Some(filename) = filename {
if !python_file_at_path(filename, pyproject_config, overrides)? { if !python_file_at_path(filename, pyproject_config, overrides)? {
@ -33,7 +33,7 @@ pub(crate) fn check_stdin(
stdin, stdin,
&pyproject_config.settings, &pyproject_config.settings,
noqa, noqa,
autofix, fix_mode,
)?; )?;
diagnostics.messages.sort_unstable(); diagnostics.messages.sort_unstable();
Ok(diagnostics) Ok(diagnostics)

View file

@ -5,7 +5,7 @@ use serde::ser::SerializeSeq;
use serde::{Serialize, Serializer}; use serde::{Serialize, Serializer};
use strum::IntoEnumIterator; use strum::IntoEnumIterator;
use ruff_diagnostics::AutofixKind; use ruff_diagnostics::FixKind;
use ruff_linter::registry::{Linter, Rule, RuleNamespace}; use ruff_linter::registry::{Linter, Rule, RuleNamespace};
use crate::args::HelpFormat; use crate::args::HelpFormat;
@ -17,7 +17,7 @@ struct Explanation<'a> {
linter: &'a str, linter: &'a str,
summary: &'a str, summary: &'a str,
message_formats: &'a [&'a str], message_formats: &'a [&'a str],
autofix: String, fix: String,
explanation: Option<&'a str>, explanation: Option<&'a str>,
preview: bool, preview: bool,
} }
@ -26,14 +26,14 @@ impl<'a> Explanation<'a> {
fn from_rule(rule: &'a Rule) -> Self { fn from_rule(rule: &'a Rule) -> Self {
let code = rule.noqa_code().to_string(); let code = rule.noqa_code().to_string();
let (linter, _) = Linter::parse_code(&code).unwrap(); let (linter, _) = Linter::parse_code(&code).unwrap();
let autofix = rule.autofixable().to_string(); let fix = rule.fixable().to_string();
Self { Self {
name: rule.as_ref(), name: rule.as_ref(),
code, code,
linter: linter.name(), linter: linter.name(),
summary: rule.message_formats()[0], summary: rule.message_formats()[0],
message_formats: rule.message_formats(), message_formats: rule.message_formats(),
autofix, fix,
explanation: rule.explanation(), explanation: rule.explanation(),
preview: rule.is_preview(), preview: rule.is_preview(),
} }
@ -51,9 +51,9 @@ fn format_rule_text(rule: Rule) -> String {
output.push('\n'); output.push('\n');
output.push('\n'); output.push('\n');
let autofix = rule.autofixable(); let fix_kind = rule.fixable();
if matches!(autofix, AutofixKind::Always | AutofixKind::Sometimes) { if matches!(fix_kind, FixKind::Always | FixKind::Sometimes) {
output.push_str(&autofix.to_string()); output.push_str(&fix_kind.to_string());
output.push('\n'); output.push('\n');
output.push('\n'); output.push('\n');
} }

View file

@ -147,7 +147,7 @@ pub(crate) fn lint_path(
settings: &LinterSettings, settings: &LinterSettings,
cache: Option<&Cache>, cache: Option<&Cache>,
noqa: flags::Noqa, noqa: flags::Noqa,
autofix: flags::FixMode, fix_mode: 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
@ -156,7 +156,7 @@ pub(crate) fn lint_path(
// write the fixes to disk, thus invalidating the cache. But it's a bit hard // write the fixes to disk, thus invalidating the cache. But it's a bit hard
// 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 caching = match cache { let caching = match cache {
Some(cache) if noqa.into() && autofix.is_generate() => { Some(cache) if noqa.into() && fix_mode.is_generate() => {
let relative_path = cache let relative_path = cache
.relative_path(path) .relative_path(path)
.expect("wrong package cache for file"); .expect("wrong package cache for file");
@ -220,7 +220,7 @@ pub(crate) fn lint_path(
error: parse_error, error: parse_error,
}, },
fixed, fixed,
) = if matches!(autofix, flags::FixMode::Apply | flags::FixMode::Diff) { ) = if matches!(fix_mode, flags::FixMode::Apply | flags::FixMode::Diff) {
if let Ok(FixerResult { if let Ok(FixerResult {
result, result,
transformed, transformed,
@ -228,7 +228,7 @@ pub(crate) fn lint_path(
}) = lint_fix(path, package, noqa, settings, &source_kind, source_type) }) = lint_fix(path, package, noqa, settings, &source_kind, source_type)
{ {
if !fixed.is_empty() { if !fixed.is_empty() {
match autofix { match fix_mode {
flags::FixMode::Apply => match transformed.as_ref() { flags::FixMode::Apply => match transformed.as_ref() {
SourceKind::Python(transformed) => { SourceKind::Python(transformed) => {
write(path, transformed.as_bytes())?; write(path, transformed.as_bytes())?;
@ -301,7 +301,7 @@ pub(crate) fn lint_path(
} }
(result, fixed) (result, fixed)
} else { } else {
// If we fail to autofix, lint the original source code. // If we fail to fix, lint the original source code.
let result = lint_only(path, package, settings, noqa, &source_kind, source_type); let result = lint_only(path, package, settings, noqa, &source_kind, source_type);
let fixed = FxHashMap::default(); let fixed = FxHashMap::default();
(result, fixed) (result, fixed)
@ -369,7 +369,7 @@ pub(crate) fn lint_stdin(
contents: String, contents: String,
settings: &Settings, settings: &Settings,
noqa: flags::Noqa, noqa: flags::Noqa,
autofix: flags::FixMode, fix_mode: flags::FixMode,
) -> Result<Diagnostics> { ) -> Result<Diagnostics> {
// TODO(charlie): Support `pyproject.toml`. // TODO(charlie): Support `pyproject.toml`.
let SourceType::Python(source_type) = path.map(SourceType::from).unwrap_or_default() else { let SourceType::Python(source_type) = path.map(SourceType::from).unwrap_or_default() else {
@ -392,7 +392,7 @@ pub(crate) fn lint_stdin(
error: parse_error, error: parse_error,
}, },
fixed, fixed,
) = if matches!(autofix, flags::FixMode::Apply | flags::FixMode::Diff) { ) = if matches!(fix_mode, flags::FixMode::Apply | flags::FixMode::Diff) {
if let Ok(FixerResult { if let Ok(FixerResult {
result, result,
transformed, transformed,
@ -405,7 +405,7 @@ pub(crate) fn lint_stdin(
&source_kind, &source_kind,
source_type, source_type,
) { ) {
match autofix { match fix_mode {
flags::FixMode::Apply => { 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.source_code().as_bytes())?; io::stdout().write_all(transformed.source_code().as_bytes())?;
@ -434,7 +434,7 @@ pub(crate) fn lint_stdin(
(result, fixed) (result, fixed)
} else { } else {
// If we fail to autofix, lint the original source code. // If we fail to fix, lint the original source code.
let result = lint_only( let result = lint_only(
path.unwrap_or_else(|| Path::new("-")), path.unwrap_or_else(|| Path::new("-")),
package, package,
@ -446,7 +446,7 @@ pub(crate) fn lint_stdin(
let fixed = FxHashMap::default(); let fixed = FxHashMap::default();
// Write the contents to stdout anyway. // Write the contents to stdout anyway.
if autofix.is_apply() { if fix_mode.is_apply() {
io::stdout().write_all(source_kind.source_code().as_bytes())?; io::stdout().write_all(source_kind.source_code().as_bytes())?;
} }

View file

@ -234,13 +234,13 @@ pub fn check(args: CheckCommand, log_level: LogLevel) -> Result<ExitStatus> {
.. ..
} = pyproject_config.settings; } = pyproject_config.settings;
// Autofix rules are as follows: // Fix rules are as follows:
// - By default, generate all fixes, but don't apply them to the filesystem. // - By default, generate all fixes, but don't apply them to the filesystem.
// - If `--fix` or `--fix-only` is set, always apply fixes to the filesystem (or // - If `--fix` or `--fix-only` is set, always apply fixes to the filesystem (or
// print them to stdout, if we're reading from stdin). // print them to stdout, if we're reading from stdin).
// - If `--diff` or `--fix-only` are set, don't print any violations (only // - If `--diff` or `--fix-only` are set, don't print any violations (only
// fixes). // fixes).
let autofix = if cli.diff { let fix_mode = if cli.diff {
flags::FixMode::Diff flags::FixMode::Diff
} else if fix || fix_only { } else if fix || fix_only {
flags::FixMode::Apply flags::FixMode::Apply
@ -275,7 +275,7 @@ pub fn check(args: CheckCommand, log_level: LogLevel) -> Result<ExitStatus> {
} }
if cli.add_noqa { if cli.add_noqa {
if !autofix.is_generate() { if !fix_mode.is_generate() {
warn_user!("--fix is incompatible with --add-noqa."); warn_user!("--fix is incompatible with --add-noqa.");
} }
let modifications = let modifications =
@ -290,7 +290,7 @@ pub fn check(args: CheckCommand, log_level: LogLevel) -> Result<ExitStatus> {
return Ok(ExitStatus::Success); return Ok(ExitStatus::Success);
} }
let printer = Printer::new(output_format, log_level, autofix, printer_flags); let printer = Printer::new(output_format, log_level, fix_mode, printer_flags);
if cli.watch { if cli.watch {
if output_format != SerializationFormat::Text { if output_format != SerializationFormat::Text {
@ -317,7 +317,7 @@ pub fn check(args: CheckCommand, log_level: LogLevel) -> Result<ExitStatus> {
&overrides, &overrides,
cache.into(), cache.into(),
noqa.into(), noqa.into(),
autofix, fix_mode,
)?; )?;
printer.write_continuously(&mut writer, &messages)?; printer.write_continuously(&mut writer, &messages)?;
@ -349,7 +349,7 @@ pub fn check(args: CheckCommand, log_level: LogLevel) -> Result<ExitStatus> {
&overrides, &overrides,
cache.into(), cache.into(),
noqa.into(), noqa.into(),
autofix, fix_mode,
)?; )?;
printer.write_continuously(&mut writer, &messages)?; printer.write_continuously(&mut writer, &messages)?;
} }
@ -366,7 +366,7 @@ pub fn check(args: CheckCommand, log_level: LogLevel) -> Result<ExitStatus> {
&pyproject_config, &pyproject_config,
&overrides, &overrides,
noqa.into(), noqa.into(),
autofix, fix_mode,
)? )?
} else { } else {
commands::check::check( commands::check::check(
@ -375,14 +375,14 @@ pub fn check(args: CheckCommand, log_level: LogLevel) -> Result<ExitStatus> {
&overrides, &overrides,
cache.into(), cache.into(),
noqa.into(), noqa.into(),
autofix, fix_mode,
)? )?
}; };
// 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, flags::FixMode::Apply | flags::FixMode::Diff)) { if !(is_stdin && matches!(fix_mode, flags::FixMode::Apply | flags::FixMode::Diff)) {
if cli.statistics { if cli.statistics {
printer.write_statistics(&diagnostics, &mut writer)?; printer.write_statistics(&diagnostics, &mut writer)?;
} else { } else {

View file

@ -72,7 +72,7 @@ impl From<Rule> for SerializeRuleAsCode {
pub(crate) struct Printer { pub(crate) struct Printer {
format: SerializationFormat, format: SerializationFormat,
log_level: LogLevel, log_level: LogLevel,
autofix_level: flags::FixMode, fix_mode: flags::FixMode,
flags: Flags, flags: Flags,
} }
@ -80,13 +80,13 @@ impl Printer {
pub(crate) const fn new( pub(crate) const fn new(
format: SerializationFormat, format: SerializationFormat,
log_level: LogLevel, log_level: LogLevel,
autofix_level: flags::FixMode, fix_mode: flags::FixMode,
flags: Flags, flags: Flags,
) -> Self { ) -> Self {
Self { Self {
format, format,
log_level, log_level,
autofix_level, fix_mode,
flags, flags,
} }
} }
@ -118,7 +118,7 @@ impl Printer {
writeln!(writer, "Found {remaining} error{s}.")?; writeln!(writer, "Found {remaining} error{s}.")?;
} }
if show_fix_status(self.autofix_level) { if show_fix_status(self.fix_mode) {
let num_fixable = diagnostics let num_fixable = diagnostics
.messages .messages
.iter() .iter()
@ -140,7 +140,7 @@ 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 self.autofix_level.is_apply() { if self.fix_mode.is_apply() {
writeln!(writer, "Fixed {fixed} error{s}.")?; writeln!(writer, "Fixed {fixed} error{s}.")?;
} else { } else {
writeln!(writer, "Would fix {fixed} error{s}.")?; writeln!(writer, "Would fix {fixed} error{s}.")?;
@ -191,7 +191,7 @@ impl Printer {
} }
SerializationFormat::Text => { SerializationFormat::Text => {
TextEmitter::default() TextEmitter::default()
.with_show_fix_status(show_fix_status(self.autofix_level)) .with_show_fix_status(show_fix_status(self.fix_mode))
.with_show_fix_diff(self.flags.intersects(Flags::SHOW_FIX_DIFF)) .with_show_fix_diff(self.flags.intersects(Flags::SHOW_FIX_DIFF))
.with_show_source(self.flags.intersects(Flags::SHOW_SOURCE)) .with_show_source(self.flags.intersects(Flags::SHOW_SOURCE))
.emit(writer, &diagnostics.messages, &context)?; .emit(writer, &diagnostics.messages, &context)?;
@ -209,7 +209,7 @@ impl Printer {
SerializationFormat::Grouped => { SerializationFormat::Grouped => {
GroupedEmitter::default() GroupedEmitter::default()
.with_show_source(self.flags.intersects(Flags::SHOW_SOURCE)) .with_show_source(self.flags.intersects(Flags::SHOW_SOURCE))
.with_show_fix_status(show_fix_status(self.autofix_level)) .with_show_fix_status(show_fix_status(self.fix_mode))
.emit(writer, &diagnostics.messages, &context)?; .emit(writer, &diagnostics.messages, &context)?;
if self.flags.intersects(Flags::SHOW_FIX_SUMMARY) { if self.flags.intersects(Flags::SHOW_FIX_SUMMARY) {
@ -366,7 +366,7 @@ impl Printer {
let context = EmitterContext::new(&diagnostics.notebook_indexes); let context = EmitterContext::new(&diagnostics.notebook_indexes);
TextEmitter::default() TextEmitter::default()
.with_show_fix_status(show_fix_status(self.autofix_level)) .with_show_fix_status(show_fix_status(self.fix_mode))
.with_show_source(self.flags.intersects(Flags::SHOW_SOURCE)) .with_show_source(self.flags.intersects(Flags::SHOW_SOURCE))
.emit(writer, &diagnostics.messages, &context)?; .emit(writer, &diagnostics.messages, &context)?;
} }
@ -390,13 +390,13 @@ fn num_digits(n: usize) -> usize {
} }
/// Return `true` if the [`Printer`] should indicate that a rule is fixable. /// Return `true` if the [`Printer`] should indicate that a rule is fixable.
const fn show_fix_status(autofix_level: flags::FixMode) -> bool { const fn show_fix_status(fix_mode: 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 fix is not
// enabled, we may inadvertently indicate that a rule is fixable.) // enabled, we may inadvertently indicate that a rule is fixable.)
!autofix_level.is_apply() !fix_mode.is_apply()
} }
fn print_fix_summary(writer: &mut dyn Write, fixed: &FxHashMap<String, FixTable>) -> Result<()> { fn print_fix_summary(writer: &mut dyn Write, fixed: &FxHashMap<String, FixTable>) -> Result<()> {

View file

@ -136,7 +136,7 @@ fn stdin_json() {
} }
#[test] #[test]
fn stdin_autofix() { fn stdin_fix() {
let args = ["--fix"]; let args = ["--fix"];
assert_cmd_snapshot!(Command::new(get_cargo_bin(BIN_NAME)) assert_cmd_snapshot!(Command::new(get_cargo_bin(BIN_NAME))
.args(STDIN_BASE_OPTIONS) .args(STDIN_BASE_OPTIONS)
@ -154,7 +154,7 @@ fn stdin_autofix() {
} }
#[test] #[test]
fn stdin_autofix_when_not_fixable_should_still_print_contents() { fn stdin_fix_when_not_fixable_should_still_print_contents() {
let args = ["--fix"]; let args = ["--fix"];
assert_cmd_snapshot!(Command::new(get_cargo_bin(BIN_NAME)) assert_cmd_snapshot!(Command::new(get_cargo_bin(BIN_NAME))
.args(STDIN_BASE_OPTIONS) .args(STDIN_BASE_OPTIONS)
@ -173,7 +173,7 @@ fn stdin_autofix_when_not_fixable_should_still_print_contents() {
} }
#[test] #[test]
fn stdin_autofix_when_no_issues_should_still_print_contents() { fn stdin_fix_when_no_issues_should_still_print_contents() {
let args = ["--fix"]; let args = ["--fix"];
assert_cmd_snapshot!(Command::new(get_cargo_bin(BIN_NAME)) assert_cmd_snapshot!(Command::new(get_cargo_bin(BIN_NAME))
.args(STDIN_BASE_OPTIONS) .args(STDIN_BASE_OPTIONS)

View file

@ -13,7 +13,7 @@ exit_code: 0
Derived from the **Pyflakes** linter. Derived from the **Pyflakes** linter.
Autofix is sometimes available. Fix is sometimes available.
## What it does ## What it does
Checks for unused imports. Checks for unused imports.

View file

@ -8,7 +8,7 @@ use anyhow::Result;
use regex::{Captures, Regex}; use regex::{Captures, Regex};
use strum::IntoEnumIterator; use strum::IntoEnumIterator;
use ruff_diagnostics::AutofixKind; use ruff_diagnostics::FixKind;
use ruff_linter::registry::{Linter, Rule, RuleNamespace}; use ruff_linter::registry::{Linter, Rule, RuleNamespace};
use ruff_workspace::options::Options; use ruff_workspace::options::Options;
use ruff_workspace::options_base::OptionsMetadata; use ruff_workspace::options_base::OptionsMetadata;
@ -37,9 +37,9 @@ pub(crate) fn main(args: &Args) -> Result<()> {
output.push('\n'); output.push('\n');
} }
let autofix = rule.autofixable(); let fix_kind = rule.fixable();
if matches!(autofix, AutofixKind::Always | AutofixKind::Sometimes) { if matches!(fix_kind, FixKind::Always | FixKind::Sometimes) {
output.push_str(&autofix.to_string()); output.push_str(&fix_kind.to_string());
output.push('\n'); output.push('\n');
output.push('\n'); output.push('\n');
} }

View file

@ -5,7 +5,7 @@
use itertools::Itertools; use itertools::Itertools;
use strum::IntoEnumIterator; use strum::IntoEnumIterator;
use ruff_diagnostics::AutofixKind; use ruff_diagnostics::FixKind;
use ruff_linter::registry::{Linter, Rule, RuleNamespace}; use ruff_linter::registry::{Linter, Rule, RuleNamespace};
use ruff_linter::upstream_categories::UpstreamCategoryAndPrefix; use ruff_linter::upstream_categories::UpstreamCategoryAndPrefix;
use ruff_workspace::options::Options; use ruff_workspace::options::Options;
@ -20,11 +20,11 @@ fn generate_table(table_out: &mut String, rules: impl IntoIterator<Item = Rule>,
table_out.push_str("| ---- | ---- | ------- | ------: |"); table_out.push_str("| ---- | ---- | ------- | ------: |");
table_out.push('\n'); table_out.push('\n');
for rule in rules { for rule in rules {
let fix_token = match rule.autofixable() { let fix_token = match rule.fixable() {
AutofixKind::Always | AutofixKind::Sometimes => { FixKind::Always | FixKind::Sometimes => {
format!("<span style='opacity: 1'>{FIX_SYMBOL}</span>") format!("<span style='opacity: 1'>{FIX_SYMBOL}</span>")
} }
AutofixKind::None => format!("<span style='opacity: 0.1'>{FIX_SYMBOL}</span>"), FixKind::None => format!("<span style='opacity: 0.1'>{FIX_SYMBOL}</span>"),
}; };
let preview_token = if rule.is_preview() || rule.is_nursery() { let preview_token = if rule.is_preview() || rule.is_nursery() {
format!("<span style='opacity: 1'>{PREVIEW_SYMBOL}</span>") format!("<span style='opacity: 1'>{PREVIEW_SYMBOL}</span>")

View file

@ -2,7 +2,7 @@ pub use diagnostic::{Diagnostic, DiagnosticKind};
pub use edit::Edit; pub use edit::Edit;
pub use fix::{Applicability, Fix, IsolationLevel}; pub use fix::{Applicability, Fix, IsolationLevel};
pub use source_map::{SourceMap, SourceMarker}; pub use source_map::{SourceMap, SourceMarker};
pub use violation::{AlwaysAutofixableViolation, AutofixKind, Violation}; pub use violation::{AlwaysFixableViolation, FixKind, Violation};
mod diagnostic; mod diagnostic;
mod edit; mod edit;

View file

@ -1,26 +1,26 @@
use std::fmt::{Debug, Display}; use std::fmt::{Debug, Display};
#[derive(Debug, Copy, Clone)] #[derive(Debug, Copy, Clone)]
pub enum AutofixKind { pub enum FixKind {
Sometimes, Sometimes,
Always, Always,
None, None,
} }
impl Display for AutofixKind { impl Display for FixKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self { match self {
AutofixKind::Sometimes => write!(f, "Autofix is sometimes available."), FixKind::Sometimes => write!(f, "Fix is sometimes available."),
AutofixKind::Always => write!(f, "Autofix is always available."), FixKind::Always => write!(f, "Fix is always available."),
AutofixKind::None => write!(f, "Autofix is not available."), FixKind::None => write!(f, "Fix is not available."),
} }
} }
} }
pub trait Violation: Debug + PartialEq + Eq { pub trait Violation: Debug + PartialEq + Eq {
/// `None` in the case an autofix is never available or otherwise Some /// `None` in the case an fix is never available or otherwise Some
/// [`AutofixKind`] describing the available autofix. /// [`FixKind`] describing the available fix.
const AUTOFIX: AutofixKind = AutofixKind::None; const FIX_KIND: FixKind = FixKind::None;
/// The message used to describe the violation. /// The message used to describe the violation.
fn message(&self) -> String; fn message(&self) -> String;
@ -30,13 +30,13 @@ pub trait Violation: Debug + PartialEq + Eq {
None None
} }
// TODO(micha): Move `autofix_title` to `Fix`, add new `advice` method that is shown as an advice. // TODO(micha): Move `fix_title` to `Fix`, add new `advice` method that is shown as an advice.
// Change the `Diagnostic` renderer to show the advice, and render the fix message after the `Suggested fix: <here>` // Change the `Diagnostic` renderer to show the advice, and render the fix message after the `Suggested fix: <here>`
/// Returns the title for the autofix. The message is also shown as an advice as part of the diagnostics. /// Returns the title for the fix. The message is also shown as an advice as part of the diagnostics.
/// ///
/// Required for rules that have autofixes. /// Required for rules that have fixes.
fn autofix_title(&self) -> Option<String> { fn fix_title(&self) -> Option<String> {
None None
} }
@ -45,8 +45,8 @@ pub trait Violation: Debug + PartialEq + Eq {
} }
/// This trait exists just to make implementing the [`Violation`] trait more /// This trait exists just to make implementing the [`Violation`] trait more
/// convenient for violations that can always be autofixed. /// convenient for violations that can always be fixed.
pub trait AlwaysAutofixableViolation: Debug + PartialEq + Eq { pub trait AlwaysFixableViolation: Debug + PartialEq + Eq {
/// The message used to describe the violation. /// The message used to describe the violation.
fn message(&self) -> String; fn message(&self) -> String;
@ -55,31 +55,31 @@ pub trait AlwaysAutofixableViolation: Debug + PartialEq + Eq {
None None
} }
/// The title displayed for the available autofix. /// The title displayed for the available fix.
fn autofix_title(&self) -> String; fn fix_title(&self) -> String;
/// Returns the format strings used by /// Returns the format strings used by
/// [`message`](AlwaysAutofixableViolation::message). /// [`message`](AlwaysFixableViolation::message).
fn message_formats() -> &'static [&'static str]; fn message_formats() -> &'static [&'static str];
} }
/// A blanket implementation. /// A blanket implementation.
impl<VA: AlwaysAutofixableViolation> Violation for VA { impl<V: AlwaysFixableViolation> Violation for V {
const AUTOFIX: AutofixKind = AutofixKind::Always; const FIX_KIND: FixKind = FixKind::Always;
fn message(&self) -> String { fn message(&self) -> String {
<Self as AlwaysAutofixableViolation>::message(self) <Self as AlwaysFixableViolation>::message(self)
} }
fn explanation() -> Option<&'static str> { fn explanation() -> Option<&'static str> {
<Self as AlwaysAutofixableViolation>::explanation() <Self as AlwaysFixableViolation>::explanation()
} }
fn autofix_title(&self) -> Option<String> { fn fix_title(&self) -> Option<String> {
Some(<Self as AlwaysAutofixableViolation>::autofix_title(self)) Some(<Self as AlwaysFixableViolation>::fix_title(self))
} }
fn message_formats() -> &'static [&'static str] { fn message_formats() -> &'static [&'static str] {
<Self as AlwaysAutofixableViolation>::message_formats() <Self as AlwaysFixableViolation>::message_formats()
} }
} }

View file

@ -627,7 +627,7 @@ result = function(
**{'ham': spam} **{'ham': spam}
) )
# Make sure the COM812 and UP034 rules don't autofix simultaneously and cause a syntax error. # Make sure the COM812 and UP034 rules don't fix simultaneously and cause a syntax error.
the_first_one = next( the_first_one = next(
(i for i in range(10) if i // 2 == 0) # COM812 fix should include the final bracket (i for i in range(10) if i // 2 == 0) # COM812 fix should include the final bracket
) )

View file

@ -33,10 +33,10 @@ message
assert not (a or not (b or c)) assert not (a or not (b or c))
assert not (a or not (b and c)) assert not (a or not (b and c))
# detected, but no autofix for messages # detected, but no fix for messages
assert something and something_else, "error message" assert something and something_else, "error message"
assert not (something or something_else and something_third), "with message" assert not (something or something_else and something_third), "with message"
# detected, but no autofix for mixed conditions (e.g. `a or b and c`) # detected, but no fix for mixed conditions (e.g. `a or b and c`)
assert not (something or something_else and something_third) assert not (something or something_else and something_third)

View file

@ -335,7 +335,7 @@ def foo():
return x return x
# Autofix cases # Fix cases
def foo(): def foo():
a = 1 a = 1
b=a b=a

View file

@ -1,4 +1,4 @@
"""Test case for autofixing F841 violations.""" """Test case for fixing F841 violations."""
def f(): def f():

View file

@ -1,4 +1,4 @@
use crate::autofix::codemods::CodegenStylist; use crate::fix::codemods::CodegenStylist;
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use libcst_native::{ use libcst_native::{
Arg, Attribute, Call, Comparison, CompoundStatement, Dict, Expression, FunctionDef, Arg, Attribute, Call, Comparison, CompoundStatement, Dict, Expression, FunctionDef,

View file

@ -1,4 +1,4 @@
//! Interface for generating autofix edits from higher-level actions (e.g., "remove an argument"). //! Interface for generating fix edits from higher-level actions (e.g., "remove an argument").
use anyhow::{Context, Result}; use anyhow::{Context, Result};
@ -12,7 +12,7 @@ use ruff_python_trivia::{
use ruff_source_file::{Locator, NewlineWithTrailingNewline}; use ruff_source_file::{Locator, NewlineWithTrailingNewline};
use ruff_text_size::{Ranged, TextLen, TextRange, TextSize}; use ruff_text_size::{Ranged, TextLen, TextRange, TextSize};
use crate::autofix::codemods; use crate::fix::codemods;
/// Return the `Fix` to use when deleting a `Stmt`. /// Return the `Fix` to use when deleting a `Stmt`.
/// ///
@ -293,7 +293,7 @@ mod tests {
use ruff_source_file::Locator; use ruff_source_file::Locator;
use ruff_text_size::{Ranged, TextSize}; use ruff_text_size::{Ranged, TextSize};
use crate::autofix::edits::{next_stmt_break, trailing_semicolon}; use crate::fix::edits::{next_stmt_break, trailing_semicolon};
#[test] #[test]
fn find_semicolon() -> Result<()> { fn find_semicolon() -> Result<()> {

View file

@ -141,7 +141,7 @@ mod tests {
use ruff_diagnostics::{Diagnostic, Edit, Fix, SourceMarker}; use ruff_diagnostics::{Diagnostic, Edit, Fix, SourceMarker};
use ruff_source_file::Locator; use ruff_source_file::Locator;
use crate::autofix::{apply_fixes, FixResult}; use crate::fix::{apply_fixes, FixResult};
use crate::rules::pycodestyle::rules::MissingNewlineAtEndOfFile; use crate::rules::pycodestyle::rules::MissingNewlineAtEndOfFile;
#[allow(deprecated)] #[allow(deprecated)]

View file

@ -17,9 +17,9 @@ use ruff_python_semantic::SemanticModel;
use ruff_python_trivia::textwrap::indent; use ruff_python_trivia::textwrap::indent;
use ruff_source_file::Locator; use ruff_source_file::Locator;
use crate::autofix;
use crate::autofix::codemods::CodegenStylist;
use crate::cst::matchers::{match_aliases, match_import_from, match_statement}; use crate::cst::matchers::{match_aliases, match_import_from, match_statement};
use crate::fix;
use crate::fix::codemods::CodegenStylist;
use crate::importer::insertion::Insertion; use crate::importer::insertion::Insertion;
mod insertion; mod insertion;
@ -91,7 +91,7 @@ impl<'a> Importer<'a> {
at: TextSize, at: TextSize,
) -> Result<RuntimeImportEdit> { ) -> Result<RuntimeImportEdit> {
// Generate the modified import statement. // Generate the modified import statement.
let content = autofix::codemods::retain_imports( let content = fix::codemods::retain_imports(
&import.names, &import.names,
import.statement, import.statement,
self.locator, self.locator,
@ -124,7 +124,7 @@ impl<'a> Importer<'a> {
source_type: PySourceType, source_type: PySourceType,
) -> Result<TypingImportEdit> { ) -> Result<TypingImportEdit> {
// Generate the modified import statement. // Generate the modified import statement.
let content = autofix::codemods::retain_imports( let content = fix::codemods::retain_imports(
&import.names, &import.names,
import.statement, import.statement,
self.locator, self.locator,

View file

@ -14,7 +14,6 @@ pub use rules::pycodestyle::rules::{IOError, SyntaxError};
pub const VERSION: &str = env!("CARGO_PKG_VERSION"); pub const VERSION: &str = env!("CARGO_PKG_VERSION");
mod autofix;
mod checkers; mod checkers;
pub mod codes; pub mod codes;
mod comments; mod comments;
@ -22,6 +21,7 @@ mod cst;
pub mod directives; pub mod directives;
mod doc_lines; mod doc_lines;
mod docstrings; mod docstrings;
mod fix;
pub mod fs; pub mod fs;
mod importer; mod importer;
mod lex; mod lex;

View file

@ -18,7 +18,6 @@ use ruff_python_parser::{AsMode, ParseError};
use ruff_source_file::{Locator, SourceFileBuilder}; use ruff_source_file::{Locator, SourceFileBuilder};
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
use crate::autofix::{fix_file, FixResult};
use crate::checkers::ast::check_ast; use crate::checkers::ast::check_ast;
use crate::checkers::filesystem::check_file_path; use crate::checkers::filesystem::check_file_path;
use crate::checkers::imports::check_imports; use crate::checkers::imports::check_imports;
@ -27,6 +26,7 @@ use crate::checkers::physical_lines::check_physical_lines;
use crate::checkers::tokens::check_tokens; use crate::checkers::tokens::check_tokens;
use crate::directives::Directives; use crate::directives::Directives;
use crate::doc_lines::{doc_lines_from_ast, doc_lines_from_tokens}; use crate::doc_lines::{doc_lines_from_ast, doc_lines_from_tokens};
use crate::fix::{fix_file, FixResult};
use crate::logging::DisplayParseError; use crate::logging::DisplayParseError;
use crate::message::Message; use crate::message::Message;
use crate::noqa::add_noqa; use crate::noqa::add_noqa;
@ -412,7 +412,7 @@ fn diagnostics_to_messages(
.collect() .collect()
} }
/// Generate `Diagnostic`s from source code content, iteratively autofixing /// Generate `Diagnostic`s from source code content, iteratively fixing
/// until stable. /// until stable.
pub fn lint_fix<'a>( pub fn lint_fix<'a>(
path: &Path, path: &Path,
@ -433,7 +433,7 @@ pub fn lint_fix<'a>(
// Track whether the _initial_ source code was parseable. // Track whether the _initial_ source code was parseable.
let mut parseable = false; let mut parseable = false;
// Continuously autofix until the source code stabilizes. // Continuously fix until the source code stabilizes.
loop { loop {
// Tokenize once. // Tokenize once.
let tokens: Vec<LexResult> = let tokens: Vec<LexResult> =
@ -478,17 +478,17 @@ pub fn lint_fix<'a>(
// longer parseable on a subsequent pass, then we've introduced a // longer parseable on a subsequent pass, then we've introduced a
// syntax error. Return the original code. // syntax error. Return the original code.
if parseable && result.error.is_some() { if parseable && result.error.is_some() {
report_autofix_syntax_error( report_fix_syntax_error(
path, path,
transformed.source_code(), transformed.source_code(),
&result.error.unwrap(), &result.error.unwrap(),
fixed.keys().copied(), fixed.keys().copied(),
); );
return Err(anyhow!("Autofix introduced a syntax error")); return Err(anyhow!("Fix introduced a syntax error"));
} }
} }
// Apply autofix. // Apply fix.
if let Some(FixResult { if let Some(FixResult {
code: fixed_contents, code: fixed_contents,
fixes: applied, fixes: applied,
@ -569,7 +569,7 @@ This indicates a bug in Ruff. If you could open an issue at:
} }
#[allow(clippy::print_stderr)] #[allow(clippy::print_stderr)]
fn report_autofix_syntax_error( fn report_fix_syntax_error(
path: &Path, path: &Path,
transformed: &str, transformed: &str,
error: &ParseError, error: &ParseError,
@ -578,7 +578,7 @@ fn report_autofix_syntax_error(
let codes = collect_rule_codes(rules); let codes = collect_rule_codes(rules);
if cfg!(debug_assertions) { if cfg!(debug_assertions) {
eprintln!( eprintln!(
"{}{} Autofix introduced a syntax error in `{}` with rule codes {}: {}\n---\n{}\n---", "{}{} Fix introduced a syntax error in `{}` with rule codes {}: {}\n---\n{}\n---",
"error".red().bold(), "error".red().bold(),
":".bold(), ":".bold(),
fs::relativize_path(path), fs::relativize_path(path),
@ -589,11 +589,11 @@ fn report_autofix_syntax_error(
} else { } else {
eprintln!( eprintln!(
r#" r#"
{}{} Autofix introduced a syntax error. Reverting all changes. {}{} Fix introduced a syntax error. Reverting all changes.
This indicates a bug in Ruff. If you could open an issue at: This indicates a bug in Ruff. If you could open an issue at:
https://github.com/astral-sh/ruff/issues/new?title=%5BAutofix%20error%5D https://github.com/astral-sh/ruff/issues/new?title=%5BFix%20error%5D
...quoting the contents of `{}`, the rule codes {}, along with the `pyproject.toml` settings and executed command, we'd be very appreciative! ...quoting the contents of `{}`, the rule codes {}, along with the `pyproject.toml` settings and executed command, we'd be very appreciative!
"#, "#,

View file

@ -143,9 +143,9 @@ impl Display for RuleCodeAndBody<'_> {
if self.show_fix_status && self.message.fix.is_some() { if self.show_fix_status && self.message.fix.is_some() {
write!( write!(
f, f,
"{code} {autofix}{body}", "{code} {fix}{body}",
code = kind.rule().noqa_code().to_string().red().bold(), code = kind.rule().noqa_code().to_string().red().bold(),
autofix = format_args!("[{}] ", "*".cyan()), fix = format_args!("[{}] ", "*".cyan()),
body = kind.body, body = kind.body,
) )
} else { } else {

View file

@ -1,4 +1,4 @@
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_index::Indexer; use ruff_python_index::Indexer;
use ruff_source_file::Locator; use ruff_source_file::Locator;
@ -25,13 +25,13 @@ use super::super::detection::comment_contains_code;
#[violation] #[violation]
pub struct CommentedOutCode; pub struct CommentedOutCode;
impl AlwaysAutofixableViolation for CommentedOutCode { impl AlwaysFixableViolation for CommentedOutCode {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Found commented-out code") format!("Found commented-out code")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Remove commented-out code".to_string() "Remove commented-out code".to_string()
} }
} }

View file

@ -1,4 +1,4 @@
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::ReturnStatementVisitor; use ruff_python_ast::helpers::ReturnStatementVisitor;
use ruff_python_ast::identifier::Identifier; use ruff_python_ast::identifier::Identifier;
@ -287,14 +287,14 @@ pub struct MissingReturnTypeSpecialMethod {
name: String, name: String,
} }
impl AlwaysAutofixableViolation for MissingReturnTypeSpecialMethod { impl AlwaysFixableViolation for MissingReturnTypeSpecialMethod {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
let MissingReturnTypeSpecialMethod { name } = self; let MissingReturnTypeSpecialMethod { name } = self;
format!("Missing return type annotation for special method `{name}`") format!("Missing return type annotation for special method `{name}`")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Add `None` return type".to_string() "Add `None` return type".to_string()
} }
} }

View file

@ -1,7 +1,7 @@
use ruff_python_ast::{self as ast, Arguments, Expr, ExprContext, Stmt}; use ruff_python_ast::{self as ast, Arguments, Expr, ExprContext, Stmt};
use ruff_text_size::{Ranged, TextRange}; use ruff_text_size::{Ranged, TextRange};
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::is_const_false; use ruff_python_ast::helpers::is_const_false;
@ -33,13 +33,13 @@ use crate::registry::AsRule;
#[violation] #[violation]
pub struct AssertFalse; pub struct AssertFalse;
impl AlwaysAutofixableViolation for AssertFalse { impl AlwaysFixableViolation for AssertFalse {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Do not `assert False` (`python -O` removes these calls), raise `AssertionError()`") format!("Do not `assert False` (`python -O` removes these calls), raise `AssertionError()`")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Replace `assert False`".to_string() "Replace `assert False`".to_string()
} }
} }

View file

@ -3,7 +3,7 @@ use ruff_python_ast::{self as ast, ExceptHandler, Expr, ExprContext};
use ruff_text_size::{Ranged, TextRange}; use ruff_text_size::{Ranged, TextRange};
use rustc_hash::{FxHashMap, FxHashSet}; use rustc_hash::{FxHashMap, FxHashSet};
use ruff_diagnostics::{AlwaysAutofixableViolation, Violation}; use ruff_diagnostics::{AlwaysFixableViolation, Violation};
use ruff_diagnostics::{Diagnostic, Edit, Fix}; use ruff_diagnostics::{Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::call_path; use ruff_python_ast::call_path;
@ -86,7 +86,7 @@ pub struct DuplicateHandlerException {
pub names: Vec<String>, pub names: Vec<String>,
} }
impl AlwaysAutofixableViolation for DuplicateHandlerException { impl AlwaysFixableViolation for DuplicateHandlerException {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
let DuplicateHandlerException { names } = self; let DuplicateHandlerException { names } = self;
@ -98,7 +98,7 @@ impl AlwaysAutofixableViolation for DuplicateHandlerException {
} }
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"De-duplicate exceptions".to_string() "De-duplicate exceptions".to_string()
} }
} }

View file

@ -1,5 +1,5 @@
use crate::autofix::edits::pad; use crate::fix::edits::pad;
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::{self as ast, Constant, Expr}; use ruff_python_ast::{self as ast, Constant, Expr};
use ruff_python_stdlib::identifiers::{is_identifier, is_mangled_private}; use ruff_python_stdlib::identifiers::{is_identifier, is_mangled_private};
@ -34,7 +34,7 @@ use crate::registry::AsRule;
#[violation] #[violation]
pub struct GetAttrWithConstant; pub struct GetAttrWithConstant;
impl AlwaysAutofixableViolation for GetAttrWithConstant { impl AlwaysFixableViolation for GetAttrWithConstant {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!( format!(
@ -43,7 +43,7 @@ impl AlwaysAutofixableViolation for GetAttrWithConstant {
) )
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Replace `getattr` with attribute access".to_string() "Replace `getattr` with attribute access".to_string()
} }
} }

View file

@ -1,5 +1,5 @@
use ast::call_path::{from_qualified_name, CallPath}; use ast::call_path::{from_qualified_name, CallPath};
use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{Diagnostic, Edit, Fix, FixKind, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::is_docstring_stmt; use ruff_python_ast::helpers::is_docstring_stmt;
use ruff_python_ast::{self as ast, Expr, Parameter, ParameterWithDefault}; use ruff_python_ast::{self as ast, Expr, Parameter, ParameterWithDefault};
@ -64,14 +64,14 @@ use crate::registry::AsRule;
pub struct MutableArgumentDefault; pub struct MutableArgumentDefault;
impl Violation for MutableArgumentDefault { impl Violation for MutableArgumentDefault {
const AUTOFIX: AutofixKind = AutofixKind::Sometimes; const FIX_KIND: FixKind = FixKind::Sometimes;
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Do not use mutable data structures for argument defaults") format!("Do not use mutable data structures for argument defaults")
} }
fn autofix_title(&self) -> Option<String> { fn fix_title(&self) -> Option<String> {
Some(format!("Replace with `None`; initialize within function")) Some(format!("Replace with `None`; initialize within function"))
} }
} }

View file

@ -1,11 +1,11 @@
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::map_starred; use ruff_python_ast::helpers::map_starred;
use ruff_python_ast::{self as ast, ExceptHandler, Expr}; use ruff_python_ast::{self as ast, ExceptHandler, Expr};
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
use crate::autofix::edits::pad;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::fix::edits::pad;
use crate::registry::AsRule; use crate::registry::AsRule;
/// ## What it does /// ## What it does
@ -39,13 +39,13 @@ pub struct RedundantTupleInExceptionHandler {
name: String, name: String,
} }
impl AlwaysAutofixableViolation for RedundantTupleInExceptionHandler { impl AlwaysFixableViolation for RedundantTupleInExceptionHandler {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("A length-one tuple literal is redundant in exception handlers") format!("A length-one tuple literal is redundant in exception handlers")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
let RedundantTupleInExceptionHandler { name } = self; let RedundantTupleInExceptionHandler { name } = self;
format!("Replace with `except {name}`") format!("Replace with `except {name}`")
} }

View file

@ -1,7 +1,7 @@
use ruff_python_ast::{self as ast, Constant, Expr, ExprContext, Identifier, Stmt}; use ruff_python_ast::{self as ast, Constant, Expr, ExprContext, Identifier, Stmt};
use ruff_text_size::{Ranged, TextRange}; use ruff_text_size::{Ranged, TextRange};
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_codegen::Generator; use ruff_python_codegen::Generator;
use ruff_python_stdlib::identifiers::{is_identifier, is_mangled_private}; use ruff_python_stdlib::identifiers::{is_identifier, is_mangled_private};
@ -34,7 +34,7 @@ use crate::registry::AsRule;
#[violation] #[violation]
pub struct SetAttrWithConstant; pub struct SetAttrWithConstant;
impl AlwaysAutofixableViolation for SetAttrWithConstant { impl AlwaysFixableViolation for SetAttrWithConstant {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!( format!(
@ -43,7 +43,7 @@ impl AlwaysAutofixableViolation for SetAttrWithConstant {
) )
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Replace `setattr` with assignment".to_string() "Replace `setattr` with assignment".to_string()
} }
} }

View file

@ -1,6 +1,6 @@
use ruff_python_ast::{self as ast, Constant, Expr}; use ruff_python_ast::{self as ast, Constant, Expr};
use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{Diagnostic, Edit, Fix, FixKind, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
@ -37,7 +37,7 @@ use crate::registry::AsRule;
pub struct UnreliableCallableCheck; pub struct UnreliableCallableCheck;
impl Violation for UnreliableCallableCheck { impl Violation for UnreliableCallableCheck {
const AUTOFIX: AutofixKind = AutofixKind::Sometimes; const FIX_KIND: FixKind = FixKind::Sometimes;
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
@ -47,7 +47,7 @@ impl Violation for UnreliableCallableCheck {
) )
} }
fn autofix_title(&self) -> Option<String> { fn fix_title(&self) -> Option<String> {
Some(format!("Replace with `callable()`")) Some(format!("Replace with `callable()`"))
} }
} }

View file

@ -1,6 +1,6 @@
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{Diagnostic, Edit, Fix, FixKind, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::visitor::Visitor; use ruff_python_ast::visitor::Visitor;
use ruff_python_ast::{self as ast, Expr}; use ruff_python_ast::{self as ast, Expr};
@ -56,7 +56,7 @@ pub struct UnusedLoopControlVariable {
} }
impl Violation for UnusedLoopControlVariable { impl Violation for UnusedLoopControlVariable {
const AUTOFIX: AutofixKind = AutofixKind::Sometimes; const FIX_KIND: FixKind = FixKind::Sometimes;
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
@ -70,7 +70,7 @@ impl Violation for UnusedLoopControlVariable {
} }
} }
fn autofix_title(&self) -> Option<String> { fn fix_title(&self) -> Option<String> {
let UnusedLoopControlVariable { rename, name, .. } = self; let UnusedLoopControlVariable { rename, name, .. } = self;
rename rename

View file

@ -1,6 +1,6 @@
use itertools::Itertools; use itertools::Itertools;
use ruff_diagnostics::{AlwaysAutofixableViolation, Violation}; use ruff_diagnostics::{AlwaysFixableViolation, Violation};
use ruff_diagnostics::{Diagnostic, Edit, Fix}; use ruff_diagnostics::{Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_parser::lexer::{LexResult, Spanned}; use ruff_python_parser::lexer::{LexResult, Spanned};
@ -138,13 +138,13 @@ impl Context {
#[violation] #[violation]
pub struct MissingTrailingComma; pub struct MissingTrailingComma;
impl AlwaysAutofixableViolation for MissingTrailingComma { impl AlwaysFixableViolation for MissingTrailingComma {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Trailing comma missing") format!("Trailing comma missing")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Add trailing comma".to_string() "Add trailing comma".to_string()
} }
} }
@ -209,13 +209,13 @@ impl Violation for TrailingCommaOnBareTuple {
#[violation] #[violation]
pub struct ProhibitedTrailingComma; pub struct ProhibitedTrailingComma;
impl AlwaysAutofixableViolation for ProhibitedTrailingComma { impl AlwaysFixableViolation for ProhibitedTrailingComma {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Trailing comma prohibited") format!("Trailing comma prohibited")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Remove trailing comma".to_string() "Remove trailing comma".to_string()
} }
} }
@ -361,7 +361,7 @@ pub(crate) fn trailing_commas(
); );
if settings.rules.should_fix(Rule::MissingTrailingComma) { if settings.rules.should_fix(Rule::MissingTrailingComma) {
// Create a replacement that includes the final bracket (or other token), // Create a replacement that includes the final bracket (or other token),
// rather than just inserting a comma at the end. This prevents the UP034 autofix // rather than just inserting a comma at the end. This prevents the UP034 fix
// removing any brackets in the same linter pass - doing both at the same time could // removing any brackets in the same linter pass - doing both at the same time could
// lead to a syntax error. // lead to a syntax error.
let contents = locator.slice(missing_comma.1); let contents = locator.slice(missing_comma.1);

View file

@ -917,11 +917,11 @@ COM81.py:627:20: COM812 [*] Trailing comma missing
627 |+ **{'ham': spam}, 627 |+ **{'ham': spam},
628 628 | ) 628 628 | )
629 629 | 629 629 |
630 630 | # Make sure the COM812 and UP034 rules don't autofix simultaneously and cause a syntax error. 630 630 | # Make sure the COM812 and UP034 rules don't fix simultaneously and cause a syntax error.
COM81.py:632:42: COM812 [*] Trailing comma missing COM81.py:632:42: COM812 [*] Trailing comma missing
| |
630 | # Make sure the COM812 and UP034 rules don't autofix simultaneously and cause a syntax error. 630 | # Make sure the COM812 and UP034 rules don't fix simultaneously and cause a syntax error.
631 | the_first_one = next( 631 | the_first_one = next(
632 | (i for i in range(10) if i // 2 == 0) # COM812 fix should include the final bracket 632 | (i for i in range(10) if i // 2 == 0) # COM812 fix should include the final bracket
| COM812 | COM812
@ -931,7 +931,7 @@ COM81.py:632:42: COM812 [*] Trailing comma missing
Fix Fix
629 629 | 629 629 |
630 630 | # Make sure the COM812 and UP034 rules don't autofix simultaneously and cause a syntax error. 630 630 | # Make sure the COM812 and UP034 rules don't fix simultaneously and cause a syntax error.
631 631 | the_first_one = next( 631 631 | the_first_one = next(
632 |- (i for i in range(10) if i // 2 == 0) # COM812 fix should include the final bracket 632 |- (i for i in range(10) if i // 2 == 0) # COM812 fix should include the final bracket
632 |+ (i for i in range(10) if i // 2 == 0), # COM812 fix should include the final bracket 632 |+ (i for i in range(10) if i // 2 == 0), # COM812 fix should include the final bracket

View file

@ -15,9 +15,9 @@ use ruff_python_semantic::SemanticModel;
use ruff_source_file::Locator; use ruff_source_file::Locator;
use ruff_text_size::{Ranged, TextRange}; use ruff_text_size::{Ranged, TextRange};
use crate::autofix::codemods::CodegenStylist;
use crate::autofix::edits::pad;
use crate::cst::helpers::{negate, space}; use crate::cst::helpers::{negate, space};
use crate::fix::codemods::CodegenStylist;
use crate::fix::edits::pad;
use crate::rules::flake8_comprehensions::rules::ObjectType; use crate::rules::flake8_comprehensions::rules::ObjectType;
use crate::{ use crate::{
checkers::ast::Checker, checkers::ast::Checker,

View file

@ -1,4 +1,4 @@
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::{self as ast, Expr}; use ruff_python_ast::{self as ast, Expr};
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
@ -35,14 +35,14 @@ pub struct UnnecessaryCallAroundSorted {
func: String, func: String,
} }
impl AlwaysAutofixableViolation for UnnecessaryCallAroundSorted { impl AlwaysFixableViolation for UnnecessaryCallAroundSorted {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
let UnnecessaryCallAroundSorted { func } = self; let UnnecessaryCallAroundSorted { func } = self;
format!("Unnecessary `{func}` call around `sorted()`") format!("Unnecessary `{func}` call around `sorted()`")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
let UnnecessaryCallAroundSorted { func } = self; let UnnecessaryCallAroundSorted { func } = self;
format!("Remove unnecessary `{func}` call") format!("Remove unnecessary `{func}` call")
} }

View file

@ -1,4 +1,4 @@
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::{Expr, Keyword}; use ruff_python_ast::{Expr, Keyword};
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
@ -37,14 +37,14 @@ pub struct UnnecessaryCollectionCall {
obj_type: String, obj_type: String,
} }
impl AlwaysAutofixableViolation for UnnecessaryCollectionCall { impl AlwaysFixableViolation for UnnecessaryCollectionCall {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
let UnnecessaryCollectionCall { obj_type } = self; let UnnecessaryCollectionCall { obj_type } = self;
format!("Unnecessary `{obj_type}` call (rewrite as a literal)") format!("Unnecessary `{obj_type}` call (rewrite as a literal)")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Rewrite as a literal".to_string() "Rewrite as a literal".to_string()
} }
} }

View file

@ -1,4 +1,4 @@
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::comparable::ComparableExpr; use ruff_python_ast::comparable::ComparableExpr;
use ruff_python_ast::{self as ast, Comprehension, Expr}; use ruff_python_ast::{self as ast, Comprehension, Expr};
@ -34,14 +34,14 @@ pub struct UnnecessaryComprehension {
obj_type: String, obj_type: String,
} }
impl AlwaysAutofixableViolation for UnnecessaryComprehension { impl AlwaysFixableViolation for UnnecessaryComprehension {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
let UnnecessaryComprehension { obj_type } = self; let UnnecessaryComprehension { obj_type } = self;
format!("Unnecessary `{obj_type}` comprehension (rewrite using `{obj_type}()`)") format!("Unnecessary `{obj_type}` comprehension (rewrite using `{obj_type}()`)")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
let UnnecessaryComprehension { obj_type } = self; let UnnecessaryComprehension { obj_type } = self;
format!("Rewrite using `{obj_type}()`") format!("Rewrite using `{obj_type}()`")
} }

View file

@ -1,7 +1,7 @@
use ruff_python_ast::{self as ast, Expr, Keyword}; use ruff_python_ast::{self as ast, Expr, Keyword};
use ruff_diagnostics::Violation; use ruff_diagnostics::Violation;
use ruff_diagnostics::{AutofixKind, Diagnostic}; use ruff_diagnostics::{Diagnostic, FixKind};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::any_over_expr; use ruff_python_ast::helpers::any_over_expr;
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
@ -44,14 +44,14 @@ use crate::rules::flake8_comprehensions::fixes;
pub struct UnnecessaryComprehensionAnyAll; pub struct UnnecessaryComprehensionAnyAll;
impl Violation for UnnecessaryComprehensionAnyAll { impl Violation for UnnecessaryComprehensionAnyAll {
const AUTOFIX: AutofixKind = AutofixKind::Sometimes; const FIX_KIND: FixKind = FixKind::Sometimes;
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Unnecessary list comprehension.") format!("Unnecessary list comprehension.")
} }
fn autofix_title(&self) -> Option<String> { fn fix_title(&self) -> Option<String> {
Some("Remove unnecessary list comprehension".to_string()) Some("Remove unnecessary list comprehension".to_string())
} }
} }

View file

@ -1,4 +1,4 @@
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::comparable::ComparableKeyword; use ruff_python_ast::comparable::ComparableKeyword;
use ruff_python_ast::{self as ast, Arguments, Expr, Keyword}; use ruff_python_ast::{self as ast, Arguments, Expr, Keyword};
@ -49,14 +49,14 @@ pub struct UnnecessaryDoubleCastOrProcess {
outer: String, outer: String,
} }
impl AlwaysAutofixableViolation for UnnecessaryDoubleCastOrProcess { impl AlwaysFixableViolation for UnnecessaryDoubleCastOrProcess {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
let UnnecessaryDoubleCastOrProcess { inner, outer } = self; let UnnecessaryDoubleCastOrProcess { inner, outer } = self;
format!("Unnecessary `{inner}` call within `{outer}()`") format!("Unnecessary `{inner}` call within `{outer}()`")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
let UnnecessaryDoubleCastOrProcess { inner, .. } = self; let UnnecessaryDoubleCastOrProcess { inner, .. } = self;
format!("Remove the inner `{inner}` call") format!("Remove the inner `{inner}` call")
} }

View file

@ -1,4 +1,4 @@
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::{self as ast, Expr, Keyword}; use ruff_python_ast::{self as ast, Expr, Keyword};
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
@ -30,13 +30,13 @@ use super::helpers;
#[violation] #[violation]
pub struct UnnecessaryGeneratorDict; pub struct UnnecessaryGeneratorDict;
impl AlwaysAutofixableViolation for UnnecessaryGeneratorDict { impl AlwaysFixableViolation for UnnecessaryGeneratorDict {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Unnecessary generator (rewrite as a `dict` comprehension)") format!("Unnecessary generator (rewrite as a `dict` comprehension)")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Rewrite as a `dict` comprehension".to_string() "Rewrite as a `dict` comprehension".to_string()
} }
} }

View file

@ -1,6 +1,6 @@
use ruff_python_ast::{Expr, Keyword}; use ruff_python_ast::{Expr, Keyword};
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
@ -31,13 +31,13 @@ use super::helpers;
#[violation] #[violation]
pub struct UnnecessaryGeneratorList; pub struct UnnecessaryGeneratorList;
impl AlwaysAutofixableViolation for UnnecessaryGeneratorList { impl AlwaysFixableViolation for UnnecessaryGeneratorList {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Unnecessary generator (rewrite as a `list` comprehension)") format!("Unnecessary generator (rewrite as a `list` comprehension)")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Rewrite as a `list` comprehension".to_string() "Rewrite as a `list` comprehension".to_string()
} }
} }

View file

@ -1,6 +1,6 @@
use ruff_python_ast::{Expr, Keyword}; use ruff_python_ast::{Expr, Keyword};
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
@ -31,13 +31,13 @@ use super::helpers;
#[violation] #[violation]
pub struct UnnecessaryGeneratorSet; pub struct UnnecessaryGeneratorSet;
impl AlwaysAutofixableViolation for UnnecessaryGeneratorSet { impl AlwaysFixableViolation for UnnecessaryGeneratorSet {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Unnecessary generator (rewrite as a `set` comprehension)") format!("Unnecessary generator (rewrite as a `set` comprehension)")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Rewrite as a `set` comprehension".to_string() "Rewrite as a `set` comprehension".to_string()
} }
} }

View file

@ -1,6 +1,6 @@
use ruff_python_ast::Expr; use ruff_python_ast::Expr;
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
@ -28,13 +28,13 @@ use super::helpers;
#[violation] #[violation]
pub struct UnnecessaryListCall; pub struct UnnecessaryListCall;
impl AlwaysAutofixableViolation for UnnecessaryListCall { impl AlwaysFixableViolation for UnnecessaryListCall {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Unnecessary `list` call (remove the outer call to `list()`)") format!("Unnecessary `list` call (remove the outer call to `list()`)")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Remove outer `list` call".to_string() "Remove outer `list` call".to_string()
} }
} }

View file

@ -1,4 +1,4 @@
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::{self as ast, Expr, Keyword}; use ruff_python_ast::{self as ast, Expr, Keyword};
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
@ -28,13 +28,13 @@ use super::helpers;
#[violation] #[violation]
pub struct UnnecessaryListComprehensionDict; pub struct UnnecessaryListComprehensionDict;
impl AlwaysAutofixableViolation for UnnecessaryListComprehensionDict { impl AlwaysFixableViolation for UnnecessaryListComprehensionDict {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Unnecessary `list` comprehension (rewrite as a `dict` comprehension)") format!("Unnecessary `list` comprehension (rewrite as a `dict` comprehension)")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Rewrite as a `dict` comprehension".to_string() "Rewrite as a `dict` comprehension".to_string()
} }
} }

View file

@ -1,6 +1,6 @@
use ruff_python_ast::{Expr, Keyword}; use ruff_python_ast::{Expr, Keyword};
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
@ -29,13 +29,13 @@ use super::helpers;
#[violation] #[violation]
pub struct UnnecessaryListComprehensionSet; pub struct UnnecessaryListComprehensionSet;
impl AlwaysAutofixableViolation for UnnecessaryListComprehensionSet { impl AlwaysFixableViolation for UnnecessaryListComprehensionSet {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Unnecessary `list` comprehension (rewrite as a `set` comprehension)") format!("Unnecessary `list` comprehension (rewrite as a `set` comprehension)")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Rewrite as a `set` comprehension".to_string() "Rewrite as a `set` comprehension".to_string()
} }
} }

View file

@ -1,4 +1,4 @@
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::{self as ast, Expr, Keyword}; use ruff_python_ast::{self as ast, Expr, Keyword};
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
@ -34,14 +34,14 @@ pub struct UnnecessaryLiteralDict {
obj_type: String, obj_type: String,
} }
impl AlwaysAutofixableViolation for UnnecessaryLiteralDict { impl AlwaysFixableViolation for UnnecessaryLiteralDict {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
let UnnecessaryLiteralDict { obj_type } = self; let UnnecessaryLiteralDict { obj_type } = self;
format!("Unnecessary `{obj_type}` literal (rewrite as a `dict` literal)") format!("Unnecessary `{obj_type}` literal (rewrite as a `dict` literal)")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Rewrite as a `dict` literal".to_string() "Rewrite as a `dict` literal".to_string()
} }
} }

View file

@ -1,6 +1,6 @@
use ruff_python_ast::{Expr, Keyword}; use ruff_python_ast::{Expr, Keyword};
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
@ -36,14 +36,14 @@ pub struct UnnecessaryLiteralSet {
obj_type: String, obj_type: String,
} }
impl AlwaysAutofixableViolation for UnnecessaryLiteralSet { impl AlwaysFixableViolation for UnnecessaryLiteralSet {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
let UnnecessaryLiteralSet { obj_type } = self; let UnnecessaryLiteralSet { obj_type } = self;
format!("Unnecessary `{obj_type}` literal (rewrite as a `set` literal)") format!("Unnecessary `{obj_type}` literal (rewrite as a `set` literal)")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Rewrite as a `set` literal".to_string() "Rewrite as a `set` literal".to_string()
} }
} }

View file

@ -2,7 +2,7 @@ use std::fmt;
use ruff_python_ast::{Expr, Keyword}; use ruff_python_ast::{Expr, Keyword};
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
@ -51,14 +51,14 @@ pub struct UnnecessaryLiteralWithinDictCall {
kind: DictKind, kind: DictKind,
} }
impl AlwaysAutofixableViolation for UnnecessaryLiteralWithinDictCall { impl AlwaysFixableViolation for UnnecessaryLiteralWithinDictCall {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
let UnnecessaryLiteralWithinDictCall { kind } = self; let UnnecessaryLiteralWithinDictCall { kind } = self;
format!("Unnecessary `dict` {kind} passed to `dict()` (remove the outer call to `dict()`)") format!("Unnecessary `dict` {kind} passed to `dict()` (remove the outer call to `dict()`)")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Remove outer `dict` call".to_string() "Remove outer `dict` call".to_string()
} }
} }

View file

@ -1,4 +1,4 @@
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::{Expr, Keyword}; use ruff_python_ast::{Expr, Keyword};
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
@ -37,7 +37,7 @@ pub struct UnnecessaryLiteralWithinListCall {
literal: String, literal: String,
} }
impl AlwaysAutofixableViolation for UnnecessaryLiteralWithinListCall { impl AlwaysFixableViolation for UnnecessaryLiteralWithinListCall {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
let UnnecessaryLiteralWithinListCall { literal } = self; let UnnecessaryLiteralWithinListCall { literal } = self;
@ -53,7 +53,7 @@ impl AlwaysAutofixableViolation for UnnecessaryLiteralWithinListCall {
} }
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
let UnnecessaryLiteralWithinListCall { literal } = self; let UnnecessaryLiteralWithinListCall { literal } = self;
{ {
if literal == "list" { if literal == "list" {

View file

@ -1,6 +1,6 @@
use ruff_python_ast::{Expr, Keyword}; use ruff_python_ast::{Expr, Keyword};
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
@ -38,7 +38,7 @@ pub struct UnnecessaryLiteralWithinTupleCall {
literal: String, literal: String,
} }
impl AlwaysAutofixableViolation for UnnecessaryLiteralWithinTupleCall { impl AlwaysFixableViolation for UnnecessaryLiteralWithinTupleCall {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
let UnnecessaryLiteralWithinTupleCall { literal } = self; let UnnecessaryLiteralWithinTupleCall { literal } = self;
@ -55,7 +55,7 @@ impl AlwaysAutofixableViolation for UnnecessaryLiteralWithinTupleCall {
} }
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
let UnnecessaryLiteralWithinTupleCall { literal } = self; let UnnecessaryLiteralWithinTupleCall { literal } = self;
{ {
if literal == "list" { if literal == "list" {

View file

@ -1,7 +1,7 @@
use std::fmt; use std::fmt;
use ruff_diagnostics::{AutofixKind, Violation};
use ruff_diagnostics::{Diagnostic, Fix}; use ruff_diagnostics::{Diagnostic, Fix};
use ruff_diagnostics::{FixKind, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::visitor; use ruff_python_ast::visitor;
use ruff_python_ast::visitor::Visitor; use ruff_python_ast::visitor::Visitor;
@ -47,7 +47,7 @@ pub struct UnnecessaryMap {
} }
impl Violation for UnnecessaryMap { impl Violation for UnnecessaryMap {
const AUTOFIX: AutofixKind = AutofixKind::Sometimes; const FIX_KIND: FixKind = FixKind::Sometimes;
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
@ -55,7 +55,7 @@ impl Violation for UnnecessaryMap {
format!("Unnecessary `map` usage (rewrite using a {object_type})") format!("Unnecessary `map` usage (rewrite using a {object_type})")
} }
fn autofix_title(&self) -> Option<String> { fn fix_title(&self) -> Option<String> {
let UnnecessaryMap { object_type } = self; let UnnecessaryMap { object_type } = self;
Some(format!("Replace `map` with a {object_type}")) Some(format!("Replace `map` with a {object_type}"))
} }

View file

@ -1,7 +1,7 @@
use ruff_python_ast::{self as ast, Arguments, Constant, Expr, ExprContext, Stmt}; use ruff_python_ast::{self as ast, Arguments, Constant, Expr, ExprContext, Stmt};
use ruff_text_size::{Ranged, TextRange}; use ruff_text_size::{Ranged, TextRange};
use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{Diagnostic, Edit, Fix, FixKind, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::whitespace; use ruff_python_ast::whitespace;
use ruff_python_codegen::{Generator, Stylist}; use ruff_python_codegen::{Generator, Stylist};
@ -50,14 +50,14 @@ use crate::registry::{AsRule, Rule};
pub struct RawStringInException; pub struct RawStringInException;
impl Violation for RawStringInException { impl Violation for RawStringInException {
const AUTOFIX: AutofixKind = AutofixKind::Sometimes; const FIX_KIND: FixKind = FixKind::Sometimes;
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Exception must not use a string literal, assign to variable first") format!("Exception must not use a string literal, assign to variable first")
} }
fn autofix_title(&self) -> Option<String> { fn fix_title(&self) -> Option<String> {
Some("Assign to variable; remove string literal".to_string()) Some("Assign to variable; remove string literal".to_string())
} }
} }
@ -104,14 +104,14 @@ impl Violation for RawStringInException {
pub struct FStringInException; pub struct FStringInException;
impl Violation for FStringInException { impl Violation for FStringInException {
const AUTOFIX: AutofixKind = AutofixKind::Sometimes; const FIX_KIND: FixKind = FixKind::Sometimes;
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Exception must not use an f-string literal, assign to variable first") format!("Exception must not use an f-string literal, assign to variable first")
} }
fn autofix_title(&self) -> Option<String> { fn fix_title(&self) -> Option<String> {
Some("Assign to variable; remove f-string literal".to_string()) Some("Assign to variable; remove f-string literal".to_string())
} }
} }
@ -160,14 +160,14 @@ impl Violation for FStringInException {
pub struct DotFormatInException; pub struct DotFormatInException;
impl Violation for DotFormatInException { impl Violation for DotFormatInException {
const AUTOFIX: AutofixKind = AutofixKind::Sometimes; const FIX_KIND: FixKind = FixKind::Sometimes;
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Exception must not use a `.format()` string directly, assign to variable first") format!("Exception must not use a `.format()` string directly, assign to variable first")
} }
fn autofix_title(&self) -> Option<String> { fn fix_title(&self) -> Option<String> {
Some("Assign to variable; remove `.format()` string".to_string()) Some("Assign to variable; remove `.format()` string".to_string())
} }
} }

View file

@ -1,6 +1,6 @@
use ruff_text_size::{TextRange, TextSize}; use ruff_text_size::{TextRange, TextSize};
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_trivia::is_python_whitespace; use ruff_python_trivia::is_python_whitespace;
use ruff_source_file::Locator; use ruff_source_file::Locator;
@ -35,13 +35,13 @@ use crate::settings::LinterSettings;
#[violation] #[violation]
pub struct ShebangLeadingWhitespace; pub struct ShebangLeadingWhitespace;
impl AlwaysAutofixableViolation for ShebangLeadingWhitespace { impl AlwaysFixableViolation for ShebangLeadingWhitespace {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Avoid whitespace before shebang") format!("Avoid whitespace before shebang")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
format!("Remove whitespace before shebang") format!("Remove whitespace before shebang")
} }
} }

View file

@ -2,7 +2,7 @@ use itertools::Itertools;
use ruff_python_parser::lexer::LexResult; use ruff_python_parser::lexer::LexResult;
use ruff_text_size::{Ranged, TextRange}; use ruff_text_size::{Ranged, TextRange};
use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{Diagnostic, Edit, Fix, FixKind, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::str::{leading_quote, trailing_quote}; use ruff_python_ast::str::{leading_quote, trailing_quote};
use ruff_source_file::Locator; use ruff_source_file::Locator;
@ -34,14 +34,14 @@ use crate::rules::flake8_implicit_str_concat::settings::Settings;
pub struct SingleLineImplicitStringConcatenation; pub struct SingleLineImplicitStringConcatenation;
impl Violation for SingleLineImplicitStringConcatenation { impl Violation for SingleLineImplicitStringConcatenation {
const AUTOFIX: AutofixKind = AutofixKind::Sometimes; const FIX_KIND: FixKind = FixKind::Sometimes;
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Implicitly concatenated string literals on one line") format!("Implicitly concatenated string literals on one line")
} }
fn autofix_title(&self) -> Option<String> { fn fix_title(&self) -> Option<String> {
Some("Combine string literals".to_string()) Some("Combine string literals".to_string())
} }
} }

View file

@ -1,6 +1,6 @@
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use ruff_diagnostics::{AutofixKind, Diagnostic, Fix, Violation}; use ruff_diagnostics::{Diagnostic, Fix, FixKind, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_semantic::{Binding, Imported}; use ruff_python_semantic::{Binding, Imported};
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
@ -37,7 +37,7 @@ pub struct UnconventionalImportAlias {
} }
impl Violation for UnconventionalImportAlias { impl Violation for UnconventionalImportAlias {
const AUTOFIX: AutofixKind = AutofixKind::Sometimes; const FIX_KIND: FixKind = FixKind::Sometimes;
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
@ -45,7 +45,7 @@ impl Violation for UnconventionalImportAlias {
format!("`{name}` should be imported as `{asname}`") format!("`{name}` should be imported as `{asname}`")
} }
fn autofix_title(&self) -> Option<String> { fn fix_title(&self) -> Option<String> {
let UnconventionalImportAlias { name, asname } = self; let UnconventionalImportAlias { name, asname } = self;
Some(format!("Alias `{name}` to `{asname}`")) Some(format!("Alias `{name}` to `{asname}`"))
} }

View file

@ -1,4 +1,4 @@
use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{Diagnostic, Edit, Fix, FixKind, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast as ast; use ruff_python_ast as ast;
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
@ -41,14 +41,14 @@ use crate::registry::AsRule;
pub struct DirectLoggerInstantiation; pub struct DirectLoggerInstantiation;
impl Violation for DirectLoggerInstantiation { impl Violation for DirectLoggerInstantiation {
const AUTOFIX: AutofixKind = AutofixKind::Sometimes; const FIX_KIND: FixKind = FixKind::Sometimes;
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Use `logging.getLogger()` to instantiate loggers") format!("Use `logging.getLogger()` to instantiate loggers")
} }
fn autofix_title(&self) -> Option<String> { fn fix_title(&self) -> Option<String> {
Some(format!("Replace with `logging.getLogger()`")) Some(format!("Replace with `logging.getLogger()`"))
} }
} }

View file

@ -1,4 +1,4 @@
use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{Diagnostic, Edit, Fix, FixKind, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::{self as ast, Expr}; use ruff_python_ast::{self as ast, Expr};
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
@ -44,14 +44,14 @@ use crate::registry::AsRule;
pub struct InvalidGetLoggerArgument; pub struct InvalidGetLoggerArgument;
impl Violation for InvalidGetLoggerArgument { impl Violation for InvalidGetLoggerArgument {
const AUTOFIX: AutofixKind = AutofixKind::Sometimes; const FIX_KIND: FixKind = FixKind::Sometimes;
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Use `__name__` with `logging.getLogger()`") format!("Use `__name__` with `logging.getLogger()`")
} }
fn autofix_title(&self) -> Option<String> { fn fix_title(&self) -> Option<String> {
Some(format!("Replace with `__name__`")) Some(format!("Replace with `__name__`"))
} }
} }

View file

@ -1,6 +1,6 @@
use ruff_python_ast::Expr; use ruff_python_ast::Expr;
use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{Diagnostic, Edit, Fix, FixKind, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
@ -36,13 +36,13 @@ use crate::registry::AsRule;
pub struct UndocumentedWarn; pub struct UndocumentedWarn;
impl Violation for UndocumentedWarn { impl Violation for UndocumentedWarn {
const AUTOFIX: AutofixKind = AutofixKind::Sometimes; const FIX_KIND: FixKind = FixKind::Sometimes;
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Use of undocumented `logging.WARN` constant") format!("Use of undocumented `logging.WARN` constant")
} }
fn autofix_title(&self) -> Option<String> { fn fix_title(&self) -> Option<String> {
Some(format!("Replace `logging.WARN` with `logging.WARNING`")) Some(format!("Replace `logging.WARN` with `logging.WARNING`"))
} }
} }

View file

@ -1,4 +1,4 @@
use ruff_diagnostics::{AlwaysAutofixableViolation, Violation}; use ruff_diagnostics::{AlwaysFixableViolation, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
/// ## What it does /// ## What it does
@ -376,13 +376,13 @@ impl Violation for LoggingFString {
#[violation] #[violation]
pub struct LoggingWarn; pub struct LoggingWarn;
impl AlwaysAutofixableViolation for LoggingWarn { impl AlwaysFixableViolation for LoggingWarn {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Logging statement uses `warn` instead of `warning`") format!("Logging statement uses `warn` instead of `warning`")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Convert to `warn`".to_string() "Convert to `warn`".to_string()
} }
} }

View file

@ -1,13 +1,13 @@
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
use ruff_diagnostics::Diagnostic; use ruff_diagnostics::Diagnostic;
use ruff_diagnostics::{AlwaysAutofixableViolation, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::{self as ast, Expr, Stmt}; use ruff_python_ast::{self as ast, Expr, Stmt};
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
use crate::autofix;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::fix;
use crate::registry::AsRule; use crate::registry::AsRule;
/// ## What it does /// ## What it does
@ -36,14 +36,14 @@ pub struct DuplicateClassFieldDefinition {
name: String, name: String,
} }
impl AlwaysAutofixableViolation for DuplicateClassFieldDefinition { impl AlwaysFixableViolation for DuplicateClassFieldDefinition {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
let DuplicateClassFieldDefinition { name } = self; let DuplicateClassFieldDefinition { name } = self;
format!("Class field `{name}` is defined multiple times") format!("Class field `{name}` is defined multiple times")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
let DuplicateClassFieldDefinition { name } = self; let DuplicateClassFieldDefinition { name } = self;
format!("Remove duplicate field definition for `{name}`") format!("Remove duplicate field definition for `{name}`")
} }
@ -80,12 +80,8 @@ pub(crate) fn duplicate_class_field_definition(checker: &mut Checker, body: &[St
stmt.range(), stmt.range(),
); );
if checker.patch(diagnostic.kind.rule()) { if checker.patch(diagnostic.kind.rule()) {
let edit = autofix::edits::delete_stmt( let edit =
stmt, fix::edits::delete_stmt(stmt, Some(stmt), checker.locator(), checker.indexer());
Some(stmt),
checker.locator(),
checker.indexer(),
);
diagnostic.set_fix(Fix::suggested(edit).isolate(Checker::isolation(Some( diagnostic.set_fix(Fix::suggested(edit).isolate(Checker::isolation(Some(
checker.semantic().current_statement_id(), checker.semantic().current_statement_id(),
)))); ))));

View file

@ -7,7 +7,7 @@ use ruff_text_size::{Ranged, TextRange};
use ruff_python_ast::{self as ast, Arguments, BoolOp, Expr, ExprContext, Identifier}; use ruff_python_ast::{self as ast, Arguments, BoolOp, Expr, ExprContext, Identifier};
use ruff_diagnostics::AlwaysAutofixableViolation; use ruff_diagnostics::AlwaysFixableViolation;
use ruff_diagnostics::{Diagnostic, Edit, Fix}; use ruff_diagnostics::{Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
@ -45,14 +45,14 @@ pub struct MultipleStartsEndsWith {
attr: String, attr: String,
} }
impl AlwaysAutofixableViolation for MultipleStartsEndsWith { impl AlwaysFixableViolation for MultipleStartsEndsWith {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
let MultipleStartsEndsWith { attr } = self; let MultipleStartsEndsWith { attr } = self;
format!("Call `{attr}` once with a `tuple`") format!("Call `{attr}` once with a `tuple`")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
let MultipleStartsEndsWith { attr } = self; let MultipleStartsEndsWith { attr } = self;
format!("Merge into a single `{attr}` call") format!("Merge into a single `{attr}` call")
} }

View file

@ -1,14 +1,14 @@
use ruff_python_ast::Stmt; use ruff_python_ast::Stmt;
use ruff_diagnostics::AlwaysAutofixableViolation; use ruff_diagnostics::AlwaysFixableViolation;
use ruff_diagnostics::{Diagnostic, Edit, Fix}; use ruff_diagnostics::{Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::is_docstring_stmt; use ruff_python_ast::helpers::is_docstring_stmt;
use ruff_python_ast::whitespace::trailing_comment_start_offset; use ruff_python_ast::whitespace::trailing_comment_start_offset;
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
use crate::autofix;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::fix;
use crate::registry::AsRule; use crate::registry::AsRule;
/// ## What it does /// ## What it does
@ -38,13 +38,13 @@ use crate::registry::AsRule;
#[violation] #[violation]
pub struct UnnecessaryPass; pub struct UnnecessaryPass;
impl AlwaysAutofixableViolation for UnnecessaryPass { impl AlwaysFixableViolation for UnnecessaryPass {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Unnecessary `pass` statement") format!("Unnecessary `pass` statement")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Remove unnecessary `pass`".to_string() "Remove unnecessary `pass`".to_string()
} }
} }
@ -70,7 +70,7 @@ pub(crate) fn no_unnecessary_pass(checker: &mut Checker, body: &[Stmt]) {
let edit = if let Some(index) = trailing_comment_start_offset(second, checker.locator()) { let edit = if let Some(index) = trailing_comment_start_offset(second, checker.locator()) {
Edit::range_deletion(second.range().add_end(index)) Edit::range_deletion(second.range().add_end(index))
} else { } else {
autofix::edits::delete_stmt(second, None, checker.locator(), checker.indexer()) fix::edits::delete_stmt(second, None, checker.locator(), checker.indexer())
}; };
diagnostic.set_fix(Fix::automatic(edit)); diagnostic.set_fix(Fix::automatic(edit));
} }

View file

@ -1,7 +1,7 @@
use ruff_python_ast::{self as ast, Expr, ExprLambda}; use ruff_python_ast::{self as ast, Expr, ExprLambda};
use ruff_diagnostics::{AutofixKind, Violation};
use ruff_diagnostics::{Diagnostic, Edit, Fix}; use ruff_diagnostics::{Diagnostic, Edit, Fix};
use ruff_diagnostics::{FixKind, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
@ -40,14 +40,14 @@ use crate::registry::AsRule;
pub struct ReimplementedListBuiltin; pub struct ReimplementedListBuiltin;
impl Violation for ReimplementedListBuiltin { impl Violation for ReimplementedListBuiltin {
const AUTOFIX: AutofixKind = AutofixKind::Sometimes; const FIX_KIND: FixKind = FixKind::Sometimes;
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Prefer `list` over useless lambda") format!("Prefer `list` over useless lambda")
} }
fn autofix_title(&self) -> Option<String> { fn fix_title(&self) -> Option<String> {
Some("Replace with `list`".to_string()) Some("Replace with `list`".to_string())
} }
} }

View file

@ -1,11 +1,11 @@
use ruff_diagnostics::Diagnostic; use ruff_diagnostics::Diagnostic;
use ruff_diagnostics::{AlwaysAutofixableViolation, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::{self as ast, Constant, Expr}; use ruff_python_ast::{self as ast, Constant, Expr};
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
use crate::autofix::edits::{remove_argument, Parentheses};
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::fix::edits::{remove_argument, Parentheses};
use crate::registry::AsRule; use crate::registry::AsRule;
/// ## What it does /// ## What it does
@ -31,13 +31,13 @@ use crate::registry::AsRule;
#[violation] #[violation]
pub struct UnnecessaryRangeStart; pub struct UnnecessaryRangeStart;
impl AlwaysAutofixableViolation for UnnecessaryRangeStart { impl AlwaysFixableViolation for UnnecessaryRangeStart {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Unnecessary `start` argument in `range`") format!("Unnecessary `start` argument in `range`")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
format!("Remove `start` argument") format!("Remove `start` argument")
} }
} }

View file

@ -1,6 +1,6 @@
use ruff_python_ast::Parameters; use ruff_python_ast::Parameters;
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
@ -41,14 +41,14 @@ pub struct AnyEqNeAnnotation {
method_name: String, method_name: String,
} }
impl AlwaysAutofixableViolation for AnyEqNeAnnotation { impl AlwaysFixableViolation for AnyEqNeAnnotation {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
let AnyEqNeAnnotation { method_name } = self; let AnyEqNeAnnotation { method_name } = self;
format!("Prefer `object` to `Any` for the second parameter to `{method_name}`") format!("Prefer `object` to `Any` for the second parameter to `{method_name}`")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
format!("Replace with `object`") format!("Replace with `object`")
} }
} }

View file

@ -43,7 +43,7 @@ impl Violation for CollectionsNamedTuple {
format!("Use `typing.NamedTuple` instead of `collections.namedtuple`") format!("Use `typing.NamedTuple` instead of `collections.namedtuple`")
} }
fn autofix_title(&self) -> Option<String> { fn fix_title(&self) -> Option<String> {
Some(format!("Replace with `typing.NamedTuple`")) Some(format!("Replace with `typing.NamedTuple`"))
} }
} }

View file

@ -5,7 +5,7 @@ use std::collections::HashSet;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::AsRule; use crate::registry::AsRule;
use crate::rules::flake8_pyi::helpers::traverse_union; use crate::rules::flake8_pyi::helpers::traverse_union;
use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{Diagnostic, Edit, Fix, FixKind, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::comparable::ComparableExpr; use ruff_python_ast::comparable::ComparableExpr;
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
@ -34,14 +34,14 @@ pub struct DuplicateUnionMember {
} }
impl Violation for DuplicateUnionMember { impl Violation for DuplicateUnionMember {
const AUTOFIX: AutofixKind = AutofixKind::Sometimes; const FIX_KIND: FixKind = FixKind::Sometimes;
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Duplicate union member `{}`", self.duplicate_name) format!("Duplicate union member `{}`", self.duplicate_name)
} }
fn autofix_title(&self) -> Option<String> { fn fix_title(&self) -> Option<String> {
Some(format!( Some(format!(
"Remove duplicate union member `{}`", "Remove duplicate union member `{}`",
self.duplicate_name self.duplicate_name

View file

@ -1,10 +1,10 @@
use ruff_diagnostics::{AutofixKind, Diagnostic, Fix, Violation}; use ruff_diagnostics::{Diagnostic, Fix, FixKind, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::{Constant, Expr, ExprConstant, Stmt, StmtExpr}; use ruff_python_ast::{Constant, Expr, ExprConstant, Stmt, StmtExpr};
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
use crate::autofix;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::fix;
use crate::registry::AsRule; use crate::registry::AsRule;
/// ## What it does /// ## What it does
@ -31,14 +31,14 @@ use crate::registry::AsRule;
pub struct EllipsisInNonEmptyClassBody; pub struct EllipsisInNonEmptyClassBody;
impl Violation for EllipsisInNonEmptyClassBody { impl Violation for EllipsisInNonEmptyClassBody {
const AUTOFIX: AutofixKind = AutofixKind::Sometimes; const FIX_KIND: FixKind = FixKind::Sometimes;
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Non-empty class body must not contain `...`") format!("Non-empty class body must not contain `...`")
} }
fn autofix_title(&self) -> Option<String> { fn fix_title(&self) -> Option<String> {
Some("Remove unnecessary `...`".to_string()) Some("Remove unnecessary `...`".to_string())
} }
} }
@ -64,12 +64,8 @@ pub(crate) fn ellipsis_in_non_empty_class_body(checker: &mut Checker, body: &[St
) { ) {
let mut diagnostic = Diagnostic::new(EllipsisInNonEmptyClassBody, stmt.range()); let mut diagnostic = Diagnostic::new(EllipsisInNonEmptyClassBody, stmt.range());
if checker.patch(diagnostic.kind.rule()) { if checker.patch(diagnostic.kind.rule()) {
let edit = autofix::edits::delete_stmt( let edit =
stmt, fix::edits::delete_stmt(stmt, Some(stmt), checker.locator(), checker.indexer());
Some(stmt),
checker.locator(),
checker.indexer(),
);
diagnostic.set_fix(Fix::automatic(edit).isolate(Checker::isolation(Some( diagnostic.set_fix(Fix::automatic(edit).isolate(Checker::isolation(Some(
checker.semantic().current_statement_id(), checker.semantic().current_statement_id(),
)))); ))));

View file

@ -6,7 +6,7 @@ use ruff_python_ast::{
}; };
use smallvec::SmallVec; use smallvec::SmallVec;
use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{Diagnostic, Edit, Fix, FixKind, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::is_const_none; use ruff_python_ast::helpers::is_const_none;
use ruff_python_semantic::SemanticModel; use ruff_python_semantic::SemanticModel;
@ -49,7 +49,7 @@ pub struct BadExitAnnotation {
} }
impl Violation for BadExitAnnotation { impl Violation for BadExitAnnotation {
const AUTOFIX: AutofixKind = AutofixKind::Sometimes; const FIX_KIND: FixKind = FixKind::Sometimes;
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
@ -65,7 +65,7 @@ impl Violation for BadExitAnnotation {
} }
} }
fn autofix_title(&self) -> Option<String> { fn fix_title(&self) -> Option<String> {
if matches!(self.error_kind, ErrorKind::StarArgsNotAnnotated) { if matches!(self.error_kind, ErrorKind::StarArgsNotAnnotated) {
Some("Annotate star-args with `object`".to_string()) Some("Annotate star-args with `object`".to_string())
} else { } else {

View file

@ -1,4 +1,4 @@
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::is_docstring_stmt; use ruff_python_ast::helpers::is_docstring_stmt;
use ruff_python_ast::{self as ast, Expr, Stmt}; use ruff_python_ast::{self as ast, Expr, Stmt};
@ -31,13 +31,13 @@ use crate::registry::Rule;
#[violation] #[violation]
pub struct NonEmptyStubBody; pub struct NonEmptyStubBody;
impl AlwaysAutofixableViolation for NonEmptyStubBody { impl AlwaysFixableViolation for NonEmptyStubBody {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Function body must contain only `...`") format!("Function body must contain only `...`")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
format!("Replace function body with `...`") format!("Replace function body with `...`")
} }
} }

View file

@ -104,7 +104,7 @@ impl Violation for NonSelfReturnType {
} }
} }
fn autofix_title(&self) -> Option<String> { fn fix_title(&self) -> Option<String> {
Some("Consider using `typing_extensions.Self` as return type".to_string()) Some("Consider using `typing_extensions.Self` as return type".to_string())
} }
} }

View file

@ -1,7 +1,7 @@
use ruff_python_ast::Expr; use ruff_python_ast::Expr;
use ruff_text_size::{Ranged, TextSize}; use ruff_text_size::{Ranged, TextSize};
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
@ -30,13 +30,13 @@ pub struct NumericLiteralTooLong;
/// ```python /// ```python
/// def foo(arg: int = ...) -> None: ... /// def foo(arg: int = ...) -> None: ...
/// ``` /// ```
impl AlwaysAutofixableViolation for NumericLiteralTooLong { impl AlwaysFixableViolation for NumericLiteralTooLong {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Numeric literals with a string representation longer than ten characters are not permitted") format!("Numeric literals with a string representation longer than ten characters are not permitted")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Replace with `...`".to_string() "Replace with `...`".to_string()
} }
} }

View file

@ -1,22 +1,22 @@
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::{self as ast}; use ruff_python_ast::{self as ast};
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
use crate::autofix;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::fix;
use crate::registry::AsRule; use crate::registry::AsRule;
#[violation] #[violation]
pub struct PassInClassBody; pub struct PassInClassBody;
impl AlwaysAutofixableViolation for PassInClassBody { impl AlwaysFixableViolation for PassInClassBody {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Class body must not contain `pass`") format!("Class body must not contain `pass`")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
format!("Remove unnecessary `pass`") format!("Remove unnecessary `pass`")
} }
} }
@ -36,7 +36,7 @@ pub(crate) fn pass_in_class_body(checker: &mut Checker, class_def: &ast::StmtCla
let mut diagnostic = Diagnostic::new(PassInClassBody, stmt.range()); let mut diagnostic = Diagnostic::new(PassInClassBody, stmt.range());
if checker.patch(diagnostic.kind.rule()) { if checker.patch(diagnostic.kind.rule()) {
let edit = let edit =
autofix::edits::delete_stmt(stmt, Some(stmt), checker.locator(), checker.indexer()); fix::edits::delete_stmt(stmt, Some(stmt), checker.locator(), checker.indexer());
diagnostic.set_fix(Fix::automatic(edit).isolate(Checker::isolation(Some( diagnostic.set_fix(Fix::automatic(edit).isolate(Checker::isolation(Some(
checker.semantic().current_statement_id(), checker.semantic().current_statement_id(),
)))); ))));

View file

@ -1,4 +1,4 @@
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::Stmt; use ruff_python_ast::Stmt;
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
@ -29,13 +29,13 @@ use crate::registry::Rule;
#[violation] #[violation]
pub struct PassStatementStubBody; pub struct PassStatementStubBody;
impl AlwaysAutofixableViolation for PassStatementStubBody { impl AlwaysFixableViolation for PassStatementStubBody {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Empty body should contain `...`, not `pass`") format!("Empty body should contain `...`, not `pass`")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
format!("Replace `pass` with `...`") format!("Replace `pass` with `...`")
} }
} }

View file

@ -1,6 +1,6 @@
use ruff_text_size::TextRange; use ruff_text_size::TextRange;
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
@ -9,13 +9,13 @@ use crate::registry::Rule;
#[violation] #[violation]
pub struct QuotedAnnotationInStub; pub struct QuotedAnnotationInStub;
impl AlwaysAutofixableViolation for QuotedAnnotationInStub { impl AlwaysFixableViolation for QuotedAnnotationInStub {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Quoted annotations should not be included in stubs") format!("Quoted annotations should not be included in stubs")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Remove quotes".to_string() "Remove quotes".to_string()
} }
} }

View file

@ -8,7 +8,7 @@ use ruff_python_ast::{self as ast, Expr};
use ruff_python_semantic::SemanticModel; use ruff_python_semantic::SemanticModel;
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
use crate::autofix::snippet::SourceCodeSnippet; use crate::fix::snippet::SourceCodeSnippet;
use crate::{checkers::ast::Checker, rules::flake8_pyi::helpers::traverse_union}; use crate::{checkers::ast::Checker, rules::flake8_pyi::helpers::traverse_union};
/// ## What it does /// ## What it does

View file

@ -1,4 +1,4 @@
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::call_path::CallPath; use ruff_python_ast::call_path::CallPath;
use ruff_python_ast::{ use ruff_python_ast::{
@ -18,13 +18,13 @@ use crate::settings::types::PythonVersion;
#[violation] #[violation]
pub struct TypedArgumentDefaultInStub; pub struct TypedArgumentDefaultInStub;
impl AlwaysAutofixableViolation for TypedArgumentDefaultInStub { impl AlwaysFixableViolation for TypedArgumentDefaultInStub {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Only simple default values allowed for typed arguments") format!("Only simple default values allowed for typed arguments")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Replace default value with `...`".to_string() "Replace default value with `...`".to_string()
} }
} }
@ -32,13 +32,13 @@ impl AlwaysAutofixableViolation for TypedArgumentDefaultInStub {
#[violation] #[violation]
pub struct ArgumentDefaultInStub; pub struct ArgumentDefaultInStub;
impl AlwaysAutofixableViolation for ArgumentDefaultInStub { impl AlwaysFixableViolation for ArgumentDefaultInStub {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Only simple default values allowed for arguments") format!("Only simple default values allowed for arguments")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Replace default value with `...`".to_string() "Replace default value with `...`".to_string()
} }
} }
@ -46,13 +46,13 @@ impl AlwaysAutofixableViolation for ArgumentDefaultInStub {
#[violation] #[violation]
pub struct AssignmentDefaultInStub; pub struct AssignmentDefaultInStub;
impl AlwaysAutofixableViolation for AssignmentDefaultInStub { impl AlwaysFixableViolation for AssignmentDefaultInStub {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Only simple default values allowed for assignments") format!("Only simple default values allowed for assignments")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Replace default value with `...`".to_string() "Replace default value with `...`".to_string()
} }
} }
@ -131,7 +131,7 @@ pub struct TypeAliasWithoutAnnotation {
value: String, value: String,
} }
impl AlwaysAutofixableViolation for TypeAliasWithoutAnnotation { impl AlwaysFixableViolation for TypeAliasWithoutAnnotation {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
let TypeAliasWithoutAnnotation { let TypeAliasWithoutAnnotation {
@ -142,7 +142,7 @@ impl AlwaysAutofixableViolation for TypeAliasWithoutAnnotation {
format!("Use `{module}.TypeAlias` for type alias, e.g., `{name}: TypeAlias = {value}`") format!("Use `{module}.TypeAlias` for type alias, e.g., `{name}: TypeAlias = {value}`")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Add `TypeAlias` annotation".to_string() "Add `TypeAlias` annotation".to_string()
} }
} }

View file

@ -1,13 +1,13 @@
use ruff_python_ast as ast; use ruff_python_ast as ast;
use ruff_python_ast::Stmt; use ruff_python_ast::Stmt;
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::identifier::Identifier; use ruff_python_ast::identifier::Identifier;
use ruff_python_semantic::analyze::visibility::is_abstract; use ruff_python_semantic::analyze::visibility::is_abstract;
use crate::autofix::edits::delete_stmt;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::fix::edits::delete_stmt;
use crate::registry::AsRule; use crate::registry::AsRule;
/// ## What it does /// ## What it does
@ -29,14 +29,14 @@ pub struct StrOrReprDefinedInStub {
name: String, name: String,
} }
impl AlwaysAutofixableViolation for StrOrReprDefinedInStub { impl AlwaysFixableViolation for StrOrReprDefinedInStub {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
let StrOrReprDefinedInStub { name } = self; let StrOrReprDefinedInStub { name } = self;
format!("Defining `{name}` in a stub is almost always redundant") format!("Defining `{name}` in a stub is almost always redundant")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
let StrOrReprDefinedInStub { name } = self; let StrOrReprDefinedInStub { name } = self;
format!("Remove definition of `{name}`") format!("Remove definition of `{name}`")
} }

View file

@ -1,6 +1,6 @@
use ruff_python_ast::{self as ast, Constant, Expr}; use ruff_python_ast::{self as ast, Constant, Expr};
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::is_docstring_stmt; use ruff_python_ast::helpers::is_docstring_stmt;
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
@ -30,13 +30,13 @@ pub struct StringOrBytesTooLong;
/// ```python /// ```python
/// def foo(arg: str = ...) -> None: ... /// def foo(arg: str = ...) -> None: ...
/// ``` /// ```
impl AlwaysAutofixableViolation for StringOrBytesTooLong { impl AlwaysFixableViolation for StringOrBytesTooLong {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("String and bytes literals longer than 50 characters are not permitted") format!("String and bytes literals longer than 50 characters are not permitted")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Replace with `...`".to_string() "Replace with `...`".to_string()
} }
} }

View file

@ -1,4 +1,4 @@
use ruff_diagnostics::{AutofixKind, Diagnostic, Fix, Violation}; use ruff_diagnostics::{Diagnostic, Fix, FixKind, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_semantic::Imported; use ruff_python_semantic::Imported;
use ruff_python_semantic::{Binding, BindingKind}; use ruff_python_semantic::{Binding, BindingKind};
@ -33,7 +33,7 @@ use crate::renamer::Renamer;
pub struct UnaliasedCollectionsAbcSetImport; pub struct UnaliasedCollectionsAbcSetImport;
impl Violation for UnaliasedCollectionsAbcSetImport { impl Violation for UnaliasedCollectionsAbcSetImport {
const AUTOFIX: AutofixKind = AutofixKind::Sometimes; const FIX_KIND: FixKind = FixKind::Sometimes;
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
@ -42,7 +42,7 @@ impl Violation for UnaliasedCollectionsAbcSetImport {
) )
} }
fn autofix_title(&self) -> Option<String> { fn fix_title(&self) -> Option<String> {
Some(format!("Alias `Set` to `AbstractSet`")) Some(format!("Alias `Set` to `AbstractSet`"))
} }
} }

View file

@ -7,7 +7,7 @@ use libcst_native::{
SimpleWhitespace, SmallStatement, Statement, TrailingWhitespace, SimpleWhitespace, SmallStatement, Statement, TrailingWhitespace,
}; };
use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{Diagnostic, Edit, Fix, FixKind, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::Truthiness; use ruff_python_ast::helpers::Truthiness;
use ruff_python_ast::parenthesize::parenthesized_range; use ruff_python_ast::parenthesize::parenthesized_range;
@ -20,11 +20,11 @@ use ruff_python_codegen::Stylist;
use ruff_source_file::Locator; use ruff_source_file::Locator;
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
use crate::autofix::codemods::CodegenStylist;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::cst::helpers::negate; use crate::cst::helpers::negate;
use crate::cst::matchers::match_indented_block; use crate::cst::matchers::match_indented_block;
use crate::cst::matchers::match_module; use crate::cst::matchers::match_module;
use crate::fix::codemods::CodegenStylist;
use crate::importer::ImportRequest; use crate::importer::ImportRequest;
use crate::registry::AsRule; use crate::registry::AsRule;
@ -62,14 +62,14 @@ use super::unittest_assert::UnittestAssert;
pub struct PytestCompositeAssertion; pub struct PytestCompositeAssertion;
impl Violation for PytestCompositeAssertion { impl Violation for PytestCompositeAssertion {
const AUTOFIX: AutofixKind = AutofixKind::Sometimes; const FIX_KIND: FixKind = FixKind::Sometimes;
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Assertion should be broken down into multiple parts") format!("Assertion should be broken down into multiple parts")
} }
fn autofix_title(&self) -> Option<String> { fn fix_title(&self) -> Option<String> {
Some("Break down assertion into multiple parts".to_string()) Some("Break down assertion into multiple parts".to_string())
} }
} }
@ -192,7 +192,7 @@ pub struct PytestUnittestAssertion {
} }
impl Violation for PytestUnittestAssertion { impl Violation for PytestUnittestAssertion {
const AUTOFIX: AutofixKind = AutofixKind::Sometimes; const FIX_KIND: FixKind = FixKind::Sometimes;
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
@ -200,7 +200,7 @@ impl Violation for PytestUnittestAssertion {
format!("Use a regular `assert` instead of unittest-style `{assertion}`") format!("Use a regular `assert` instead of unittest-style `{assertion}`")
} }
fn autofix_title(&self) -> Option<String> { fn fix_title(&self) -> Option<String> {
let PytestUnittestAssertion { assertion } = self; let PytestUnittestAssertion { assertion } = self;
Some(format!("Replace `{assertion}(...)` with `assert ...`")) Some(format!("Replace `{assertion}(...)` with `assert ...`"))
} }
@ -354,7 +354,7 @@ pub struct PytestUnittestRaisesAssertion {
} }
impl Violation for PytestUnittestRaisesAssertion { impl Violation for PytestUnittestRaisesAssertion {
const AUTOFIX: AutofixKind = AutofixKind::Sometimes; const FIX_KIND: FixKind = FixKind::Sometimes;
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
@ -362,7 +362,7 @@ impl Violation for PytestUnittestRaisesAssertion {
format!("Use `pytest.raises` instead of unittest-style `{assertion}`") format!("Use `pytest.raises` instead of unittest-style `{assertion}`")
} }
fn autofix_title(&self) -> Option<String> { fn fix_title(&self) -> Option<String> {
let PytestUnittestRaisesAssertion { assertion } = self; let PytestUnittestRaisesAssertion { assertion } = self;
Some(format!("Replace `{assertion}` with `pytest.raises`")) Some(format!("Replace `{assertion}` with `pytest.raises`"))
} }

View file

@ -1,6 +1,6 @@
use std::fmt; use std::fmt;
use ruff_diagnostics::{AlwaysAutofixableViolation, Violation}; use ruff_diagnostics::{AlwaysFixableViolation, Violation};
use ruff_diagnostics::{Diagnostic, Edit, Fix}; use ruff_diagnostics::{Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::call_path::collect_call_path; use ruff_python_ast::call_path::collect_call_path;
@ -14,8 +14,8 @@ use ruff_python_semantic::SemanticModel;
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
use ruff_text_size::{TextLen, TextRange}; use ruff_text_size::{TextLen, TextRange};
use crate::autofix::edits;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::fix::edits;
use crate::registry::{AsRule, Rule}; use crate::registry::{AsRule, Rule};
use super::helpers::{ use super::helpers::{
@ -65,14 +65,14 @@ pub struct PytestFixtureIncorrectParenthesesStyle {
actual: Parentheses, actual: Parentheses,
} }
impl AlwaysAutofixableViolation for PytestFixtureIncorrectParenthesesStyle { impl AlwaysFixableViolation for PytestFixtureIncorrectParenthesesStyle {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
let PytestFixtureIncorrectParenthesesStyle { expected, actual } = self; let PytestFixtureIncorrectParenthesesStyle { expected, actual } = self;
format!("Use `@pytest.fixture{expected}` over `@pytest.fixture{actual}`") format!("Use `@pytest.fixture{expected}` over `@pytest.fixture{actual}`")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
let PytestFixtureIncorrectParenthesesStyle { expected, .. } = self; let PytestFixtureIncorrectParenthesesStyle { expected, .. } = self;
match expected { match expected {
Parentheses::None => "Remove parentheses".to_string(), Parentheses::None => "Remove parentheses".to_string(),
@ -154,13 +154,13 @@ impl Violation for PytestFixturePositionalArgs {
#[violation] #[violation]
pub struct PytestExtraneousScopeFunction; pub struct PytestExtraneousScopeFunction;
impl AlwaysAutofixableViolation for PytestExtraneousScopeFunction { impl AlwaysFixableViolation for PytestExtraneousScopeFunction {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("`scope='function'` is implied in `@pytest.fixture()`") format!("`scope='function'` is implied in `@pytest.fixture()`")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Remove implied `scope` argument".to_string() "Remove implied `scope` argument".to_string()
} }
} }
@ -488,14 +488,14 @@ pub struct PytestUselessYieldFixture {
name: String, name: String,
} }
impl AlwaysAutofixableViolation for PytestUselessYieldFixture { impl AlwaysFixableViolation for PytestUselessYieldFixture {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
let PytestUselessYieldFixture { name } = self; let PytestUselessYieldFixture { name } = self;
format!("No teardown in fixture `{name}`, use `return` instead of `yield`") format!("No teardown in fixture `{name}`, use `return` instead of `yield`")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Replace `yield` with `return`".to_string() "Replace `yield` with `return`".to_string()
} }
} }
@ -543,13 +543,13 @@ impl AlwaysAutofixableViolation for PytestUselessYieldFixture {
#[violation] #[violation]
pub struct PytestErroneousUseFixturesOnFixture; pub struct PytestErroneousUseFixturesOnFixture;
impl AlwaysAutofixableViolation for PytestErroneousUseFixturesOnFixture { impl AlwaysFixableViolation for PytestErroneousUseFixturesOnFixture {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("`pytest.mark.usefixtures` has no effect on fixtures") format!("`pytest.mark.usefixtures` has no effect on fixtures")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Remove `pytest.mark.usefixtures`".to_string() "Remove `pytest.mark.usefixtures`".to_string()
} }
} }
@ -586,13 +586,13 @@ impl AlwaysAutofixableViolation for PytestErroneousUseFixturesOnFixture {
#[violation] #[violation]
pub struct PytestUnnecessaryAsyncioMarkOnFixture; pub struct PytestUnnecessaryAsyncioMarkOnFixture;
impl AlwaysAutofixableViolation for PytestUnnecessaryAsyncioMarkOnFixture { impl AlwaysFixableViolation for PytestUnnecessaryAsyncioMarkOnFixture {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("`pytest.mark.asyncio` is unnecessary for fixtures") format!("`pytest.mark.asyncio` is unnecessary for fixtures")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Remove `pytest.mark.asyncio`".to_string() "Remove `pytest.mark.asyncio`".to_string()
} }
} }

View file

@ -1,6 +1,6 @@
use ruff_python_ast::{self as ast, Arguments, Decorator, Expr}; use ruff_python_ast::{self as ast, Arguments, Decorator, Expr};
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::call_path::CallPath; use ruff_python_ast::call_path::CallPath;
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
@ -54,7 +54,7 @@ pub struct PytestIncorrectMarkParenthesesStyle {
actual_parens: String, actual_parens: String,
} }
impl AlwaysAutofixableViolation for PytestIncorrectMarkParenthesesStyle { impl AlwaysFixableViolation for PytestIncorrectMarkParenthesesStyle {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
let PytestIncorrectMarkParenthesesStyle { let PytestIncorrectMarkParenthesesStyle {
@ -68,7 +68,7 @@ impl AlwaysAutofixableViolation for PytestIncorrectMarkParenthesesStyle {
) )
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Add/remove parentheses".to_string() "Add/remove parentheses".to_string()
} }
} }
@ -103,13 +103,13 @@ impl AlwaysAutofixableViolation for PytestIncorrectMarkParenthesesStyle {
#[violation] #[violation]
pub struct PytestUseFixturesWithoutParameters; pub struct PytestUseFixturesWithoutParameters;
impl AlwaysAutofixableViolation for PytestUseFixturesWithoutParameters { impl AlwaysFixableViolation for PytestUseFixturesWithoutParameters {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Useless `pytest.mark.usefixtures` without parameters") format!("Useless `pytest.mark.usefixtures` without parameters")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Remove `usefixtures` decorator or pass parameters".to_string() "Remove `usefixtures` decorator or pass parameters".to_string()
} }
} }

View file

@ -2,7 +2,7 @@ use std::hash::BuildHasherDefault;
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{Diagnostic, Edit, Fix, FixKind, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::comparable::ComparableExpr; use ruff_python_ast::comparable::ComparableExpr;
use ruff_python_ast::node::AstNode; use ruff_python_ast::node::AstNode;
@ -77,7 +77,7 @@ pub struct PytestParametrizeNamesWrongType {
} }
impl Violation for PytestParametrizeNamesWrongType { impl Violation for PytestParametrizeNamesWrongType {
const AUTOFIX: AutofixKind = AutofixKind::Sometimes; const FIX_KIND: FixKind = FixKind::Sometimes;
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
@ -85,7 +85,7 @@ impl Violation for PytestParametrizeNamesWrongType {
format!("Wrong name(s) type in `@pytest.mark.parametrize`, expected `{expected}`") format!("Wrong name(s) type in `@pytest.mark.parametrize`, expected `{expected}`")
} }
fn autofix_title(&self) -> Option<String> { fn fix_title(&self) -> Option<String> {
let PytestParametrizeNamesWrongType { expected } = self; let PytestParametrizeNamesWrongType { expected } = self;
Some(format!("Use a `{expected}` for parameter names")) Some(format!("Use a `{expected}` for parameter names"))
} }
@ -234,7 +234,7 @@ pub struct PytestDuplicateParametrizeTestCases {
} }
impl Violation for PytestDuplicateParametrizeTestCases { impl Violation for PytestDuplicateParametrizeTestCases {
const AUTOFIX: AutofixKind = AutofixKind::Sometimes; const FIX_KIND: FixKind = FixKind::Sometimes;
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
@ -242,7 +242,7 @@ impl Violation for PytestDuplicateParametrizeTestCases {
format!("Duplicate of test case at index {index} in `@pytest_mark.parametrize`") format!("Duplicate of test case at index {index} in `@pytest_mark.parametrize`")
} }
fn autofix_title(&self) -> Option<String> { fn fix_title(&self) -> Option<String> {
Some("Remove duplicate test case".to_string()) Some("Remove duplicate test case".to_string())
} }
} }

View file

@ -453,7 +453,7 @@ impl UnittestAssert {
Ok(assert(&node.into(), msg)) Ok(assert(&node.into(), msg))
} }
} }
_ => bail!("Cannot autofix `{self}`"), _ => bail!("Cannot fix `{self}`"),
} }
} }
} }

View file

@ -228,7 +228,7 @@ PT018.py:33:5: PT018 [*] Assertion should be broken down into multiple parts
34 |+ assert (b or c) 34 |+ assert (b or c)
34 35 | assert not (a or not (b and c)) 34 35 | assert not (a or not (b and c))
35 36 | 35 36 |
36 37 | # detected, but no autofix for messages 36 37 | # detected, but no fix for messages
PT018.py:34:5: PT018 [*] Assertion should be broken down into multiple parts PT018.py:34:5: PT018 [*] Assertion should be broken down into multiple parts
| |
@ -237,7 +237,7 @@ PT018.py:34:5: PT018 [*] Assertion should be broken down into multiple parts
34 | assert not (a or not (b and c)) 34 | assert not (a or not (b and c))
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ PT018 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ PT018
35 | 35 |
36 | # detected, but no autofix for messages 36 | # detected, but no fix for messages
| |
= help: Break down assertion into multiple parts = help: Break down assertion into multiple parts
@ -249,26 +249,26 @@ PT018.py:34:5: PT018 [*] Assertion should be broken down into multiple parts
34 |+ assert not a 34 |+ assert not a
35 |+ assert (b and c) 35 |+ assert (b and c)
35 36 | 35 36 |
36 37 | # detected, but no autofix for messages 36 37 | # detected, but no fix for messages
37 38 | assert something and something_else, "error message" 37 38 | assert something and something_else, "error message"
PT018.py:37:5: PT018 Assertion should be broken down into multiple parts PT018.py:37:5: PT018 Assertion should be broken down into multiple parts
| |
36 | # detected, but no autofix for messages 36 | # detected, but no fix for messages
37 | assert something and something_else, "error message" 37 | assert something and something_else, "error message"
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ PT018 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ PT018
38 | assert not (something or something_else and something_third), "with message" 38 | assert not (something or something_else and something_third), "with message"
39 | # detected, but no autofix for mixed conditions (e.g. `a or b and c`) 39 | # detected, but no fix for mixed conditions (e.g. `a or b and c`)
| |
= help: Break down assertion into multiple parts = help: Break down assertion into multiple parts
PT018.py:38:5: PT018 Assertion should be broken down into multiple parts PT018.py:38:5: PT018 Assertion should be broken down into multiple parts
| |
36 | # detected, but no autofix for messages 36 | # detected, but no fix for messages
37 | assert something and something_else, "error message" 37 | assert something and something_else, "error message"
38 | assert not (something or something_else and something_third), "with message" 38 | assert not (something or something_else and something_third), "with message"
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ PT018 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ PT018
39 | # detected, but no autofix for mixed conditions (e.g. `a or b and c`) 39 | # detected, but no fix for mixed conditions (e.g. `a or b and c`)
40 | assert not (something or something_else and something_third) 40 | assert not (something or something_else and something_third)
| |
= help: Break down assertion into multiple parts = help: Break down assertion into multiple parts
@ -276,7 +276,7 @@ PT018.py:38:5: PT018 Assertion should be broken down into multiple parts
PT018.py:40:5: PT018 Assertion should be broken down into multiple parts PT018.py:40:5: PT018 Assertion should be broken down into multiple parts
| |
38 | assert not (something or something_else and something_third), "with message" 38 | assert not (something or something_else and something_third), "with message"
39 | # detected, but no autofix for mixed conditions (e.g. `a or b and c`) 39 | # detected, but no fix for mixed conditions (e.g. `a or b and c`)
40 | assert not (something or something_else and something_third) 40 | assert not (something or something_else and something_third)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ PT018 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ PT018
| |

View file

@ -2,7 +2,7 @@ use ruff_python_parser::lexer::LexResult;
use ruff_python_parser::Tok; use ruff_python_parser::Tok;
use ruff_text_size::TextRange; use ruff_text_size::TextRange;
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_source_file::Locator; use ruff_source_file::Locator;
@ -37,7 +37,7 @@ pub struct BadQuotesInlineString {
quote: Quote, quote: Quote,
} }
impl AlwaysAutofixableViolation for BadQuotesInlineString { impl AlwaysFixableViolation for BadQuotesInlineString {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
let BadQuotesInlineString { quote } = self; let BadQuotesInlineString { quote } = self;
@ -47,7 +47,7 @@ impl AlwaysAutofixableViolation for BadQuotesInlineString {
} }
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
let BadQuotesInlineString { quote } = self; let BadQuotesInlineString { quote } = self;
match quote { match quote {
Quote::Double => "Replace single quotes with double quotes".to_string(), Quote::Double => "Replace single quotes with double quotes".to_string(),
@ -86,7 +86,7 @@ pub struct BadQuotesMultilineString {
quote: Quote, quote: Quote,
} }
impl AlwaysAutofixableViolation for BadQuotesMultilineString { impl AlwaysFixableViolation for BadQuotesMultilineString {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
let BadQuotesMultilineString { quote } = self; let BadQuotesMultilineString { quote } = self;
@ -96,7 +96,7 @@ impl AlwaysAutofixableViolation for BadQuotesMultilineString {
} }
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
let BadQuotesMultilineString { quote } = self; let BadQuotesMultilineString { quote } = self;
match quote { match quote {
Quote::Double => "Replace single multiline quotes with double quotes".to_string(), Quote::Double => "Replace single multiline quotes with double quotes".to_string(),
@ -134,7 +134,7 @@ pub struct BadQuotesDocstring {
quote: Quote, quote: Quote,
} }
impl AlwaysAutofixableViolation for BadQuotesDocstring { impl AlwaysFixableViolation for BadQuotesDocstring {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
let BadQuotesDocstring { quote } = self; let BadQuotesDocstring { quote } = self;
@ -144,7 +144,7 @@ impl AlwaysAutofixableViolation for BadQuotesDocstring {
} }
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
let BadQuotesDocstring { quote } = self; let BadQuotesDocstring { quote } = self;
match quote { match quote {
Quote::Double => "Replace single quotes docstring with double quotes".to_string(), Quote::Double => "Replace single quotes docstring with double quotes".to_string(),
@ -173,13 +173,13 @@ impl AlwaysAutofixableViolation for BadQuotesDocstring {
#[violation] #[violation]
pub struct AvoidableEscapedQuote; pub struct AvoidableEscapedQuote;
impl AlwaysAutofixableViolation for AvoidableEscapedQuote { impl AlwaysFixableViolation for AvoidableEscapedQuote {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Change outer quotes to avoid escaping inner quotes") format!("Change outer quotes to avoid escaping inner quotes")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Change outer quotes to avoid escaping inner quotes".to_string() "Change outer quotes to avoid escaping inner quotes".to_string()
} }
} }

View file

@ -1,4 +1,4 @@
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::{self as ast, Expr}; use ruff_python_ast::{self as ast, Expr};
use ruff_text_size::Ranged; use ruff_text_size::Ranged;
@ -31,13 +31,13 @@ use crate::registry::AsRule;
#[violation] #[violation]
pub struct UnnecessaryParenOnRaiseException; pub struct UnnecessaryParenOnRaiseException;
impl AlwaysAutofixableViolation for UnnecessaryParenOnRaiseException { impl AlwaysFixableViolation for UnnecessaryParenOnRaiseException {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Unnecessary parentheses on raised exception") format!("Unnecessary parentheses on raised exception")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
format!("Remove unnecessary parentheses") format!("Remove unnecessary parentheses")
} }
} }

View file

@ -3,7 +3,7 @@ use std::ops::Add;
use ruff_python_ast::{self as ast, ElifElseClause, Expr, Stmt}; use ruff_python_ast::{self as ast, ElifElseClause, Expr, Stmt};
use ruff_text_size::{Ranged, TextRange, TextSize}; use ruff_text_size::{Ranged, TextRange, TextSize};
use ruff_diagnostics::{AlwaysAutofixableViolation, Violation}; use ruff_diagnostics::{AlwaysFixableViolation, Violation};
use ruff_diagnostics::{Diagnostic, Edit, Fix}; use ruff_diagnostics::{Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::is_const_none; use ruff_python_ast::helpers::is_const_none;
@ -14,8 +14,8 @@ use ruff_python_ast::whitespace::indentation;
use ruff_python_semantic::SemanticModel; use ruff_python_semantic::SemanticModel;
use ruff_python_trivia::is_python_whitespace; use ruff_python_trivia::is_python_whitespace;
use crate::autofix::edits;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::fix::edits;
use crate::registry::{AsRule, Rule}; use crate::registry::{AsRule, Rule};
use crate::rules::flake8_return::helpers::end_of_last_statement; use crate::rules::flake8_return::helpers::end_of_last_statement;
@ -51,7 +51,7 @@ use super::super::visitor::{ReturnVisitor, Stack};
#[violation] #[violation]
pub struct UnnecessaryReturnNone; pub struct UnnecessaryReturnNone;
impl AlwaysAutofixableViolation for UnnecessaryReturnNone { impl AlwaysFixableViolation for UnnecessaryReturnNone {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!( format!(
@ -59,7 +59,7 @@ impl AlwaysAutofixableViolation for UnnecessaryReturnNone {
) )
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Remove explicit `return None`".to_string() "Remove explicit `return None`".to_string()
} }
} }
@ -93,13 +93,13 @@ impl AlwaysAutofixableViolation for UnnecessaryReturnNone {
#[violation] #[violation]
pub struct ImplicitReturnValue; pub struct ImplicitReturnValue;
impl AlwaysAutofixableViolation for ImplicitReturnValue { impl AlwaysFixableViolation for ImplicitReturnValue {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Do not implicitly `return None` in function able to return non-`None` value") format!("Do not implicitly `return None` in function able to return non-`None` value")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Add explicit `None` return value".to_string() "Add explicit `None` return value".to_string()
} }
} }
@ -131,13 +131,13 @@ impl AlwaysAutofixableViolation for ImplicitReturnValue {
#[violation] #[violation]
pub struct ImplicitReturn; pub struct ImplicitReturn;
impl AlwaysAutofixableViolation for ImplicitReturn { impl AlwaysFixableViolation for ImplicitReturn {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
format!("Missing explicit `return` at the end of function able to return non-`None` value") format!("Missing explicit `return` at the end of function able to return non-`None` value")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Add explicit `return` statement".to_string() "Add explicit `return` statement".to_string()
} }
} }
@ -167,14 +167,14 @@ pub struct UnnecessaryAssign {
name: String, name: String,
} }
impl AlwaysAutofixableViolation for UnnecessaryAssign { impl AlwaysFixableViolation for UnnecessaryAssign {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
let UnnecessaryAssign { name } = self; let UnnecessaryAssign { name } = self;
format!("Unnecessary assignment to `{name}` before `return` statement") format!("Unnecessary assignment to `{name}` before `return` statement")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Remove unnecessary assignment".to_string() "Remove unnecessary assignment".to_string()
} }
} }

View file

@ -131,7 +131,7 @@ RET504.py:342:12: RET504 [*] Unnecessary assignment to `b` before `return` state
= help: Remove unnecessary assignment = help: Remove unnecessary assignment
Suggested fix Suggested fix
338 338 | # Autofix cases 338 338 | # Fix cases
339 339 | def foo(): 339 339 | def foo():
340 340 | a = 1 340 340 | a = 1
341 |- b=a 341 |- b=a

View file

@ -7,7 +7,7 @@ use ruff_python_ast::{self as ast, Arguments, BoolOp, CmpOp, Expr, ExprContext,
use ruff_text_size::{Ranged, TextRange}; use ruff_text_size::{Ranged, TextRange};
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use ruff_diagnostics::{AlwaysAutofixableViolation, AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix, FixKind, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::comparable::ComparableExpr; use ruff_python_ast::comparable::ComparableExpr;
use ruff_python_ast::helpers::{contains_effect, Truthiness}; use ruff_python_ast::helpers::{contains_effect, Truthiness};
@ -49,7 +49,7 @@ pub struct DuplicateIsinstanceCall {
} }
impl Violation for DuplicateIsinstanceCall { impl Violation for DuplicateIsinstanceCall {
const AUTOFIX: AutofixKind = AutofixKind::Sometimes; const FIX_KIND: FixKind = FixKind::Sometimes;
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
@ -61,7 +61,7 @@ impl Violation for DuplicateIsinstanceCall {
} }
} }
fn autofix_title(&self) -> Option<String> { fn fix_title(&self) -> Option<String> {
let DuplicateIsinstanceCall { name } = self; let DuplicateIsinstanceCall { name } = self;
Some(if let Some(name) = name { Some(if let Some(name) = name {
@ -99,14 +99,14 @@ pub struct CompareWithTuple {
replacement: String, replacement: String,
} }
impl AlwaysAutofixableViolation for CompareWithTuple { impl AlwaysFixableViolation for CompareWithTuple {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
let CompareWithTuple { replacement } = self; let CompareWithTuple { replacement } = self;
format!("Use `{replacement}` instead of multiple equality comparisons") format!("Use `{replacement}` instead of multiple equality comparisons")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
let CompareWithTuple { replacement } = self; let CompareWithTuple { replacement } = self;
format!("Replace with `{replacement}`") format!("Replace with `{replacement}`")
} }
@ -132,14 +132,14 @@ pub struct ExprAndNotExpr {
name: String, name: String,
} }
impl AlwaysAutofixableViolation for ExprAndNotExpr { impl AlwaysFixableViolation for ExprAndNotExpr {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
let ExprAndNotExpr { name } = self; let ExprAndNotExpr { name } = self;
format!("Use `False` instead of `{name} and not {name}`") format!("Use `False` instead of `{name} and not {name}`")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Replace with `False`".to_string() "Replace with `False`".to_string()
} }
} }
@ -164,14 +164,14 @@ pub struct ExprOrNotExpr {
name: String, name: String,
} }
impl AlwaysAutofixableViolation for ExprOrNotExpr { impl AlwaysFixableViolation for ExprOrNotExpr {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
let ExprOrNotExpr { name } = self; let ExprOrNotExpr { name } = self;
format!("Use `True` instead of `{name} or not {name}`") format!("Use `True` instead of `{name} or not {name}`")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
"Replace with `True`".to_string() "Replace with `True`".to_string()
} }
} }
@ -217,7 +217,7 @@ pub struct ExprOrTrue {
remove: ContentAround, remove: ContentAround,
} }
impl AlwaysAutofixableViolation for ExprOrTrue { impl AlwaysFixableViolation for ExprOrTrue {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
let ExprOrTrue { expr, remove } = self; let ExprOrTrue { expr, remove } = self;
@ -229,7 +229,7 @@ impl AlwaysAutofixableViolation for ExprOrTrue {
format!("Use `{expr}` instead of `{replaced}`") format!("Use `{expr}` instead of `{replaced}`")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
let ExprOrTrue { expr, .. } = self; let ExprOrTrue { expr, .. } = self;
format!("Replace with `{expr}`") format!("Replace with `{expr}`")
} }
@ -269,7 +269,7 @@ pub struct ExprAndFalse {
remove: ContentAround, remove: ContentAround,
} }
impl AlwaysAutofixableViolation for ExprAndFalse { impl AlwaysFixableViolation for ExprAndFalse {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
let ExprAndFalse { expr, remove } = self; let ExprAndFalse { expr, remove } = self;
@ -281,7 +281,7 @@ impl AlwaysAutofixableViolation for ExprAndFalse {
format!("Use `{expr}` instead of `{replaced}`") format!("Use `{expr}` instead of `{replaced}`")
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
let ExprAndFalse { expr, .. } = self; let ExprAndFalse { expr, .. } = self;
format!("Replace with `{expr}`") format!("Replace with `{expr}`")
} }

View file

@ -1,8 +1,8 @@
use ruff_python_ast::{self as ast, Arguments, Constant, Expr}; use ruff_python_ast::{self as ast, Arguments, Constant, Expr};
use ruff_text_size::{Ranged, TextRange}; use ruff_text_size::{Ranged, TextRange};
use crate::autofix::snippet::SourceCodeSnippet; use crate::fix::snippet::SourceCodeSnippet;
use ruff_diagnostics::{AlwaysAutofixableViolation, AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix, FixKind, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::is_const_none; use ruff_python_ast::helpers::is_const_none;
@ -41,7 +41,7 @@ pub struct UncapitalizedEnvironmentVariables {
} }
impl Violation for UncapitalizedEnvironmentVariables { impl Violation for UncapitalizedEnvironmentVariables {
const AUTOFIX: AutofixKind = AutofixKind::Sometimes; const FIX_KIND: FixKind = FixKind::Sometimes;
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
@ -53,7 +53,7 @@ impl Violation for UncapitalizedEnvironmentVariables {
} }
} }
fn autofix_title(&self) -> Option<String> { fn fix_title(&self) -> Option<String> {
let UncapitalizedEnvironmentVariables { expected, actual } = self; let UncapitalizedEnvironmentVariables { expected, actual } = self;
if let (Some(expected), Some(actual)) = (expected.full_display(), actual.full_display()) { if let (Some(expected), Some(actual)) = (expected.full_display(), actual.full_display()) {
Some(format!("Replace `{actual}` with `{expected}`")) Some(format!("Replace `{actual}` with `{expected}`"))
@ -90,7 +90,7 @@ pub struct DictGetWithNoneDefault {
actual: SourceCodeSnippet, actual: SourceCodeSnippet,
} }
impl AlwaysAutofixableViolation for DictGetWithNoneDefault { impl AlwaysFixableViolation for DictGetWithNoneDefault {
#[derive_message_formats] #[derive_message_formats]
fn message(&self) -> String { fn message(&self) -> String {
let DictGetWithNoneDefault { expected, actual } = self; let DictGetWithNoneDefault { expected, actual } = self;
@ -101,7 +101,7 @@ impl AlwaysAutofixableViolation for DictGetWithNoneDefault {
} }
} }
fn autofix_title(&self) -> String { fn fix_title(&self) -> String {
let DictGetWithNoneDefault { expected, actual } = self; let DictGetWithNoneDefault { expected, actual } = self;
if let (Some(expected), Some(actual)) = (expected.full_display(), actual.full_display()) { if let (Some(expected), Some(actual)) = (expected.full_display(), actual.full_display()) {
format!("Replace `{actual}` with `{expected}`") format!("Replace `{actual}` with `{expected}`")

Some files were not shown because too many files have changed in this diff Show more