diff --git a/README.md b/README.md index ea51ab07cca46..5ea82dcc7b2fa 100644 --- a/README.md +++ b/README.md @@ -548,30 +548,30 @@ For more, see [Pyflakes](https://pypi.org/project/pyflakes/2.5.0/) on PyPI. | Code | Name | Message | Fix | | ---- | ---- | ------- | --- | -| F401 | UnusedImport | `...` imported but unused | 🛠 | -| F402 | ImportShadowedByLoopVar | Import `...` from line 1 shadowed by loop variable | | -| F403 | ImportStarUsed | `from ... import *` used; unable to detect undefined names | | +| F401 | UnusedImport | `{name}` imported but unused; consider adding to `__all__` or using a redundant alias | 🛠 | +| F402 | ImportShadowedByLoopVar | Import `{name}` from line {line} shadowed by loop variable | | +| F403 | ImportStarUsed | `from {name} import *` used; unable to detect undefined names | | | F404 | LateFutureImport | `from __future__` imports must occur at the beginning of the file | | -| F405 | ImportStarUsage | `...` may be undefined, or defined from star imports: `...` | | -| F406 | ImportStarNotPermitted | `from ... import *` only allowed at module level | | -| F407 | FutureFeatureNotDefined | Future feature `...` is not defined | | -| F501 | PercentFormatInvalidFormat | '...' % ... has invalid format string: ... | | +| F405 | ImportStarUsage | `{name}` may be undefined, or defined from star imports: {sources} | | +| F406 | ImportStarNotPermitted | `from {name} import *` only allowed at module level | | +| F407 | FutureFeatureNotDefined | Future feature `{name}` is not defined | | +| F501 | PercentFormatInvalidFormat | '...' % ... has invalid format string: {message} | | | F502 | PercentFormatExpectedMapping | '...' % ... expected mapping but got sequence | | | F503 | PercentFormatExpectedSequence | '...' % ... expected sequence but got mapping | | -| F504 | PercentFormatExtraNamedArguments | '...' % ... has unused named argument(s): ... | 🛠 | -| F505 | PercentFormatMissingArgument | '...' % ... is missing argument(s) for placeholder(s): ... | | +| F504 | PercentFormatExtraNamedArguments | '...' % ... has unused named argument(s): {message} | 🛠 | +| F505 | PercentFormatMissingArgument | '...' % ... is missing argument(s) for placeholder(s): {message} | | | F506 | PercentFormatMixedPositionalAndNamed | '...' % ... has mixed positional and named placeholders | | -| F507 | PercentFormatPositionalCountMismatch | '...' % ... has 4 placeholder(s) but 2 substitution(s) | | +| F507 | PercentFormatPositionalCountMismatch | '...' % ... has {wanted} placeholder(s) but {got} substitution(s) | | | F508 | PercentFormatStarRequiresSequence | '...' % ... `*` specifier requires sequence | | -| F509 | PercentFormatUnsupportedFormatCharacter | '...' % ... has unsupported format character 'c' | | -| F521 | StringDotFormatInvalidFormat | '...'.format(...) has invalid format string: ... | | -| F522 | StringDotFormatExtraNamedArguments | '...'.format(...) has unused named argument(s): ... | 🛠 | -| F523 | StringDotFormatExtraPositionalArguments | '...'.format(...) has unused arguments at position(s): ... | | -| F524 | StringDotFormatMissingArguments | '...'.format(...) is missing argument(s) for placeholder(s): ... | | +| F509 | PercentFormatUnsupportedFormatCharacter | '...' % ... has unsupported format character '{char}' | | +| F521 | StringDotFormatInvalidFormat | '...'.format(...) has invalid format string: {message} | | +| F522 | StringDotFormatExtraNamedArguments | '...'.format(...) has unused named argument(s): {message} | 🛠 | +| F523 | StringDotFormatExtraPositionalArguments | '...'.format(...) has unused arguments at position(s): {message} | | +| F524 | StringDotFormatMissingArguments | '...'.format(...) is missing argument(s) for placeholder(s): {message} | | | F525 | StringDotFormatMixingAutomatic | '...'.format(...) mixes automatic and manual numbering | | | F541 | FStringMissingPlaceholders | f-string without any placeholders | 🛠 | -| F601 | MultiValueRepeatedKeyLiteral | Dictionary key literal `...` repeated | 🛠 | -| F602 | MultiValueRepeatedKeyVariable | Dictionary key `...` repeated | 🛠 | +| F601 | MultiValueRepeatedKeyLiteral | Dictionary key literal `{name}` repeated | 🛠 | +| F602 | MultiValueRepeatedKeyVariable | Dictionary key `{name}` repeated | 🛠 | | F621 | ExpressionsInStarAssignment | Too many expressions in star-unpacking assignment | | | F622 | TwoStarredExpressions | Two starred expressions in assignment | | | F631 | AssertTuple | Assert test is a non-empty tuple, which is always `True` | | @@ -580,16 +580,16 @@ For more, see [Pyflakes](https://pypi.org/project/pyflakes/2.5.0/) on PyPI. | F634 | IfTuple | If test is a tuple, which is always `True` | | | F701 | BreakOutsideLoop | `break` outside loop | | | F702 | ContinueOutsideLoop | `continue` not properly in loop | | -| F704 | YieldOutsideFunction | `yield` statement outside of a function | | +| F704 | YieldOutsideFunction | `{keyword}` statement outside of a function | | | F706 | ReturnOutsideFunction | `return` statement outside of a function/method | | | F707 | DefaultExceptNotLast | An `except` block as not the last exception handler | | -| F722 | ForwardAnnotationSyntaxError | Syntax error in forward annotation: `...` | | -| F811 | RedefinedWhileUnused | Redefinition of unused `...` from line 1 | | -| F821 | UndefinedName | Undefined name `...` | | -| F822 | UndefinedExport | Undefined name `...` in `__all__` | | -| F823 | UndefinedLocal | Local variable `...` referenced before assignment | | -| F841 | UnusedVariable | Local variable `...` is assigned to but never used | 🛠 | -| F842 | UnusedAnnotation | Local variable `...` is annotated but never used | | +| F722 | ForwardAnnotationSyntaxError | Syntax error in forward annotation: `{body}` | | +| F811 | RedefinedWhileUnused | Redefinition of unused `{name}` from line {line} | | +| F821 | UndefinedName | Undefined name `{name}` | | +| F822 | UndefinedExport | Undefined name `{name}` in `__all__` | | +| F823 | UndefinedLocal | Local variable `{name}` referenced before assignment | | +| F841 | UnusedVariable | Local variable `{name}` is assigned to but never used | 🛠 | +| F842 | UnusedAnnotation | Local variable `{name}` is annotated but never used | | | F901 | RaiseNotImplemented | `raise NotImplemented` should be `raise NotImplementedError` | 🛠 | ### pycodestyle (E, W) @@ -601,7 +601,7 @@ For more, see [pycodestyle](https://pypi.org/project/pycodestyle/2.9.1/) on PyPI | ---- | ---- | ------- | --- | | E401 | MultipleImportsOnOneLine | Multiple imports on one line | | | E402 | ModuleImportNotAtTopOfFile | Module level import not at top of file | | -| E501 | LineTooLong | Line too long (89 > 88 characters) | | +| E501 | LineTooLong | Line too long ({length} > {limit} characters) | | | E711 | NoneComparison | Comparison to `None` should be `cond is None` | 🛠 | | E712 | TrueFalseComparison | Comparison to `True` should be `cond is True` | 🛠 | | E713 | NotInTest | Test for membership should be `not in` | 🛠 | @@ -609,18 +609,18 @@ For more, see [pycodestyle](https://pypi.org/project/pycodestyle/2.9.1/) on PyPI | E721 | TypeComparison | Do not compare types, use `isinstance()` | | | E722 | DoNotUseBareExcept | Do not use bare `except` | | | E731 | DoNotAssignLambda | Do not assign a `lambda` expression, use a `def` | 🛠 | -| E741 | AmbiguousVariableName | Ambiguous variable name: `...` | | -| E742 | AmbiguousClassName | Ambiguous class name: `...` | | -| E743 | AmbiguousFunctionName | Ambiguous function name: `...` | | -| E902 | IOError | IOError: `...` | | -| E999 | SyntaxError | SyntaxError: `...` | | +| E741 | AmbiguousVariableName | Ambiguous variable name: `{name}` | | +| E742 | AmbiguousClassName | Ambiguous class name: `{name}` | | +| E743 | AmbiguousFunctionName | Ambiguous function name: `{name}` | | +| E902 | IOError | {message} | | +| E999 | SyntaxError | SyntaxError: {message} | | #### Warning (W) | Code | Name | Message | Fix | | ---- | ---- | ------- | --- | | W292 | NoNewLineAtEndOfFile | No newline at end of file | 🛠 | -| W505 | DocLineTooLong | Doc line too long (89 > 88 characters) | | -| W605 | InvalidEscapeSequence | Invalid escape sequence: '\c' | 🛠 | +| W505 | DocLineTooLong | Doc line too long ({length} > {limit} characters) | | +| W605 | InvalidEscapeSequence | Invalid escape sequence: '\{char}' | 🛠 | ### mccabe (C90) @@ -628,7 +628,7 @@ For more, see [mccabe](https://pypi.org/project/mccabe/0.7.0/) on PyPI. | Code | Name | Message | Fix | | ---- | ---- | ------- | --- | -| C901 | FunctionIsTooComplex | `...` is too complex (10) | | +| C901 | FunctionIsTooComplex | `{name}` is too complex ({complexity}) | | ### isort (I) @@ -637,7 +637,7 @@ For more, see [isort](https://pypi.org/project/isort/5.10.1/) on PyPI. | Code | Name | Message | Fix | | ---- | ---- | ------- | --- | | I001 | UnsortedImports | Import block is un-sorted or un-formatted | 🛠 | -| I002 | MissingRequiredImport | Missing required import: `from __future__ import ...` | 🛠 | +| I002 | MissingRequiredImport | Missing required import: `{name}` | 🛠 | ### pydocstyle (D) @@ -654,11 +654,11 @@ For more, see [pydocstyle](https://pypi.org/project/pydocstyle/6.1.1/) on PyPI. | D106 | PublicNestedClass | Missing docstring in public nested class | | | D107 | PublicInit | Missing docstring in `__init__` | | | D200 | FitsOnOneLine | One-line docstring should fit on one line | | -| D201 | NoBlankLineBeforeFunction | No blank lines allowed before function docstring (found 1) | 🛠 | -| D202 | NoBlankLineAfterFunction | No blank lines allowed after function docstring (found 1) | 🛠 | +| D201 | NoBlankLineBeforeFunction | No blank lines allowed before function docstring (found {num_lines}) | 🛠 | +| D202 | NoBlankLineAfterFunction | No blank lines allowed after function docstring (found {num_lines}) | 🛠 | | D203 | OneBlankLineBeforeClass | 1 blank line required before class docstring | 🛠 | | D204 | OneBlankLineAfterClass | 1 blank line required after class docstring | 🛠 | -| D205 | BlankLineAfterSummary | 1 blank line required between summary line and description (found 2) | 🛠 | +| D205 | BlankLineAfterSummary | 1 blank line required between summary line and description | 🛠 | | D206 | IndentWithSpaces | Docstring should be indented with spaces, not tabs | | | D207 | NoUnderIndentation | Docstring is under-indented | 🛠 | | D208 | NoOverIndentation | Docstring is over-indented | 🛠 | @@ -667,27 +667,27 @@ For more, see [pydocstyle](https://pypi.org/project/pydocstyle/6.1.1/) on PyPI. | D211 | NoBlankLineBeforeClass | No blank lines allowed before class docstring | 🛠 | | D212 | MultiLineSummaryFirstLine | Multi-line docstring summary should start at the first line | | | D213 | MultiLineSummarySecondLine | Multi-line docstring summary should start at the second line | | -| D214 | SectionNotOverIndented | Section is over-indented ("Returns") | 🛠 | -| D215 | SectionUnderlineNotOverIndented | Section underline is over-indented ("Returns") | 🛠 | +| D214 | SectionNotOverIndented | Section is over-indented ("{name}") | 🛠 | +| D215 | SectionUnderlineNotOverIndented | Section underline is over-indented ("{name}") | 🛠 | | D300 | UsesTripleQuotes | Use """triple double quotes""" | | | D301 | UsesRPrefixForBackslashedContent | Use r""" if any backslashes in a docstring | | | D400 | EndsInPeriod | First line should end with a period | 🛠 | | D402 | NoSignature | First line should not be the function's signature | | | D403 | FirstLineCapitalized | First word of the first line should be properly capitalized | | | D404 | NoThisPrefix | First word of the docstring should not be "This" | | -| D405 | CapitalizeSectionName | Section name should be properly capitalized ("returns") | 🛠 | -| D406 | NewLineAfterSectionName | Section name should end with a newline ("Returns") | 🛠 | -| D407 | DashedUnderlineAfterSection | Missing dashed underline after section ("Returns") | 🛠 | -| D408 | SectionUnderlineAfterName | Section underline should be in the line following the section's name ("Returns") | 🛠 | -| D409 | SectionUnderlineMatchesSectionLength | Section underline should match the length of its name ("Returns") | 🛠 | -| D410 | BlankLineAfterSection | Missing blank line after section ("Returns") | 🛠 | -| D411 | BlankLineBeforeSection | Missing blank line before section ("Returns") | 🛠 | -| D412 | NoBlankLinesBetweenHeaderAndContent | No blank lines allowed between a section header and its content ("Returns") | 🛠 | -| D413 | BlankLineAfterLastSection | Missing blank line after last section ("Returns") | 🛠 | -| D414 | NonEmptySection | Section has no content ("Returns") | | +| D405 | CapitalizeSectionName | Section name should be properly capitalized ("{name}") | 🛠 | +| D406 | NewLineAfterSectionName | Section name should end with a newline ("{name}") | 🛠 | +| D407 | DashedUnderlineAfterSection | Missing dashed underline after section ("{name}") | 🛠 | +| D408 | SectionUnderlineAfterName | Section underline should be in the line following the section's name ("{name}") | 🛠 | +| D409 | SectionUnderlineMatchesSectionLength | Section underline should match the length of its name ("{name}") | 🛠 | +| D410 | BlankLineAfterSection | Missing blank line after section ("{name}") | 🛠 | +| D411 | BlankLineBeforeSection | Missing blank line before section ("{name}") | 🛠 | +| D412 | NoBlankLinesBetweenHeaderAndContent | No blank lines allowed between a section header and its content ("{name}") | 🛠 | +| D413 | BlankLineAfterLastSection | Missing blank line after last section ("{name}") | 🛠 | +| D414 | NonEmptySection | Section has no content ("{name}") | | | D415 | EndsInPunctuation | First line should end with a period, question mark, or exclamation point | 🛠 | -| D416 | SectionNameEndsInColon | Section name should end with a colon ("Returns") | 🛠 | -| D417 | DocumentAllArguments | Missing argument descriptions in the docstring: `x`, `y` | | +| D416 | SectionNameEndsInColon | Section name should end with a colon ("{name}") | 🛠 | +| D417 | DocumentAllArguments | Missing argument description in the docstring: `{name}` | | | D418 | SkipDocstring | Function decorated with `@overload` shouldn't contain a docstring | | | D419 | NonEmpty | Docstring is empty | | @@ -698,22 +698,22 @@ For more, see [pyupgrade](https://pypi.org/project/pyupgrade/3.2.0/) on PyPI. | Code | Name | Message | Fix | | ---- | ---- | ------- | --- | | UP001 | UselessMetaclassType | `__metaclass__ = type` is implied | 🛠 | -| UP003 | TypeOfPrimitive | Use `str` instead of `type(...)` | 🛠 | -| UP004 | UselessObjectInheritance | Class `...` inherits from `object` | 🛠 | -| UP005 | DeprecatedUnittestAlias | `assertEquals` is deprecated, use `assertEqual` | 🛠 | -| UP006 | UsePEP585Annotation | Use `list` instead of `List` for type annotations | 🛠 | +| UP003 | TypeOfPrimitive | Use `{}` instead of `type(...)` | 🛠 | +| UP004 | UselessObjectInheritance | Class `{name}` inherits from `object` | 🛠 | +| UP005 | DeprecatedUnittestAlias | `{alias}` is deprecated, use `{target}` | 🛠 | +| UP006 | UsePEP585Annotation | Use `{}` instead of `{}` for type annotations | 🛠 | | UP007 | UsePEP604Annotation | Use `X \| Y` for type annotations | 🛠 | | UP008 | SuperCallWithParameters | Use `super()` instead of `super(__class__, self)` | 🛠 | | UP009 | PEP3120UnnecessaryCodingComment | UTF-8 encoding declaration is unnecessary | 🛠 | -| UP010 | UnnecessaryFutureImport | Unnecessary `__future__` import `...` for target Python version | 🛠 | +| UP010 | UnnecessaryFutureImport | Unnecessary `__future__` import `{import}` for target Python version | 🛠 | | UP011 | LRUCacheWithoutParameters | Unnecessary parameters to `functools.lru_cache` | 🛠 | | UP012 | UnnecessaryEncodeUTF8 | Unnecessary call to `encode` as UTF-8 | 🛠 | -| UP013 | ConvertTypedDictFunctionalToClass | Convert `...` from `TypedDict` functional to class syntax | 🛠 | -| UP014 | ConvertNamedTupleFunctionalToClass | Convert `...` from `NamedTuple` functional to class syntax | 🛠 | +| UP013 | ConvertTypedDictFunctionalToClass | Convert `{name}` from `TypedDict` functional to class syntax | 🛠 | +| UP014 | ConvertNamedTupleFunctionalToClass | Convert `{name}` from `NamedTuple` functional to class syntax | 🛠 | | UP015 | RedundantOpenModes | Unnecessary open mode parameters | 🛠 | | UP016 | RemoveSixCompat | Unnecessary `six` compatibility usage | 🛠 | | UP017 | DatetimeTimezoneUTC | Use `datetime.UTC` alias | 🛠 | -| UP018 | NativeLiterals | Unnecessary call to `str` | 🛠 | +| UP018 | NativeLiterals | Unnecessary call to `{literal_type}` | 🛠 | | UP019 | TypingTextStrAlias | `typing.Text` is deprecated, use `str` | 🛠 | | UP020 | OpenAlias | Use builtin `open` | 🛠 | | UP021 | ReplaceUniversalNewlines | `universal_newlines` is deprecated, use `text` | 🛠 | @@ -724,7 +724,7 @@ For more, see [pyupgrade](https://pypi.org/project/pyupgrade/3.2.0/) on PyPI. | UP026 | RewriteMockImport | `mock` is deprecated, use `unittest.mock` | 🛠 | | UP027 | RewriteListComprehension | Replace unpacked list comprehension with a generator expression | 🛠 | | UP028 | RewriteYieldFrom | Replace `yield` over `for` loop with `yield from` | 🛠 | -| UP029 | UnnecessaryBuiltinImport | Unnecessary builtin import: `...` | 🛠 | +| UP029 | UnnecessaryBuiltinImport | Unnecessary builtin import: `{import}` | 🛠 | | UP030 | FormatLiterals | Use implicit references for positional format fields | 🛠 | | UP032 | FString | Use f-string instead of `format` call | 🛠 | | UP033 | FunctoolsCache | Use `@functools.cache` instead of `@functools.lru_cache(maxsize=None)` | 🛠 | @@ -735,21 +735,21 @@ For more, see [pep8-naming](https://pypi.org/project/pep8-naming/0.13.2/) on PyP | Code | Name | Message | Fix | | ---- | ---- | ------- | --- | -| N801 | InvalidClassName | Class name `...` should use CapWords convention | | -| N802 | InvalidFunctionName | Function name `...` should be lowercase | | -| N803 | InvalidArgumentName | Argument name `...` should be lowercase | | +| N801 | InvalidClassName | Class name `{name}` should use CapWords convention | | +| N802 | InvalidFunctionName | Function name `{name}` should be lowercase | | +| N803 | InvalidArgumentName | Argument name `{name}` should be lowercase | | | N804 | InvalidFirstArgumentNameForClassMethod | First argument of a class method should be named `cls` | | | N805 | InvalidFirstArgumentNameForMethod | First argument of a method should be named `self` | | -| N806 | NonLowercaseVariableInFunction | Variable `...` in function should be lowercase | | +| N806 | NonLowercaseVariableInFunction | Variable `{name}` in function should be lowercase | | | N807 | DunderFunctionName | Function name should not start and end with `__` | | -| N811 | ConstantImportedAsNonConstant | Constant `...` imported as non-constant `...` | | -| N812 | LowercaseImportedAsNonLowercase | Lowercase `...` imported as non-lowercase `...` | | -| N813 | CamelcaseImportedAsLowercase | Camelcase `...` imported as lowercase `...` | | -| N814 | CamelcaseImportedAsConstant | Camelcase `...` imported as constant `...` | | -| N815 | MixedCaseVariableInClassScope | Variable `mixedCase` in class scope should not be mixedCase | | -| N816 | MixedCaseVariableInGlobalScope | Variable `mixedCase` in global scope should not be mixedCase | | -| N817 | CamelcaseImportedAsAcronym | Camelcase `...` imported as acronym `...` | | -| N818 | ErrorSuffixOnExceptionName | Exception name `...` should be named with an Error suffix | | +| N811 | ConstantImportedAsNonConstant | Constant `{name}` imported as non-constant `{asname}` | | +| N812 | LowercaseImportedAsNonLowercase | Lowercase `{name}` imported as non-lowercase `{asname}` | | +| N813 | CamelcaseImportedAsLowercase | Camelcase `{name}` imported as lowercase `{asname}` | | +| N814 | CamelcaseImportedAsConstant | Camelcase `{name}` imported as constant `{asname}` | | +| N815 | MixedCaseVariableInClassScope | Variable `{name}` in class scope should not be mixedCase | | +| N816 | MixedCaseVariableInGlobalScope | Variable `{name}` in global scope should not be mixedCase | | +| N817 | CamelcaseImportedAsAcronym | Camelcase `{name}` imported as acronym `{asname}` | | +| N818 | ErrorSuffixOnExceptionName | Exception name `{name}` should be named with an Error suffix | | ### flake8-2020 (YTT) @@ -774,17 +774,17 @@ For more, see [flake8-annotations](https://pypi.org/project/flake8-annotations/2 | Code | Name | Message | Fix | | ---- | ---- | ------- | --- | -| ANN001 | MissingTypeFunctionArgument | Missing type annotation for function argument `...` | | -| ANN002 | MissingTypeArgs | Missing type annotation for `*...` | | -| ANN003 | MissingTypeKwargs | Missing type annotation for `**...` | | -| ANN101 | MissingTypeSelf | Missing type annotation for `...` in method | | -| ANN102 | MissingTypeCls | Missing type annotation for `...` in classmethod | | -| ANN201 | MissingReturnTypePublicFunction | Missing return type annotation for public function `...` | | -| ANN202 | MissingReturnTypePrivateFunction | Missing return type annotation for private function `...` | | -| ANN204 | MissingReturnTypeSpecialMethod | Missing return type annotation for special method `...` | 🛠 | -| ANN205 | MissingReturnTypeStaticMethod | Missing return type annotation for staticmethod `...` | | -| ANN206 | MissingReturnTypeClassMethod | Missing return type annotation for classmethod `...` | | -| ANN401 | DynamicallyTypedExpression | Dynamically typed expressions (typing.Any) are disallowed in `...` | | +| ANN001 | MissingTypeFunctionArgument | Missing type annotation for function argument `{name}` | | +| ANN002 | MissingTypeArgs | Missing type annotation for `*{name}` | | +| ANN003 | MissingTypeKwargs | Missing type annotation for `**{name}` | | +| ANN101 | MissingTypeSelf | Missing type annotation for `{name}` in method | | +| ANN102 | MissingTypeCls | Missing type annotation for `{name}` in classmethod | | +| ANN201 | MissingReturnTypePublicFunction | Missing return type annotation for public function `{name}` | | +| ANN202 | MissingReturnTypePrivateFunction | Missing return type annotation for private function `{name}` | | +| ANN204 | MissingReturnTypeSpecialMethod | Missing return type annotation for special method `{name}` | 🛠 | +| ANN205 | MissingReturnTypeStaticMethod | Missing return type annotation for staticmethod `{name}` | | +| ANN206 | MissingReturnTypeClassMethod | Missing return type annotation for classmethod `{name}` | | +| ANN401 | DynamicallyTypedExpression | Dynamically typed expressions (typing.Any) are disallowed in `{name}` | | ### flake8-bandit (S) @@ -794,19 +794,19 @@ For more, see [flake8-bandit](https://pypi.org/project/flake8-bandit/4.1.1/) on | ---- | ---- | ------- | --- | | S101 | AssertUsed | Use of `assert` detected | | | S102 | ExecUsed | Use of `exec` detected | | -| S103 | BadFilePermissions | `os.chmod` setting a permissive mask `0o777` on file or directory | | +| S103 | BadFilePermissions | `os.chmod` setting a permissive mask `{mask:#o}` on file or directory | | | S104 | HardcodedBindAllInterfaces | Possible binding to all interfaces | | -| S105 | HardcodedPasswordString | Possible hardcoded password: "..." | | -| S106 | HardcodedPasswordFuncArg | Possible hardcoded password: "..." | | -| S107 | HardcodedPasswordDefault | Possible hardcoded password: "..." | | -| S108 | HardcodedTempFile | Probable insecure usage of temporary file or directory: "..." | | -| S113 | RequestWithoutTimeout | Probable use of requests call without timeout | | -| S324 | HashlibInsecureHashFunction | Probable use of insecure hash functions in `hashlib`: "..." | | -| S501 | RequestWithNoCertValidation | Probable use of `...` call with `verify=False` disabling SSL certificate checks | | -| S506 | UnsafeYAMLLoad | Probable use of unsafe `yaml.load`. Allows instantiation of arbitrary objects. Consider `yaml.safe_load`. | | +| S105 | HardcodedPasswordString | Possible hardcoded password: "{}" | | +| S106 | HardcodedPasswordFuncArg | Possible hardcoded password: "{}" | | +| S107 | HardcodedPasswordDefault | Possible hardcoded password: "{}" | | +| S108 | HardcodedTempFile | Probable insecure usage of temporary file or directory: "{}" | | +| S113 | RequestWithoutTimeout | Probable use of requests call with timeout set to `{value}` | | +| S324 | HashlibInsecureHashFunction | Probable use of insecure hash functions in `hashlib`: "{}" | | +| S501 | RequestWithNoCertValidation | Probable use of `{string}` call with `verify=False` disabling SSL certificate checks | | +| S506 | UnsafeYAMLLoad | Probable use of unsafe loader `{name}` with `yaml.load`. Allows instantiation of arbitrary objects. Consider `yaml.safe_load`. | | | S508 | SnmpInsecureVersion | The use of SNMPv1 and SNMPv2 is insecure. Use SNMPv3 if able. | | | S509 | SnmpWeakCryptography | You should not use SNMPv3 without encryption. `noAuthNoPriv` & `authNoPriv` is insecure. | | -| S701 | Jinja2AutoescapeFalse | By default, jinja2 sets `autoescape` to `False`. Consider using `autoescape=True` or the `select_autoescape` function to mitigate XSS vulnerabilities. | | +| S701 | Jinja2AutoescapeFalse | Using jinja2 templates with `autoescape=False` is dangerous and can lead to XSS. Ensure `autoescape=True` or use the `select_autoescape` function. | | ### flake8-blind-except (BLE) @@ -814,7 +814,7 @@ For more, see [flake8-blind-except](https://pypi.org/project/flake8-blind-except | Code | Name | Message | Fix | | ---- | ---- | ------- | --- | -| BLE001 | BlindExcept | Do not catch blind exception: `Exception` | | +| BLE001 | BlindExcept | Do not catch blind exception: `{name}` | | ### flake8-boolean-trap (FBT) @@ -837,27 +837,27 @@ For more, see [flake8-bugbear](https://pypi.org/project/flake8-bugbear/22.10.27/ | B004 | UnreliableCallableCheck | Using `hasattr(x, '__call__')` to test if x is callable is unreliable. Use `callable(x)` for consistent results. | | | B005 | StripWithMultiCharacters | Using `.strip()` with multi-character strings is misleading the reader | | | B006 | MutableArgumentDefault | Do not use mutable data structures for argument defaults | | -| B007 | UnusedLoopControlVariable | Loop control variable `i` not used within the loop body | 🛠 | -| B008 | FunctionCallArgumentDefault | Do not perform function call in argument defaults | | +| B007 | UnusedLoopControlVariable | Loop control variable `{name}` not used within the loop body | 🛠 | +| B008 | FunctionCallArgumentDefault | Do not perform function call `{name}` in argument defaults | | | B009 | GetAttrWithConstant | Do not call `getattr` with a constant attribute value. It is not any safer than normal property access. | 🛠 | | B010 | SetAttrWithConstant | Do not call `setattr` with a constant attribute value. It is not any safer than normal property access. | 🛠 | | B011 | DoNotAssertFalse | Do not `assert False` (`python -O` removes these calls), raise `AssertionError()` | 🛠 | -| B012 | JumpStatementInFinally | `return/continue/break` inside finally blocks cause exceptions to be silenced | | -| B013 | RedundantTupleInExceptionHandler | A length-one tuple literal is redundant. Write `except ValueError` instead of `except (ValueError,)`. | 🛠 | -| B014 | DuplicateHandlerException | Exception handler with duplicate exception: `ValueError` | 🛠 | +| B012 | JumpStatementInFinally | `{name}` inside finally blocks cause exceptions to be silenced | | +| B013 | RedundantTupleInExceptionHandler | A length-one tuple literal is redundant. Write `except {name}` instead of `except ({name},)`. | 🛠 | +| B014 | DuplicateHandlerException | Exception handler with duplicate exception: `{name}` | 🛠 | | B015 | UselessComparison | Pointless comparison. This comparison does nothing but waste CPU instructions. Either prepend `assert` or remove it. | | | B016 | CannotRaiseLiteral | Cannot raise a literal. Did you intend to return it or raise an Exception? | | | B017 | NoAssertRaisesException | `assertRaises(Exception)` should be considered evil | | | B018 | UselessExpression | Found useless expression. Either assign it to a variable or remove it. | | | B019 | CachedInstanceMethod | Use of `functools.lru_cache` or `functools.cache` on methods can lead to memory leaks | | -| B020 | LoopVariableOverridesIterator | Loop control variable `...` overrides iterable it iterates | | +| B020 | LoopVariableOverridesIterator | Loop control variable `{name}` overrides iterable it iterates | | | B021 | FStringDocstring | f-string used as docstring. This will be interpreted by python as a joined string rather than a docstring. | | | B022 | UselessContextlibSuppress | No arguments passed to `contextlib.suppress`. No exceptions will be suppressed and therefore this context manager is redundant | | -| B023 | FunctionUsesLoopVariable | Function definition does not bind loop variable `...` | | -| B024 | AbstractBaseClassWithoutAbstractMethod | `...` is an abstract base class, but it has no abstract methods | | -| B025 | DuplicateTryBlockException | try-except block with duplicate exception `Exception` | | +| B023 | FunctionUsesLoopVariable | Function definition does not bind loop variable `{name}` | | +| B024 | AbstractBaseClassWithoutAbstractMethod | `{name}` is an abstract base class, but it has no abstract methods | | +| B025 | DuplicateTryBlockException | try-except block with duplicate exception `{name}` | | | B026 | StarArgUnpackingAfterKeywordArg | Star-arg unpacking after a keyword argument is strongly discouraged | | -| B027 | EmptyMethodWithoutAbstractDecorator | `...` is an empty method in an abstract base class, but has no abstract decorator | | +| B027 | EmptyMethodWithoutAbstractDecorator | `{name}` is an empty method in an abstract base class, but has no abstract decorator | | | B904 | RaiseWithoutFromInsideExcept | Within an except clause, raise exceptions with `raise ... from err` or `raise ... from None` to distinguish them from errors in exception handling | | | B905 | ZipWithoutExplicitStrict | `zip()` without an explicit `strict=` parameter | | @@ -867,9 +867,9 @@ For more, see [flake8-builtins](https://pypi.org/project/flake8-builtins/2.0.1/) | Code | Name | Message | Fix | | ---- | ---- | ------- | --- | -| A001 | BuiltinVariableShadowing | Variable `...` is shadowing a python builtin | | -| A002 | BuiltinArgumentShadowing | Argument `...` is shadowing a python builtin | | -| A003 | BuiltinAttributeShadowing | Class attribute `...` is shadowing a python builtin | | +| A001 | BuiltinVariableShadowing | Variable `{name}` is shadowing a python builtin | | +| A002 | BuiltinArgumentShadowing | Argument `{name}` is shadowing a python builtin | | +| A003 | BuiltinAttributeShadowing | Class attribute `{name}` is shadowing a python builtin | | ### flake8-comprehensions (C4) @@ -882,17 +882,17 @@ For more, see [flake8-comprehensions](https://pypi.org/project/flake8-comprehens | C402 | UnnecessaryGeneratorDict | Unnecessary generator (rewrite as a `dict` comprehension) | 🛠 | | C403 | UnnecessaryListComprehensionSet | Unnecessary `list` comprehension (rewrite as a `set` comprehension) | 🛠 | | C404 | UnnecessaryListComprehensionDict | Unnecessary `list` comprehension (rewrite as a `dict` comprehension) | 🛠 | -| C405 | UnnecessaryLiteralSet | Unnecessary `(list\|tuple)` literal (rewrite as a `set` literal) | 🛠 | -| C406 | UnnecessaryLiteralDict | Unnecessary `(list\|tuple)` literal (rewrite as a `dict` literal) | 🛠 | -| C408 | UnnecessaryCollectionCall | Unnecessary `(dict\|list\|tuple)` call (rewrite as a literal) | 🛠 | -| C409 | UnnecessaryLiteralWithinTupleCall | Unnecessary `(list\|tuple)` literal passed to `tuple()` (remove the outer call to `tuple()`) | 🛠 | -| C410 | UnnecessaryLiteralWithinListCall | Unnecessary `(list\|tuple)` literal passed to `list()` (rewrite as a `list` literal) | 🛠 | +| C405 | UnnecessaryLiteralSet | Unnecessary `{obj_type}` literal (rewrite as a `set` literal) | 🛠 | +| C406 | UnnecessaryLiteralDict | Unnecessary `{obj_type}` literal (rewrite as a `dict` literal) | 🛠 | +| C408 | UnnecessaryCollectionCall | Unnecessary `{obj_type}` call (rewrite as a literal) | 🛠 | +| C409 | UnnecessaryLiteralWithinTupleCall | Unnecessary `{literal}` literal passed to `tuple()` (rewrite as a `tuple` literal) | 🛠 | +| C410 | UnnecessaryLiteralWithinListCall | Unnecessary `{literal}` literal passed to `list()` (remove the outer call to `list()`) | 🛠 | | C411 | UnnecessaryListCall | Unnecessary `list` call (remove the outer call to `list()`) | 🛠 | -| C413 | UnnecessaryCallAroundSorted | Unnecessary `(list\|reversed)` call around `sorted()` | 🛠 | -| C414 | UnnecessaryDoubleCastOrProcess | Unnecessary `(list\|reversed\|set\|sorted\|tuple)` call within `(list\|set\|sorted\|tuple)()` | | -| C415 | UnnecessarySubscriptReversal | Unnecessary subscript reversal of iterable within `(reversed\|set\|sorted)()` | | -| C416 | UnnecessaryComprehension | Unnecessary `(list\|set)` comprehension (rewrite using `(list\|set)()`) | 🛠 | -| C417 | UnnecessaryMap | Unnecessary `map` usage (rewrite using a `(list\|set\|dict)` comprehension) | | +| C413 | UnnecessaryCallAroundSorted | Unnecessary `{func}` call around `sorted()` | 🛠 | +| C414 | UnnecessaryDoubleCastOrProcess | Unnecessary `{inner}` call within `{outer}()` | | +| C415 | UnnecessarySubscriptReversal | Unnecessary subscript reversal of iterable within `{func}()` | | +| C416 | UnnecessaryComprehension | Unnecessary `{obj_type}` comprehension (rewrite using `{obj_type}()`) | 🛠 | +| C417 | UnnecessaryMap | Unnecessary `map` usage (rewrite using a generator expression) | | ### flake8-debugger (T10) @@ -900,7 +900,7 @@ For more, see [flake8-debugger](https://pypi.org/project/flake8-debugger/4.1.2/) | Code | Name | Message | Fix | | ---- | ---- | ------- | --- | -| T100 | Debugger | Import for `...` found | | +| T100 | Debugger | Trace found: `{name}` used | | ### flake8-errmsg (EM) @@ -928,7 +928,7 @@ For more, see [flake8-import-conventions](https://github.com/joaopalmeiro/flake8 | Code | Name | Message | Fix | | ---- | ---- | ------- | --- | -| ICN001 | ImportAliasIsNotConventional | `...` should be imported as `...` | | +| ICN001 | ImportAliasIsNotConventional | `{name}` should be imported as `{asname}` | | ### flake8-print (T20) @@ -945,28 +945,28 @@ For more, see [flake8-pytest-style](https://pypi.org/project/flake8-pytest-style | Code | Name | Message | Fix | | ---- | ---- | ------- | --- | -| PT001 | IncorrectFixtureParenthesesStyle | Use `@pytest.fixture()` over `@pytest.fixture` | 🛠 | -| PT002 | FixturePositionalArgs | Configuration for fixture `...` specified via positional args, use kwargs | | +| PT001 | IncorrectFixtureParenthesesStyle | Use `@pytest.fixture{expected_parens}` over `@pytest.fixture{actual_parens}` | 🛠 | +| PT002 | FixturePositionalArgs | Configuration for fixture `{function}` specified via positional args, use kwargs | | | PT003 | ExtraneousScopeFunction | `scope='function'` is implied in `@pytest.fixture()` | | -| PT004 | MissingFixtureNameUnderscore | Fixture `...` does not return anything, add leading underscore | | -| PT005 | IncorrectFixtureNameUnderscore | Fixture `...` returns a value, remove leading underscore | | -| PT006 | ParametrizeNamesWrongType | Wrong name(s) type in `@pytest.mark.parametrize`, expected `tuple` | 🛠 | -| PT007 | ParametrizeValuesWrongType | Wrong values type in `@pytest.mark.parametrize` expected `list` of `tuple` | | +| PT004 | MissingFixtureNameUnderscore | Fixture `{function}` does not return anything, add leading underscore | | +| PT005 | IncorrectFixtureNameUnderscore | Fixture `{function}` returns a value, remove leading underscore | | +| PT006 | ParametrizeNamesWrongType | Wrong name(s) type in `@pytest.mark.parametrize`, expected `{expected}` | 🛠 | +| PT007 | ParametrizeValuesWrongType | Wrong values type in `@pytest.mark.parametrize` expected `{values}` of `{row}` | | | PT008 | PatchWithLambda | Use `return_value=` instead of patching with `lambda` | | -| PT009 | UnittestAssertion | Use a regular `assert` instead of unittest-style `...` | 🛠 | +| PT009 | UnittestAssertion | Use a regular `assert` instead of unittest-style `{assertion}` | 🛠 | | PT010 | RaisesWithoutException | set the expected exception in `pytest.raises()` | | -| PT011 | RaisesTooBroad | `pytest.raises(...)` is too broad, set the `match` parameter or use a more specific exception | | +| PT011 | RaisesTooBroad | `pytest.raises({exception})` is too broad, set the `match` parameter or use a more specific exception | | | PT012 | RaisesWithMultipleStatements | `pytest.raises()` block should contain a single simple statement | | | PT013 | IncorrectPytestImport | Found incorrect import of pytest, use simple `import pytest` instead | | | PT015 | AssertAlwaysFalse | Assertion always fails, replace with `pytest.fail()` | | | PT016 | FailWithoutMessage | No message passed to `pytest.fail()` | | -| PT017 | AssertInExcept | Found assertion on exception `...` in except block, use `pytest.raises()` instead | | +| PT017 | AssertInExcept | Found assertion on exception `{name}` in except block, use `pytest.raises()` instead | | | PT018 | CompositeAssertion | Assertion should be broken down into multiple parts | | -| PT019 | FixtureParamWithoutValue | Fixture `...` without value is injected as parameter, use `@pytest.mark.usefixtures` instead | | +| PT019 | FixtureParamWithoutValue | Fixture `{name}` without value is injected as parameter, use `@pytest.mark.usefixtures` instead | | | PT020 | DeprecatedYieldFixture | `@pytest.yield_fixture` is deprecated, use `@pytest.fixture` | | | PT021 | FixtureFinalizerCallback | Use `yield` instead of `request.addfinalizer` | | -| PT022 | UselessYieldFixture | No teardown in fixture `...`, use `return` instead of `yield` | 🛠 | -| PT023 | IncorrectMarkParenthesesStyle | Use `@pytest.mark....` over `@pytest.mark....()` | 🛠 | +| PT022 | UselessYieldFixture | No teardown in fixture `{name}`, use `return` instead of `yield` | 🛠 | +| PT023 | IncorrectMarkParenthesesStyle | Use `@pytest.mark.{mark_name}{expected_parens}` over `@pytest.mark.{mark_name}{actual_parens}` | 🛠 | | PT024 | UnnecessaryAsyncioMarkOnFixture | `pytest.mark.asyncio` is unnecessary for fixtures | 🛠 | | PT025 | ErroneousUseFixturesOnFixture | `pytest.mark.usefixtures` has no effect on fixtures | 🛠 | | PT026 | UseFixturesWithoutParameters | Useless `pytest.mark.usefixtures` without parameters | 🛠 | @@ -977,9 +977,9 @@ For more, see [flake8-quotes](https://pypi.org/project/flake8-quotes/3.3.1/) on | Code | Name | Message | Fix | | ---- | ---- | ------- | --- | -| Q000 | BadQuotesInlineString | Single quotes found but double quotes preferred | 🛠 | -| Q001 | BadQuotesMultilineString | Single quote multiline found but double quotes preferred | 🛠 | -| Q002 | BadQuotesDocstring | Single quote docstring found but double quotes preferred | 🛠 | +| Q000 | BadQuotesInlineString | Double quotes found but single quotes preferred | 🛠 | +| Q001 | BadQuotesMultilineString | Double quote multiline found but single quotes preferred | 🛠 | +| Q002 | BadQuotesDocstring | Double quote docstring found but single quotes preferred | 🛠 | | Q003 | AvoidQuoteEscape | Change outer quotes to avoid escaping inner quotes | 🛠 | ### flake8-return (RET) @@ -992,10 +992,10 @@ For more, see [flake8-return](https://pypi.org/project/flake8-return/1.2.0/) on | RET502 | ImplicitReturnValue | Do not implicitly `return None` in function able to return non-`None` value | 🛠 | | RET503 | ImplicitReturn | Missing explicit `return` at the end of function able to return non-`None` value | 🛠 | | RET504 | UnnecessaryAssign | Unnecessary variable assignment before `return` statement | | -| RET505 | SuperfluousElseReturn | Unnecessary `else` after `return` statement | | -| RET506 | SuperfluousElseRaise | Unnecessary `else` after `raise` statement | | -| RET507 | SuperfluousElseContinue | Unnecessary `else` after `continue` statement | | -| RET508 | SuperfluousElseBreak | Unnecessary `else` after `break` statement | | +| RET505 | SuperfluousElseReturn | Unnecessary `{branch}` after `return` statement | | +| RET506 | SuperfluousElseRaise | Unnecessary `{branch}` after `raise` statement | | +| RET507 | SuperfluousElseContinue | Unnecessary `{branch}` after `continue` statement | | +| RET508 | SuperfluousElseBreak | Unnecessary `{branch}` after `break` statement | | ### flake8-simplify (SIM) @@ -1003,31 +1003,31 @@ For more, see [flake8-simplify](https://pypi.org/project/flake8-simplify/0.19.3/ | Code | Name | Message | Fix | | ---- | ---- | ------- | --- | -| SIM101 | DuplicateIsinstanceCall | Multiple `isinstance` calls for `...`, merge into a single call | 🛠 | +| SIM101 | DuplicateIsinstanceCall | Multiple `isinstance` calls for `{name}`, merge into a single call | 🛠 | | SIM102 | NestedIfStatements | Use a single `if` statement instead of nested `if` statements | 🛠 | -| SIM103 | ReturnBoolConditionDirectly | Return the condition `...` directly | 🛠 | -| SIM105 | UseContextlibSuppress | Use `contextlib.suppress(...)` instead of try-except-pass | | +| SIM103 | ReturnBoolConditionDirectly | Return the condition `{cond}` directly | 🛠 | +| SIM105 | UseContextlibSuppress | Use `contextlib.suppress({exception})` instead of try-except-pass | | | SIM107 | ReturnInTryExceptFinally | Don't use `return` in `try`/`except` and `finally` | | -| SIM108 | UseTernaryOperator | Use ternary operator `...` instead of if-else-block | 🛠 | -| SIM109 | CompareWithTuple | Use `value in (... ,...)` instead of multiple equality comparisons | 🛠 | -| SIM110 | ConvertLoopToAny | Use `return any(x for x in y)` instead of `for` loop | 🛠 | -| SIM111 | ConvertLoopToAll | Use `return all(x for x in y)` instead of `for` loop | 🛠 | -| SIM112 | UseCapitalEnvironmentVariables | Use capitalized environment variable `...` instead of `...` | 🛠 | +| SIM108 | UseTernaryOperator | Use ternary operator `{contents}` instead of if-else-block | 🛠 | +| SIM109 | CompareWithTuple | Use `{replacement}` instead of multiple equality comparisons | 🛠 | +| SIM110 | ConvertLoopToAny | Use `{any}` instead of `for` loop | 🛠 | +| SIM111 | ConvertLoopToAll | Use `{all}` instead of `for` loop | 🛠 | +| SIM112 | UseCapitalEnvironmentVariables | Use capitalized environment variable `{expected}` instead of `{original}` | 🛠 | | SIM115 | OpenFileWithContextHandler | Use context handler for opening files | | | SIM117 | MultipleWithStatements | Use a single `with` statement with multiple contexts instead of nested `with` statements | 🛠 | -| SIM118 | KeyInDict | Use `key in dict` instead of `key in dict.keys()` | 🛠 | -| SIM201 | NegateEqualOp | Use `left != right` instead of `not left == right` | 🛠 | -| SIM202 | NegateNotEqualOp | Use `left == right` instead of `not left != right` | 🛠 | -| SIM208 | DoubleNegation | Use `expr` instead of `not (not expr)` | 🛠 | -| SIM210 | IfExprWithTrueFalse | Use `bool(expr)` instead of `True if expr else False` | 🛠 | -| SIM211 | IfExprWithFalseTrue | Use `not expr` instead of `False if expr else True` | 🛠 | -| SIM212 | IfExprWithTwistedArms | Use `b if b else a` instead of `a if not b else b` | 🛠 | -| SIM220 | AAndNotA | Use `False` instead of `... and not ...` | 🛠 | -| SIM221 | AOrNotA | Use `True` instead of `... or not ...` | 🛠 | +| SIM118 | KeyInDict | Use `{key} in {dict}` instead of `{key} in {dict}.keys()` | 🛠 | +| SIM201 | NegateEqualOp | Use `{left} != {right}` instead of `not {left} == {right}` | 🛠 | +| SIM202 | NegateNotEqualOp | Use `{left} == {right}` instead of `not {left} != {right}` | 🛠 | +| SIM208 | DoubleNegation | Use `{expr}` instead of `not (not {expr})` | 🛠 | +| SIM210 | IfExprWithTrueFalse | Use `bool({expr})` instead of `True if {expr} else False` | 🛠 | +| SIM211 | IfExprWithFalseTrue | Use `not {expr}` instead of `False if {expr} else True` | 🛠 | +| SIM212 | IfExprWithTwistedArms | Use `{expr_else} if {expr_else} else {expr_body}` instead of `{expr_body} if not {expr_else} else {expr_else}` | 🛠 | +| SIM220 | AAndNotA | Use `False` instead of `{name} and not {name}` | 🛠 | +| SIM221 | AOrNotA | Use `True` instead of `{name} or not {name}` | 🛠 | | SIM222 | OrTrue | Use `True` instead of `... or True` | 🛠 | | SIM223 | AndFalse | Use `False` instead of `... and False` | 🛠 | -| SIM300 | YodaConditions | Yoda conditions are discouraged, use `x == 1` instead | 🛠 | -| SIM401 | DictGetWithDefault | Use `var = dict.get(key, "default")` instead of an `if` block | 🛠 | +| SIM300 | YodaConditions | Yoda conditions are discouraged, use `{suggestion}` instead | 🛠 | +| SIM401 | DictGetWithDefault | Use `{contents}` instead of an `if` block | 🛠 | ### flake8-tidy-imports (TID) @@ -1035,8 +1035,8 @@ For more, see [flake8-tidy-imports](https://pypi.org/project/flake8-tidy-imports | Code | Name | Message | Fix | | ---- | ---- | ------- | --- | -| TID251 | BannedApi | `...` is banned: ... | | -| TID252 | RelativeImports | Relative imports are banned | | +| TID251 | BannedApi | `{name}` is banned: {message} | | +| TID252 | RelativeImports | Relative imports from parent modules are banned | | ### flake8-unused-arguments (ARG) @@ -1044,11 +1044,11 @@ For more, see [flake8-unused-arguments](https://pypi.org/project/flake8-unused-a | Code | Name | Message | Fix | | ---- | ---- | ------- | --- | -| ARG001 | UnusedFunctionArgument | Unused function argument: `...` | | -| ARG002 | UnusedMethodArgument | Unused method argument: `...` | | -| ARG003 | UnusedClassMethodArgument | Unused class method argument: `...` | | -| ARG004 | UnusedStaticMethodArgument | Unused static method argument: `...` | | -| ARG005 | UnusedLambdaArgument | Unused lambda argument: `...` | | +| ARG001 | UnusedFunctionArgument | Unused function argument: `{name}` | | +| ARG002 | UnusedMethodArgument | Unused method argument: `{name}` | | +| ARG003 | UnusedClassMethodArgument | Unused class method argument: `{name}` | | +| ARG004 | UnusedStaticMethodArgument | Unused static method argument: `{name}` | | +| ARG005 | UnusedLambdaArgument | Unused lambda argument: `{name}` | | ### flake8-datetimez (DTZ) @@ -1117,25 +1117,25 @@ For more, see [Pylint](https://pypi.org/project/pylint/2.15.7/) on PyPI. #### Error (PLE) | Code | Name | Message | Fix | | ---- | ---- | ------- | --- | -| PLE0117 | NonlocalWithoutBinding | Nonlocal name `...` found without binding | | -| PLE0118 | UsedPriorGlobalDeclaration | Name `...` is used prior to global declaration on line 1 | | +| PLE0117 | NonlocalWithoutBinding | Nonlocal name `{name}` found without binding | | +| PLE0118 | UsedPriorGlobalDeclaration | Name `{name}` is used prior to global declaration on line {line} | | | PLE1142 | AwaitOutsideAsync | `await` should be used within an async function | | #### Refactor (PLR) | Code | Name | Message | Fix | | ---- | ---- | ------- | --- | -| PLR0133 | ConstantComparison | Two constants compared in a comparison, consider replacing `0 == 0` | | +| PLR0133 | ConstantComparison | Two constants compared in a comparison, consider replacing `{left_constant} {op} {right_constant}` | | | PLR0206 | PropertyWithParameters | Cannot have defined parameters for properties | | -| PLR0402 | ConsiderUsingFromImport | Use `from ... import ...` in lieu of alias | | -| PLR1701 | ConsiderMergingIsinstance | Merge these isinstance calls: `isinstance(..., (...))` | | -| PLR1722 | UseSysExit | Use `sys.exit()` instead of `exit` | 🛠 | -| PLR2004 | MagicValueComparison | Magic value used in comparison, consider replacing magic with a constant variable | | +| PLR0402 | ConsiderUsingFromImport | Use `from {module} import {name}` in lieu of alias | | +| PLR1701 | ConsiderMergingIsinstance | Merge these isinstance calls: `isinstance({obj}, ({types}))` | | +| PLR1722 | UseSysExit | Use `sys.exit()` instead of `{name}` | 🛠 | +| PLR2004 | MagicValueComparison | Magic value used in comparison, consider replacing {value} with a constant variable | | #### Warning (PLW) | Code | Name | Message | Fix | | ---- | ---- | ------- | --- | | PLW0120 | UselessElseOnLoop | Else clause on loop without a break statement, remove the else and de-indent all the code inside it | | -| PLW0602 | GlobalVariableNotAssigned | Using global for `...` but no assignment is done | | +| PLW0602 | GlobalVariableNotAssigned | Using global for `{name}` but no assignment is done | | ### flake8-pie (PIE) @@ -1144,8 +1144,8 @@ For more, see [flake8-pie](https://pypi.org/project/flake8-pie/0.16.0/) on PyPI. | Code | Name | Message | Fix | | ---- | ---- | ------- | --- | | PIE790 | NoUnnecessaryPass | Unnecessary `pass` statement | 🛠 | -| PIE794 | DupeClassFieldDefinitions | Class field `...` is defined multiple times | 🛠 | -| PIE796 | PreferUniqueEnums | Enum contains duplicate value: `...` | | +| PIE794 | DupeClassFieldDefinitions | Class field `{name}` is defined multiple times | 🛠 | +| PIE796 | PreferUniqueEnums | Enum contains duplicate value: `{value}` | | | PIE807 | PreferListBuiltin | Prefer `list()` over useless lambda | 🛠 | ### flake8-commas (COM) @@ -1164,16 +1164,16 @@ For more, see [flake8-no-pep420](https://pypi.org/project/flake8-no-pep420/2.3.0 | Code | Name | Message | Fix | | ---- | ---- | ------- | --- | -| INP001 | ImplicitNamespacePackage | File `...` is part of an implicit namespace package. Add an `__init__.py`. | | +| INP001 | ImplicitNamespacePackage | File `{filename}` is part of an implicit namespace package. Add an `__init__.py`. | | ### Ruff-specific rules (RUF) | Code | Name | Message | Fix | | ---- | ---- | ------- | --- | -| RUF001 | AmbiguousUnicodeCharacterString | String contains ambiguous unicode character '𝐁' (did you mean 'B'?) | 🛠 | -| RUF002 | AmbiguousUnicodeCharacterDocstring | Docstring contains ambiguous unicode character '𝐁' (did you mean 'B'?) | 🛠 | -| RUF003 | AmbiguousUnicodeCharacterComment | Comment contains ambiguous unicode character '𝐁' (did you mean 'B'?) | 🛠 | -| RUF004 | KeywordArgumentBeforeStarArgument | Keyword argument `...` must come after starred arguments | | +| RUF001 | AmbiguousUnicodeCharacterString | String contains ambiguous unicode character '{confusable}' (did you mean '{representant}'?) | 🛠 | +| RUF002 | AmbiguousUnicodeCharacterDocstring | Docstring contains ambiguous unicode character '{confusable}' (did you mean '{representant}'?) | 🛠 | +| RUF003 | AmbiguousUnicodeCharacterComment | Comment contains ambiguous unicode character '{confusable}' (did you mean '{representant}'?) | 🛠 | +| RUF004 | KeywordArgumentBeforeStarArgument | Keyword argument `{name}` must come after starred arguments | | | RUF100 | UnusedNOQA | Unused blanket `noqa` directive | 🛠 | diff --git a/src/rules/flake8_tidy_imports/banned_api.rs b/src/rules/flake8_tidy_imports/banned_api.rs index a20d366815842..563b1c610a91d 100644 --- a/src/rules/flake8_tidy_imports/banned_api.rs +++ b/src/rules/flake8_tidy_imports/banned_api.rs @@ -27,17 +27,11 @@ define_violation!( } ); impl Violation for BannedApi { + #[derive_message_formats] fn message(&self) -> String { let BannedApi { name, message } = self; format!("`{name}` is banned: {message}") } - - fn placeholder() -> Self { - BannedApi { - name: "...".to_string(), - message: "...".to_string(), - } - } } /// TID251 diff --git a/src/rules/flake8_tidy_imports/relative_imports.rs b/src/rules/flake8_tidy_imports/relative_imports.rs index a3d679e5df1cb..0c6a4e3ee50e4 100644 --- a/src/rules/flake8_tidy_imports/relative_imports.rs +++ b/src/rules/flake8_tidy_imports/relative_imports.rs @@ -24,17 +24,14 @@ define_violation!( pub struct RelativeImports(pub Strictness); ); impl Violation for RelativeImports { + #[derive_message_formats] fn message(&self) -> String { let RelativeImports(strictness) = self; match strictness { - Strictness::Parents => "Relative imports from parent modules are banned".to_string(), - Strictness::All => "Relative imports are banned".to_string(), + Strictness::Parents => format!("Relative imports from parent modules are banned"), + Strictness::All => format!("Relative imports are banned"), } } - - fn placeholder() -> Self { - RelativeImports(Strictness::All) - } } /// TID252 diff --git a/src/violations.rs b/src/violations.rs index c8a7a2b9aa825..211313b2db3ff 100644 --- a/src/violations.rs +++ b/src/violations.rs @@ -13,7 +13,7 @@ use crate::rules::flake8_pytest_style::types::{ }; use crate::rules::flake8_quotes::settings::Quote; use crate::rules::pyupgrade::types::Primitive; -use crate::violation::{AlwaysAutofixableViolation, AutofixKind, Violation, Availability}; +use crate::violation::{AlwaysAutofixableViolation, AutofixKind, Availability, Violation}; // pycodestyle errors @@ -21,12 +21,9 @@ define_violation!( pub struct MultipleImportsOnOneLine; ); impl Violation for MultipleImportsOnOneLine { + #[derive_message_formats] fn message(&self) -> String { - "Multiple imports on one line".to_string() - } - - fn placeholder() -> Self { - MultipleImportsOnOneLine + format!("Multiple imports on one line") } } @@ -34,12 +31,9 @@ define_violation!( pub struct ModuleImportNotAtTopOfFile; ); impl Violation for ModuleImportNotAtTopOfFile { + #[derive_message_formats] fn message(&self) -> String { - "Module level import not at top of file".to_string() - } - - fn placeholder() -> Self { - ModuleImportNotAtTopOfFile + format!("Module level import not at top of file") } } @@ -47,14 +41,11 @@ define_violation!( pub struct LineTooLong(pub usize, pub usize); ); impl Violation for LineTooLong { + #[derive_message_formats] fn message(&self) -> String { let LineTooLong(length, limit) = self; format!("Line too long ({length} > {limit} characters)") } - - fn placeholder() -> Self { - LineTooLong(89, 88) - } } #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -77,11 +68,12 @@ define_violation!( pub struct NoneComparison(pub EqCmpop); ); impl AlwaysAutofixableViolation for NoneComparison { + #[derive_message_formats] fn message(&self) -> String { let NoneComparison(op) = self; match op { - EqCmpop::Eq => "Comparison to `None` should be `cond is None`".to_string(), - EqCmpop::NotEq => "Comparison to `None` should be `cond is not None`".to_string(), + EqCmpop::Eq => format!("Comparison to `None` should be `cond is None`"), + EqCmpop::NotEq => format!("Comparison to `None` should be `cond is not None`"), } } @@ -92,26 +84,23 @@ impl AlwaysAutofixableViolation for NoneComparison { EqCmpop::NotEq => "Replace with `cond is not None`".to_string(), } } - - fn placeholder() -> Self { - NoneComparison(EqCmpop::Eq) - } } define_violation!( pub struct TrueFalseComparison(pub bool, pub EqCmpop); ); impl AlwaysAutofixableViolation for TrueFalseComparison { + #[derive_message_formats] fn message(&self) -> String { let TrueFalseComparison(value, op) = self; match (value, op) { - (true, EqCmpop::Eq) => "Comparison to `True` should be `cond is True`".to_string(), + (true, EqCmpop::Eq) => format!("Comparison to `True` should be `cond is True`"), (true, EqCmpop::NotEq) => { - "Comparison to `True` should be `cond is not True`".to_string() + format!("Comparison to `True` should be `cond is not True`") } - (false, EqCmpop::Eq) => "Comparison to `False` should be `cond is False`".to_string(), + (false, EqCmpop::Eq) => format!("Comparison to `False` should be `cond is False`"), (false, EqCmpop::NotEq) => { - "Comparison to `False` should be `cond is not False`".to_string() + format!("Comparison to `False` should be `cond is not False`") } } } @@ -125,56 +114,43 @@ impl AlwaysAutofixableViolation for TrueFalseComparison { (false, EqCmpop::NotEq) => "Replace with `cond is not False`".to_string(), } } - - fn placeholder() -> Self { - TrueFalseComparison(true, EqCmpop::Eq) - } } define_violation!( pub struct NotInTest; ); impl AlwaysAutofixableViolation for NotInTest { + #[derive_message_formats] fn message(&self) -> String { - "Test for membership should be `not in`".to_string() + format!("Test for membership should be `not in`") } fn autofix_title(&self) -> String { "Convert to `not in`".to_string() } - - fn placeholder() -> Self { - NotInTest - } } define_violation!( pub struct NotIsTest; ); impl AlwaysAutofixableViolation for NotIsTest { + #[derive_message_formats] fn message(&self) -> String { - "Test for object identity should be `is not`".to_string() + format!("Test for object identity should be `is not`") } fn autofix_title(&self) -> String { "Convert to `is not`".to_string() } - - fn placeholder() -> Self { - NotIsTest - } } define_violation!( pub struct TypeComparison; ); impl Violation for TypeComparison { + #[derive_message_formats] fn message(&self) -> String { - "Do not compare types, use `isinstance()`".to_string() - } - - fn placeholder() -> Self { - TypeComparison + format!("Do not compare types, use `isinstance()`") } } @@ -182,12 +158,9 @@ define_violation!( pub struct DoNotUseBareExcept; ); impl Violation for DoNotUseBareExcept { + #[derive_message_formats] fn message(&self) -> String { - "Do not use bare `except`".to_string() - } - - fn placeholder() -> Self { - DoNotUseBareExcept + format!("Do not use bare `except`") } } @@ -195,88 +168,70 @@ define_violation!( pub struct DoNotAssignLambda(pub String); ); impl AlwaysAutofixableViolation for DoNotAssignLambda { + #[derive_message_formats] fn message(&self) -> String { - "Do not assign a `lambda` expression, use a `def`".to_string() + format!("Do not assign a `lambda` expression, use a `def`") } fn autofix_title(&self) -> String { let DoNotAssignLambda(name) = self; format!("Rewrite `{name}` as a `def`") } - - fn placeholder() -> Self { - DoNotAssignLambda("...".to_string()) - } } define_violation!( pub struct AmbiguousVariableName(pub String); ); impl Violation for AmbiguousVariableName { + #[derive_message_formats] fn message(&self) -> String { let AmbiguousVariableName(name) = self; format!("Ambiguous variable name: `{name}`") } - - fn placeholder() -> Self { - AmbiguousVariableName("...".to_string()) - } } define_violation!( pub struct AmbiguousClassName(pub String); ); impl Violation for AmbiguousClassName { + #[derive_message_formats] fn message(&self) -> String { let AmbiguousClassName(name) = self; format!("Ambiguous class name: `{name}`") } - - fn placeholder() -> Self { - AmbiguousClassName("...".to_string()) - } } define_violation!( pub struct AmbiguousFunctionName(pub String); ); impl Violation for AmbiguousFunctionName { + #[derive_message_formats] fn message(&self) -> String { let AmbiguousFunctionName(name) = self; format!("Ambiguous function name: `{name}`") } - - fn placeholder() -> Self { - AmbiguousFunctionName("...".to_string()) - } } define_violation!( pub struct IOError(pub String); ); impl Violation for IOError { + #[derive_message_formats] fn message(&self) -> String { let IOError(message) = self; format!("{message}") } - - fn placeholder() -> Self { - IOError("IOError: `...`".to_string()) - } } define_violation!( pub struct SyntaxError(pub String); ); impl Violation for SyntaxError { + #[derive_message_formats] fn message(&self) -> String { let SyntaxError(message) = self; format!("SyntaxError: {message}") } - - fn placeholder() -> Self { - SyntaxError("`...`".to_string()) - } } // pycodestyle warnings @@ -285,23 +240,21 @@ define_violation!( pub struct NoNewLineAtEndOfFile; ); impl AlwaysAutofixableViolation for NoNewLineAtEndOfFile { + #[derive_message_formats] fn message(&self) -> String { - "No newline at end of file".to_string() + format!("No newline at end of file") } fn autofix_title(&self) -> String { "Add trailing newline".to_string() } - - fn placeholder() -> Self { - NoNewLineAtEndOfFile - } } define_violation!( pub struct InvalidEscapeSequence(pub char); ); impl AlwaysAutofixableViolation for InvalidEscapeSequence { + #[derive_message_formats] fn message(&self) -> String { let InvalidEscapeSequence(char) = self; format!("Invalid escape sequence: '\\{char}'") @@ -310,24 +263,17 @@ impl AlwaysAutofixableViolation for InvalidEscapeSequence { fn autofix_title(&self) -> String { "Add backslash to escape sequence".to_string() } - - fn placeholder() -> Self { - InvalidEscapeSequence('c') - } } define_violation!( pub struct DocLineTooLong(pub usize, pub usize); ); impl Violation for DocLineTooLong { + #[derive_message_formats] fn message(&self) -> String { let DocLineTooLong(length, limit) = self; format!("Doc line too long ({length} > {limit} characters)") } - - fn placeholder() -> Self { - DocLineTooLong(89, 88) - } } // pyflakes @@ -346,6 +292,7 @@ fn fmt_unused_import_autofix_msg(unused_import: &UnusedImport) -> String { impl Violation for UnusedImport { const AUTOFIX: Option = Some(AutofixKind::new(Availability::Always)); + #[derive_message_formats] fn message(&self) -> String { let UnusedImport(name, ignore_init, ..) = self; if *ignore_init { @@ -366,50 +313,37 @@ impl Violation for UnusedImport { Some(fmt_unused_import_autofix_msg) } } - - fn placeholder() -> Self { - UnusedImport("...".to_string(), false, false) - } } define_violation!( pub struct ImportShadowedByLoopVar(pub String, pub usize); ); impl Violation for ImportShadowedByLoopVar { + #[derive_message_formats] fn message(&self) -> String { let ImportShadowedByLoopVar(name, line) = self; format!("Import `{name}` from line {line} shadowed by loop variable") } - - fn placeholder() -> Self { - ImportShadowedByLoopVar("...".to_string(), 1) - } } define_violation!( pub struct ImportStarUsed(pub String); ); impl Violation for ImportStarUsed { + #[derive_message_formats] fn message(&self) -> String { let ImportStarUsed(name) = self; format!("`from {name} import *` used; unable to detect undefined names") } - - fn placeholder() -> Self { - ImportStarUsed("...".to_string()) - } } define_violation!( pub struct LateFutureImport; ); impl Violation for LateFutureImport { + #[derive_message_formats] fn message(&self) -> String { - "`from __future__` imports must occur at the beginning of the file".to_string() - } - - fn placeholder() -> Self { - LateFutureImport + format!("`from __future__` imports must occur at the beginning of the file") } } @@ -417,6 +351,7 @@ define_violation!( pub struct ImportStarUsage(pub String, pub Vec); ); impl Violation for ImportStarUsage { + #[derive_message_formats] fn message(&self) -> String { let ImportStarUsage(name, sources) = self; let sources = sources @@ -425,64 +360,48 @@ impl Violation for ImportStarUsage { .join(", "); format!("`{name}` may be undefined, or defined from star imports: {sources}") } - - fn placeholder() -> Self { - ImportStarUsage("...".to_string(), vec!["...".to_string()]) - } } define_violation!( pub struct ImportStarNotPermitted(pub String); ); impl Violation for ImportStarNotPermitted { + #[derive_message_formats] fn message(&self) -> String { let ImportStarNotPermitted(name) = self; format!("`from {name} import *` only allowed at module level") } - - fn placeholder() -> Self { - ImportStarNotPermitted("...".to_string()) - } } define_violation!( pub struct FutureFeatureNotDefined(pub String); ); impl Violation for FutureFeatureNotDefined { + #[derive_message_formats] fn message(&self) -> String { let FutureFeatureNotDefined(name) = self; format!("Future feature `{name}` is not defined") } - - fn placeholder() -> Self { - FutureFeatureNotDefined("...".to_string()) - } } define_violation!( pub struct PercentFormatInvalidFormat(pub String); ); impl Violation for PercentFormatInvalidFormat { + #[derive_message_formats] fn message(&self) -> String { let PercentFormatInvalidFormat(message) = self; format!("'...' % ... has invalid format string: {message}") } - - fn placeholder() -> Self { - PercentFormatInvalidFormat("...".to_string()) - } } define_violation!( pub struct PercentFormatExpectedMapping; ); impl Violation for PercentFormatExpectedMapping { + #[derive_message_formats] fn message(&self) -> String { - "'...' % ... expected mapping but got sequence".to_string() - } - - fn placeholder() -> Self { - PercentFormatExpectedMapping + format!("'...' % ... expected mapping but got sequence") } } @@ -490,12 +409,9 @@ define_violation!( pub struct PercentFormatExpectedSequence; ); impl Violation for PercentFormatExpectedSequence { + #[derive_message_formats] fn message(&self) -> String { - "'...' % ... expected sequence but got mapping".to_string() - } - - fn placeholder() -> Self { - PercentFormatExpectedSequence + format!("'...' % ... expected sequence but got mapping") } } @@ -503,6 +419,7 @@ define_violation!( pub struct PercentFormatExtraNamedArguments(pub Vec); ); impl AlwaysAutofixableViolation for PercentFormatExtraNamedArguments { + #[derive_message_formats] fn message(&self) -> String { let PercentFormatExtraNamedArguments(missing) = self; let message = missing.join(", "); @@ -514,37 +431,27 @@ impl AlwaysAutofixableViolation for PercentFormatExtraNamedArguments { let message = missing.join(", "); format!("Remove extra named arguments: {message}") } - - fn placeholder() -> Self { - PercentFormatExtraNamedArguments(vec!["...".to_string()]) - } } define_violation!( pub struct PercentFormatMissingArgument(pub Vec); ); impl Violation for PercentFormatMissingArgument { + #[derive_message_formats] fn message(&self) -> String { let PercentFormatMissingArgument(missing) = self; let message = missing.join(", "); format!("'...' % ... is missing argument(s) for placeholder(s): {message}") } - - fn placeholder() -> Self { - PercentFormatMissingArgument(vec!["...".to_string()]) - } } define_violation!( pub struct PercentFormatMixedPositionalAndNamed; ); impl Violation for PercentFormatMixedPositionalAndNamed { + #[derive_message_formats] fn message(&self) -> String { - "'...' % ... has mixed positional and named placeholders".to_string() - } - - fn placeholder() -> Self { - PercentFormatMixedPositionalAndNamed + format!("'...' % ... has mixed positional and named placeholders") } } @@ -552,26 +459,20 @@ define_violation!( pub struct PercentFormatPositionalCountMismatch(pub usize, pub usize); ); impl Violation for PercentFormatPositionalCountMismatch { + #[derive_message_formats] fn message(&self) -> String { let PercentFormatPositionalCountMismatch(wanted, got) = self; format!("'...' % ... has {wanted} placeholder(s) but {got} substitution(s)") } - - fn placeholder() -> Self { - PercentFormatPositionalCountMismatch(4, 2) - } } define_violation!( pub struct PercentFormatStarRequiresSequence; ); impl Violation for PercentFormatStarRequiresSequence { + #[derive_message_formats] fn message(&self) -> String { - "'...' % ... `*` specifier requires sequence".to_string() - } - - fn placeholder() -> Self { - PercentFormatStarRequiresSequence + format!("'...' % ... `*` specifier requires sequence") } } @@ -579,34 +480,29 @@ define_violation!( pub struct PercentFormatUnsupportedFormatCharacter(pub char); ); impl Violation for PercentFormatUnsupportedFormatCharacter { + #[derive_message_formats] fn message(&self) -> String { let PercentFormatUnsupportedFormatCharacter(char) = self; format!("'...' % ... has unsupported format character '{char}'") } - - fn placeholder() -> Self { - PercentFormatUnsupportedFormatCharacter('c') - } } define_violation!( pub struct StringDotFormatInvalidFormat(pub String); ); impl Violation for StringDotFormatInvalidFormat { + #[derive_message_formats] fn message(&self) -> String { let StringDotFormatInvalidFormat(message) = self; format!("'...'.format(...) has invalid format string: {message}") } - - fn placeholder() -> Self { - StringDotFormatInvalidFormat("...".to_string()) - } } define_violation!( pub struct StringDotFormatExtraNamedArguments(pub Vec); ); impl AlwaysAutofixableViolation for StringDotFormatExtraNamedArguments { + #[derive_message_formats] fn message(&self) -> String { let StringDotFormatExtraNamedArguments(missing) = self; let message = missing.join(", "); @@ -618,52 +514,39 @@ impl AlwaysAutofixableViolation for StringDotFormatExtraNamedArguments { let message = missing.join(", "); format!("Remove extra named arguments: {message}") } - - fn placeholder() -> Self { - StringDotFormatExtraNamedArguments(vec!["...".to_string()]) - } } define_violation!( pub struct StringDotFormatExtraPositionalArguments(pub Vec); ); impl Violation for StringDotFormatExtraPositionalArguments { + #[derive_message_formats] fn message(&self) -> String { let StringDotFormatExtraPositionalArguments(missing) = self; let message = missing.join(", "); format!("'...'.format(...) has unused arguments at position(s): {message}") } - - fn placeholder() -> Self { - StringDotFormatExtraPositionalArguments(vec!["...".to_string()]) - } } define_violation!( pub struct StringDotFormatMissingArguments(pub Vec); ); impl Violation for StringDotFormatMissingArguments { + #[derive_message_formats] fn message(&self) -> String { let StringDotFormatMissingArguments(missing) = self; let message = missing.join(", "); format!("'...'.format(...) is missing argument(s) for placeholder(s): {message}") } - - fn placeholder() -> Self { - StringDotFormatMissingArguments(vec!["...".to_string()]) - } } define_violation!( pub struct StringDotFormatMixingAutomatic; ); impl Violation for StringDotFormatMixingAutomatic { + #[derive_message_formats] fn message(&self) -> String { - "'...'.format(...) mixes automatic and manual numbering".to_string() - } - - fn placeholder() -> Self { - StringDotFormatMixingAutomatic + format!("'...'.format(...) mixes automatic and manual numbering") } } @@ -671,17 +554,14 @@ define_violation!( pub struct FStringMissingPlaceholders; ); impl AlwaysAutofixableViolation for FStringMissingPlaceholders { + #[derive_message_formats] fn message(&self) -> String { - "f-string without any placeholders".to_string() + format!("f-string without any placeholders") } fn autofix_title(&self) -> String { "Remove extraneous `f` prefix".to_string() } - - fn placeholder() -> Self { - FStringMissingPlaceholders - } } define_violation!( @@ -690,6 +570,7 @@ define_violation!( impl Violation for MultiValueRepeatedKeyLiteral { const AUTOFIX: Option = Some(AutofixKind::new(Availability::Always)); + #[derive_message_formats] fn message(&self) -> String { let MultiValueRepeatedKeyLiteral(name, ..) = self; format!("Dictionary key literal `{name}` repeated") @@ -705,10 +586,6 @@ impl Violation for MultiValueRepeatedKeyLiteral { None } } - - fn placeholder() -> Self { - MultiValueRepeatedKeyLiteral("...".to_string(), true) - } } define_violation!( @@ -717,6 +594,7 @@ define_violation!( impl Violation for MultiValueRepeatedKeyVariable { const AUTOFIX: Option = Some(AutofixKind::new(Availability::Always)); + #[derive_message_formats] fn message(&self) -> String { let MultiValueRepeatedKeyVariable(name, ..) = self; format!("Dictionary key `{name}` repeated") @@ -730,22 +608,15 @@ impl Violation for MultiValueRepeatedKeyVariable { None } } - - fn placeholder() -> Self { - MultiValueRepeatedKeyVariable("...".to_string(), true) - } } define_violation!( pub struct ExpressionsInStarAssignment; ); impl Violation for ExpressionsInStarAssignment { + #[derive_message_formats] fn message(&self) -> String { - "Too many expressions in star-unpacking assignment".to_string() - } - - fn placeholder() -> Self { - ExpressionsInStarAssignment + format!("Too many expressions in star-unpacking assignment") } } @@ -753,12 +624,9 @@ define_violation!( pub struct TwoStarredExpressions; ); impl Violation for TwoStarredExpressions { + #[derive_message_formats] fn message(&self) -> String { - "Two starred expressions in assignment".to_string() - } - - fn placeholder() -> Self { - TwoStarredExpressions + format!("Two starred expressions in assignment") } } @@ -766,12 +634,9 @@ define_violation!( pub struct AssertTuple; ); impl Violation for AssertTuple { + #[derive_message_formats] fn message(&self) -> String { - "Assert test is a non-empty tuple, which is always `True`".to_string() - } - - fn placeholder() -> Self { - AssertTuple + format!("Assert test is a non-empty tuple, which is always `True`") } } @@ -795,11 +660,12 @@ define_violation!( pub struct IsLiteral(pub IsCmpop); ); impl AlwaysAutofixableViolation for IsLiteral { + #[derive_message_formats] fn message(&self) -> String { let IsLiteral(cmpop) = self; match cmpop { - IsCmpop::Is => "Use `==` to compare constant literals".to_string(), - IsCmpop::IsNot => "Use `!=` to compare constant literals".to_string(), + IsCmpop::Is => format!("Use `==` to compare constant literals"), + IsCmpop::IsNot => format!("Use `!=` to compare constant literals"), } } @@ -810,22 +676,15 @@ impl AlwaysAutofixableViolation for IsLiteral { IsCmpop::IsNot => "Replace `is not` with `!=`".to_string(), } } - - fn placeholder() -> Self { - IsLiteral(IsCmpop::Is) - } } define_violation!( pub struct InvalidPrintSyntax; ); impl Violation for InvalidPrintSyntax { + #[derive_message_formats] fn message(&self) -> String { - "Use of `>>` is invalid with `print` function".to_string() - } - - fn placeholder() -> Self { - InvalidPrintSyntax + format!("Use of `>>` is invalid with `print` function") } } @@ -833,12 +692,9 @@ define_violation!( pub struct IfTuple; ); impl Violation for IfTuple { + #[derive_message_formats] fn message(&self) -> String { - "If test is a tuple, which is always `True`".to_string() - } - - fn placeholder() -> Self { - IfTuple + format!("If test is a tuple, which is always `True`") } } @@ -846,12 +702,9 @@ define_violation!( pub struct BreakOutsideLoop; ); impl Violation for BreakOutsideLoop { + #[derive_message_formats] fn message(&self) -> String { - "`break` outside loop".to_string() - } - - fn placeholder() -> Self { - BreakOutsideLoop + format!("`break` outside loop") } } @@ -859,12 +712,9 @@ define_violation!( pub struct ContinueOutsideLoop; ); impl Violation for ContinueOutsideLoop { + #[derive_message_formats] fn message(&self) -> String { - "`continue` not properly in loop".to_string() - } - - fn placeholder() -> Self { - ContinueOutsideLoop + format!("`continue` not properly in loop") } } @@ -889,26 +739,20 @@ define_violation!( pub struct YieldOutsideFunction(pub DeferralKeyword); ); impl Violation for YieldOutsideFunction { + #[derive_message_formats] fn message(&self) -> String { let YieldOutsideFunction(keyword) = self; format!("`{keyword}` statement outside of a function") } - - fn placeholder() -> Self { - YieldOutsideFunction(DeferralKeyword::Yield) - } } define_violation!( pub struct ReturnOutsideFunction; ); impl Violation for ReturnOutsideFunction { + #[derive_message_formats] fn message(&self) -> String { - "`return` statement outside of a function/method".to_string() - } - - fn placeholder() -> Self { - ReturnOutsideFunction + format!("`return` statement outside of a function/method") } } @@ -916,12 +760,9 @@ define_violation!( pub struct DefaultExceptNotLast; ); impl Violation for DefaultExceptNotLast { + #[derive_message_formats] fn message(&self) -> String { - "An `except` block as not the last exception handler".to_string() - } - - fn placeholder() -> Self { - DefaultExceptNotLast + format!("An `except` block as not the last exception handler") } } @@ -929,76 +770,62 @@ define_violation!( pub struct ForwardAnnotationSyntaxError(pub String); ); impl Violation for ForwardAnnotationSyntaxError { + #[derive_message_formats] fn message(&self) -> String { let ForwardAnnotationSyntaxError(body) = self; format!("Syntax error in forward annotation: `{body}`") } - - fn placeholder() -> Self { - ForwardAnnotationSyntaxError("...".to_string()) - } } define_violation!( pub struct RedefinedWhileUnused(pub String, pub usize); ); impl Violation for RedefinedWhileUnused { + #[derive_message_formats] fn message(&self) -> String { let RedefinedWhileUnused(name, line) = self; format!("Redefinition of unused `{name}` from line {line}") } - - fn placeholder() -> Self { - RedefinedWhileUnused("...".to_string(), 1) - } } define_violation!( pub struct UndefinedName(pub String); ); impl Violation for UndefinedName { + #[derive_message_formats] fn message(&self) -> String { let UndefinedName(name) = self; format!("Undefined name `{name}`") } - - fn placeholder() -> Self { - UndefinedName("...".to_string()) - } } define_violation!( pub struct UndefinedExport(pub String); ); impl Violation for UndefinedExport { + #[derive_message_formats] fn message(&self) -> String { let UndefinedExport(name) = self; format!("Undefined name `{name}` in `__all__`") } - - fn placeholder() -> Self { - UndefinedExport("...".to_string()) - } } define_violation!( pub struct UndefinedLocal(pub String); ); impl Violation for UndefinedLocal { + #[derive_message_formats] fn message(&self) -> String { let UndefinedLocal(name) = self; format!("Local variable `{name}` referenced before assignment") } - - fn placeholder() -> Self { - UndefinedLocal("...".to_string()) - } } define_violation!( pub struct UnusedVariable(pub String); ); impl AlwaysAutofixableViolation for UnusedVariable { + #[derive_message_formats] fn message(&self) -> String { let UnusedVariable(name) = self; format!("Local variable `{name}` is assigned to but never used") @@ -1008,41 +835,31 @@ impl AlwaysAutofixableViolation for UnusedVariable { let UnusedVariable(name) = self; format!("Remove assignment to unused variable `{name}`") } - - fn placeholder() -> Self { - UnusedVariable("...".to_string()) - } } define_violation!( pub struct UnusedAnnotation(pub String); ); impl Violation for UnusedAnnotation { + #[derive_message_formats] fn message(&self) -> String { let UnusedAnnotation(name) = self; format!("Local variable `{name}` is annotated but never used") } - - fn placeholder() -> Self { - UnusedAnnotation("...".to_string()) - } } define_violation!( pub struct RaiseNotImplemented; ); impl AlwaysAutofixableViolation for RaiseNotImplemented { + #[derive_message_formats] fn message(&self) -> String { - "`raise NotImplemented` should be `raise NotImplementedError`".to_string() + format!("`raise NotImplemented` should be `raise NotImplementedError`") } fn autofix_title(&self) -> String { "Use `raise NotImplementedError`".to_string() } - - fn placeholder() -> Self { - RaiseNotImplemented - } } // pylint @@ -1051,29 +868,23 @@ define_violation!( pub struct UselessImportAlias; ); impl AlwaysAutofixableViolation for UselessImportAlias { + #[derive_message_formats] fn message(&self) -> String { - "Import alias does not rename original package".to_string() + format!("Import alias does not rename original package") } fn autofix_title(&self) -> String { "Remove import alias".to_string() } - - fn placeholder() -> Self { - UselessImportAlias - } } define_violation!( pub struct UnnecessaryDirectLambdaCall; ); impl Violation for UnnecessaryDirectLambdaCall { + #[derive_message_formats] fn message(&self) -> String { - "Lambda expression called directly. Execute the expression inline instead.".to_string() - } - - fn placeholder() -> Self { - UnnecessaryDirectLambdaCall + format!("Lambda expression called directly. Execute the expression inline instead.") } } @@ -1081,40 +892,31 @@ define_violation!( pub struct NonlocalWithoutBinding(pub String); ); impl Violation for NonlocalWithoutBinding { + #[derive_message_formats] fn message(&self) -> String { let NonlocalWithoutBinding(name) = self; format!("Nonlocal name `{name}` found without binding") } - - fn placeholder() -> Self { - NonlocalWithoutBinding("...".to_string()) - } } define_violation!( pub struct UsedPriorGlobalDeclaration(pub String, pub usize); ); impl Violation for UsedPriorGlobalDeclaration { + #[derive_message_formats] fn message(&self) -> String { let UsedPriorGlobalDeclaration(name, line) = self; format!("Name `{name}` is used prior to global declaration on line {line}") } - - fn placeholder() -> Self { - UsedPriorGlobalDeclaration("...".to_string(), 1) - } } define_violation!( pub struct AwaitOutsideAsync; ); impl Violation for AwaitOutsideAsync { + #[derive_message_formats] fn message(&self) -> String { - "`await` should be used within an async function".to_string() - } - - fn placeholder() -> Self { - AwaitOutsideAsync + format!("`await` should be used within an async function") } } @@ -1122,12 +924,9 @@ define_violation!( pub struct PropertyWithParameters; ); impl Violation for PropertyWithParameters { + #[derive_message_formats] fn message(&self) -> String { - "Cannot have defined parameters for properties".to_string() - } - - fn placeholder() -> Self { - PropertyWithParameters + format!("Cannot have defined parameters for properties") } } @@ -1135,14 +934,11 @@ define_violation!( pub struct ConsiderUsingFromImport(pub String, pub String); ); impl Violation for ConsiderUsingFromImport { + #[derive_message_formats] fn message(&self) -> String { let ConsiderUsingFromImport(module, name) = self; format!("Use `from {module} import {name}` in lieu of alias") } - - fn placeholder() -> Self { - ConsiderUsingFromImport("...".to_string(), "...".to_string()) - } } #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -1202,6 +998,7 @@ define_violation!( } ); impl Violation for ConstantComparison { + #[derive_message_formats] fn message(&self) -> String { let ConstantComparison { left_constant, @@ -1214,35 +1011,25 @@ impl Violation for ConstantComparison { {right_constant}`" ) } - - fn placeholder() -> Self { - ConstantComparison { - left_constant: "0".to_string(), - op: ViolationsCmpop::Eq, - right_constant: "0".to_string(), - } - } } define_violation!( pub struct ConsiderMergingIsinstance(pub String, pub Vec); ); impl Violation for ConsiderMergingIsinstance { + #[derive_message_formats] fn message(&self) -> String { let ConsiderMergingIsinstance(obj, types) = self; let types = types.join(", "); format!("Merge these isinstance calls: `isinstance({obj}, ({types}))`") } - - fn placeholder() -> Self { - ConsiderMergingIsinstance("...".to_string(), vec!["...".to_string()]) - } } define_violation!( pub struct UseSysExit(pub String); ); impl AlwaysAutofixableViolation for UseSysExit { + #[derive_message_formats] fn message(&self) -> String { let UseSysExit(name) = self; format!("Use `sys.exit()` instead of `{name}`") @@ -1252,10 +1039,6 @@ impl AlwaysAutofixableViolation for UseSysExit { let UseSysExit(name) = self; format!("Replace `{name}` with `sys.exit()`") } - - fn placeholder() -> Self { - UseSysExit("exit".to_string()) - } } define_violation!( @@ -1264,32 +1047,25 @@ define_violation!( } ); impl Violation for MagicValueComparison { + #[derive_message_formats] fn message(&self) -> String { let MagicValueComparison { value } = self; format!( "Magic value used in comparison, consider replacing {value} with a constant variable" ) } - - fn placeholder() -> Self { - MagicValueComparison { - value: "magic".to_string(), - } - } } define_violation!( pub struct UselessElseOnLoop; ); impl Violation for UselessElseOnLoop { + #[derive_message_formats] fn message(&self) -> String { - "Else clause on loop without a break statement, remove the else and de-indent all the code \ - inside it" - .to_string() - } - - fn placeholder() -> Self { - UselessElseOnLoop + format!( + "Else clause on loop without a break statement, remove the else and de-indent all the \ + code inside it" + ) } } @@ -1297,14 +1073,11 @@ define_violation!( pub struct GlobalVariableNotAssigned(pub String); ); impl Violation for GlobalVariableNotAssigned { + #[derive_message_formats] fn message(&self) -> String { let GlobalVariableNotAssigned(name) = self; format!("Using global for `{name}` but no assignment is done") } - - fn placeholder() -> Self { - GlobalVariableNotAssigned("...".to_string()) - } } // flake8-builtins @@ -1313,42 +1086,33 @@ define_violation!( pub struct BuiltinVariableShadowing(pub String); ); impl Violation for BuiltinVariableShadowing { + #[derive_message_formats] fn message(&self) -> String { let BuiltinVariableShadowing(name) = self; format!("Variable `{name}` is shadowing a python builtin") } - - fn placeholder() -> Self { - BuiltinVariableShadowing("...".to_string()) - } } define_violation!( pub struct BuiltinArgumentShadowing(pub String); ); impl Violation for BuiltinArgumentShadowing { + #[derive_message_formats] fn message(&self) -> String { let BuiltinArgumentShadowing(name) = self; format!("Argument `{name}` is shadowing a python builtin") } - - fn placeholder() -> Self { - BuiltinArgumentShadowing("...".to_string()) - } } define_violation!( pub struct BuiltinAttributeShadowing(pub String); ); impl Violation for BuiltinAttributeShadowing { + #[derive_message_formats] fn message(&self) -> String { let BuiltinAttributeShadowing(name) = self; format!("Class attribute `{name}` is shadowing a python builtin") } - - fn placeholder() -> Self { - BuiltinAttributeShadowing("...".to_string()) - } } // flake8-bugbear @@ -1357,25 +1121,19 @@ define_violation!( pub struct UnaryPrefixIncrement; ); impl Violation for UnaryPrefixIncrement { + #[derive_message_formats] fn message(&self) -> String { format!("Python does not support the unary prefix increment") } - - fn placeholder() -> Self { - UnaryPrefixIncrement - } } define_violation!( pub struct AssignmentToOsEnviron; ); impl Violation for AssignmentToOsEnviron { + #[derive_message_formats] fn message(&self) -> String { - "Assigning to `os.environ` doesn't clear the environment".to_string() - } - - fn placeholder() -> Self { - AssignmentToOsEnviron + format!("Assigning to `os.environ` doesn't clear the environment") } } @@ -1383,14 +1141,12 @@ define_violation!( pub struct UnreliableCallableCheck; ); impl Violation for UnreliableCallableCheck { + #[derive_message_formats] fn message(&self) -> String { - " Using `hasattr(x, '__call__')` to test if x is callable is unreliable. Use `callable(x)` \ - for consistent results." - .to_string() - } - - fn placeholder() -> Self { - UnreliableCallableCheck + format!( + " Using `hasattr(x, '__call__')` to test if x is callable is unreliable. Use \ + `callable(x)` for consistent results." + ) } } @@ -1398,12 +1154,9 @@ define_violation!( pub struct StripWithMultiCharacters; ); impl Violation for StripWithMultiCharacters { + #[derive_message_formats] fn message(&self) -> String { - "Using `.strip()` with multi-character strings is misleading the reader".to_string() - } - - fn placeholder() -> Self { - StripWithMultiCharacters + format!("Using `.strip()` with multi-character strings is misleading the reader") } } @@ -1411,12 +1164,9 @@ define_violation!( pub struct MutableArgumentDefault; ); impl Violation for MutableArgumentDefault { + #[derive_message_formats] fn message(&self) -> String { - "Do not use mutable data structures for argument defaults".to_string() - } - - fn placeholder() -> Self { - MutableArgumentDefault + format!("Do not use mutable data structures for argument defaults") } } @@ -1424,6 +1174,7 @@ define_violation!( pub struct UnusedLoopControlVariable(pub String); ); impl AlwaysAutofixableViolation for UnusedLoopControlVariable { + #[derive_message_formats] fn message(&self) -> String { let UnusedLoopControlVariable(name) = self; format!("Loop control variable `{name}` not used within the loop body") @@ -1433,104 +1184,87 @@ impl AlwaysAutofixableViolation for UnusedLoopControlVariable { let UnusedLoopControlVariable(name) = self; format!("Rename unused `{name}` to `_{name}`") } - - fn placeholder() -> Self { - UnusedLoopControlVariable("i".to_string()) - } } define_violation!( pub struct FunctionCallArgumentDefault(pub Option); ); impl Violation for FunctionCallArgumentDefault { + #[derive_message_formats] fn message(&self) -> String { let FunctionCallArgumentDefault(name) = self; if let Some(name) = name { format!("Do not perform function call `{name}` in argument defaults") } else { - "Do not perform function call in argument defaults".to_string() + format!("Do not perform function call in argument defaults") } } - - fn placeholder() -> Self { - FunctionCallArgumentDefault(None) - } } define_violation!( pub struct GetAttrWithConstant; ); impl AlwaysAutofixableViolation for GetAttrWithConstant { + #[derive_message_formats] fn message(&self) -> String { - "Do not call `getattr` with a constant attribute value. It is not any safer than normal \ - property access." - .to_string() + format!( + "Do not call `getattr` with a constant attribute value. It is not any safer than \ + normal property access." + ) } fn autofix_title(&self) -> String { "Replace `getattr` with attribute access".to_string() } - - fn placeholder() -> Self { - GetAttrWithConstant - } } define_violation!( pub struct SetAttrWithConstant; ); impl AlwaysAutofixableViolation for SetAttrWithConstant { + #[derive_message_formats] fn message(&self) -> String { - "Do not call `setattr` with a constant attribute value. It is not any safer than normal \ - property access." - .to_string() + format!( + "Do not call `setattr` with a constant attribute value. It is not any safer than \ + normal property access." + ) } fn autofix_title(&self) -> String { "Replace `setattr` with assignment".to_string() } - - fn placeholder() -> Self { - SetAttrWithConstant - } } define_violation!( pub struct DoNotAssertFalse; ); impl AlwaysAutofixableViolation for DoNotAssertFalse { + #[derive_message_formats] fn message(&self) -> String { - "Do not `assert False` (`python -O` removes these calls), raise `AssertionError()`" - .to_string() + format!("Do not `assert False` (`python -O` removes these calls), raise `AssertionError()`") } fn autofix_title(&self) -> String { "Replace `assert False`".to_string() } - - fn placeholder() -> Self { - DoNotAssertFalse - } } define_violation!( pub struct JumpStatementInFinally(pub String); ); impl Violation for JumpStatementInFinally { + #[derive_message_formats] fn message(&self) -> String { let JumpStatementInFinally(name) = self; format!("`{name}` inside finally blocks cause exceptions to be silenced") } - - fn placeholder() -> Self { - JumpStatementInFinally("return/continue/break".to_string()) - } } define_violation!( pub struct RedundantTupleInExceptionHandler(pub String); ); impl AlwaysAutofixableViolation for RedundantTupleInExceptionHandler { + #[derive_message_formats] fn message(&self) -> String { let RedundantTupleInExceptionHandler(name) = self; format!( @@ -1543,16 +1277,13 @@ impl AlwaysAutofixableViolation for RedundantTupleInExceptionHandler { let RedundantTupleInExceptionHandler(name) = self; format!("Replace with `except {name}`") } - - fn placeholder() -> Self { - RedundantTupleInExceptionHandler("ValueError".to_string()) - } } define_violation!( pub struct DuplicateHandlerException(pub Vec); ); impl AlwaysAutofixableViolation for DuplicateHandlerException { + #[derive_message_formats] fn message(&self) -> String { let DuplicateHandlerException(names) = self; if names.len() == 1 { @@ -1567,24 +1298,18 @@ impl AlwaysAutofixableViolation for DuplicateHandlerException { fn autofix_title(&self) -> String { "De-duplicate exceptions".to_string() } - - fn placeholder() -> Self { - DuplicateHandlerException(vec!["ValueError".to_string()]) - } } define_violation!( pub struct UselessComparison; ); impl Violation for UselessComparison { + #[derive_message_formats] fn message(&self) -> String { - "Pointless comparison. This comparison does nothing but waste CPU instructions. Either \ - prepend `assert` or remove it." - .to_string() - } - - fn placeholder() -> Self { - UselessComparison + format!( + "Pointless comparison. This comparison does nothing but waste CPU instructions. \ + Either prepend `assert` or remove it." + ) } } @@ -1592,12 +1317,9 @@ define_violation!( pub struct CannotRaiseLiteral; ); impl Violation for CannotRaiseLiteral { + #[derive_message_formats] fn message(&self) -> String { - "Cannot raise a literal. Did you intend to return it or raise an Exception?".to_string() - } - - fn placeholder() -> Self { - CannotRaiseLiteral + format!("Cannot raise a literal. Did you intend to return it or raise an Exception?") } } @@ -1605,25 +1327,19 @@ define_violation!( pub struct NoAssertRaisesException; ); impl Violation for NoAssertRaisesException { + #[derive_message_formats] fn message(&self) -> String { format!("`assertRaises(Exception)` should be considered evil") } - - fn placeholder() -> Self { - NoAssertRaisesException - } } define_violation!( pub struct UselessExpression; ); impl Violation for UselessExpression { + #[derive_message_formats] fn message(&self) -> String { - "Found useless expression. Either assign it to a variable or remove it.".to_string() - } - - fn placeholder() -> Self { - UselessExpression + format!("Found useless expression. Either assign it to a variable or remove it.") } } @@ -1631,13 +1347,11 @@ define_violation!( pub struct CachedInstanceMethod; ); impl Violation for CachedInstanceMethod { + #[derive_message_formats] fn message(&self) -> String { - "Use of `functools.lru_cache` or `functools.cache` on methods can lead to memory leaks" - .to_string() - } - - fn placeholder() -> Self { - CachedInstanceMethod + format!( + "Use of `functools.lru_cache` or `functools.cache` on methods can lead to memory leaks" + ) } } @@ -1645,28 +1359,23 @@ define_violation!( pub struct LoopVariableOverridesIterator(pub String); ); impl Violation for LoopVariableOverridesIterator { + #[derive_message_formats] fn message(&self) -> String { let LoopVariableOverridesIterator(name) = self; format!("Loop control variable `{name}` overrides iterable it iterates") } - - fn placeholder() -> Self { - LoopVariableOverridesIterator("...".to_string()) - } } define_violation!( pub struct FStringDocstring; ); impl Violation for FStringDocstring { + #[derive_message_formats] fn message(&self) -> String { - "f-string used as docstring. This will be interpreted by python as a joined string rather \ - than a docstring." - .to_string() - } - - fn placeholder() -> Self { - FStringDocstring + format!( + "f-string used as docstring. This will be interpreted by python as a joined string \ + rather than a docstring." + ) } } @@ -1674,14 +1383,12 @@ define_violation!( pub struct UselessContextlibSuppress; ); impl Violation for UselessContextlibSuppress { + #[derive_message_formats] fn message(&self) -> String { - "No arguments passed to `contextlib.suppress`. No exceptions will be suppressed and \ - therefore this context manager is redundant" - .to_string() - } - - fn placeholder() -> Self { - UselessContextlibSuppress + format!( + "No arguments passed to `contextlib.suppress`. No exceptions will be suppressed and \ + therefore this context manager is redundant" + ) } } @@ -1689,85 +1396,68 @@ define_violation!( pub struct FunctionUsesLoopVariable(pub String); ); impl Violation for FunctionUsesLoopVariable { + #[derive_message_formats] fn message(&self) -> String { let FunctionUsesLoopVariable(name) = self; format!("Function definition does not bind loop variable `{name}`") } - - fn placeholder() -> Self { - FunctionUsesLoopVariable("...".to_string()) - } } define_violation!( pub struct AbstractBaseClassWithoutAbstractMethod(pub String); ); impl Violation for AbstractBaseClassWithoutAbstractMethod { + #[derive_message_formats] fn message(&self) -> String { let AbstractBaseClassWithoutAbstractMethod(name) = self; format!("`{name}` is an abstract base class, but it has no abstract methods") } - - fn placeholder() -> Self { - AbstractBaseClassWithoutAbstractMethod("...".to_string()) - } } define_violation!( pub struct DuplicateTryBlockException(pub String); ); impl Violation for DuplicateTryBlockException { + #[derive_message_formats] fn message(&self) -> String { let DuplicateTryBlockException(name) = self; format!("try-except block with duplicate exception `{name}`") } - - fn placeholder() -> Self { - DuplicateTryBlockException("Exception".to_string()) - } } define_violation!( pub struct StarArgUnpackingAfterKeywordArg; ); impl Violation for StarArgUnpackingAfterKeywordArg { + #[derive_message_formats] fn message(&self) -> String { format!("Star-arg unpacking after a keyword argument is strongly discouraged") } - - fn placeholder() -> Self { - StarArgUnpackingAfterKeywordArg - } } define_violation!( pub struct EmptyMethodWithoutAbstractDecorator(pub String); ); impl Violation for EmptyMethodWithoutAbstractDecorator { + #[derive_message_formats] fn message(&self) -> String { let EmptyMethodWithoutAbstractDecorator(name) = self; format!( "`{name}` is an empty method in an abstract base class, but has no abstract decorator" ) } - - fn placeholder() -> Self { - EmptyMethodWithoutAbstractDecorator("...".to_string()) - } } define_violation!( pub struct RaiseWithoutFromInsideExcept; ); impl Violation for RaiseWithoutFromInsideExcept { + #[derive_message_formats] fn message(&self) -> String { - "Within an except clause, raise exceptions with `raise ... from err` or `raise ... from \ - None` to distinguish them from errors in exception handling" - .to_string() - } - - fn placeholder() -> Self { - RaiseWithoutFromInsideExcept + format!( + "Within an except clause, raise exceptions with `raise ... from err` or `raise ... \ + from None` to distinguish them from errors in exception handling" + ) } } @@ -1775,12 +1465,9 @@ define_violation!( pub struct ZipWithoutExplicitStrict; ); impl Violation for ZipWithoutExplicitStrict { + #[derive_message_formats] fn message(&self) -> String { - "`zip()` without an explicit `strict=` parameter".to_string() - } - - fn placeholder() -> Self { - ZipWithoutExplicitStrict + format!("`zip()` without an explicit `strict=` parameter") } } @@ -1790,14 +1477,11 @@ define_violation!( pub struct BlindExcept(pub String); ); impl Violation for BlindExcept { + #[derive_message_formats] fn message(&self) -> String { let BlindExcept(name) = self; format!("Do not catch blind exception: `{name}`") } - - fn placeholder() -> Self { - BlindExcept("Exception".to_string()) - } } // flake8-comprehensions @@ -1806,91 +1490,77 @@ define_violation!( pub struct UnnecessaryGeneratorList; ); impl AlwaysAutofixableViolation for UnnecessaryGeneratorList { + #[derive_message_formats] fn message(&self) -> String { - "Unnecessary generator (rewrite as a `list` comprehension)".to_string() + format!("Unnecessary generator (rewrite as a `list` comprehension)") } fn autofix_title(&self) -> String { "Rewrite as a `list` comprehension".to_string() } - - fn placeholder() -> Self { - UnnecessaryGeneratorList - } } define_violation!( pub struct UnnecessaryGeneratorSet; ); impl AlwaysAutofixableViolation for UnnecessaryGeneratorSet { + #[derive_message_formats] fn message(&self) -> String { - "Unnecessary generator (rewrite as a `set` comprehension)".to_string() + format!("Unnecessary generator (rewrite as a `set` comprehension)") } fn autofix_title(&self) -> String { "Rewrite as a `set` comprehension".to_string() } - - fn placeholder() -> Self { - UnnecessaryGeneratorSet - } } define_violation!( pub struct UnnecessaryGeneratorDict; ); impl AlwaysAutofixableViolation for UnnecessaryGeneratorDict { + #[derive_message_formats] fn message(&self) -> String { - "Unnecessary generator (rewrite as a `dict` comprehension)".to_string() + format!("Unnecessary generator (rewrite as a `dict` comprehension)") } fn autofix_title(&self) -> String { "Rewrite as a `dict` comprehension".to_string() } - - fn placeholder() -> Self { - UnnecessaryGeneratorDict - } } define_violation!( pub struct UnnecessaryListComprehensionSet; ); impl AlwaysAutofixableViolation for UnnecessaryListComprehensionSet { + #[derive_message_formats] fn message(&self) -> String { - "Unnecessary `list` comprehension (rewrite as a `set` comprehension)".to_string() + format!("Unnecessary `list` comprehension (rewrite as a `set` comprehension)") } fn autofix_title(&self) -> String { "Rewrite as a `set` comprehension".to_string() } - - fn placeholder() -> Self { - UnnecessaryListComprehensionSet - } } define_violation!( pub struct UnnecessaryListComprehensionDict; ); impl AlwaysAutofixableViolation for UnnecessaryListComprehensionDict { + #[derive_message_formats] fn message(&self) -> String { - "Unnecessary `list` comprehension (rewrite as a `dict` comprehension)".to_string() + format!("Unnecessary `list` comprehension (rewrite as a `dict` comprehension)") } fn autofix_title(&self) -> String { "Rewrite as a `dict` comprehension".to_string() } - - fn placeholder() -> Self { - UnnecessaryListComprehensionDict - } } define_violation!( pub struct UnnecessaryLiteralSet(pub String); ); impl AlwaysAutofixableViolation for UnnecessaryLiteralSet { + #[derive_message_formats] fn message(&self) -> String { let UnnecessaryLiteralSet(obj_type) = self; format!("Unnecessary `{obj_type}` literal (rewrite as a `set` literal)") @@ -1899,16 +1569,13 @@ impl AlwaysAutofixableViolation for UnnecessaryLiteralSet { fn autofix_title(&self) -> String { "Rewrite as a `set` literal".to_string() } - - fn placeholder() -> Self { - UnnecessaryLiteralSet("(list|tuple)".to_string()) - } } define_violation!( pub struct UnnecessaryLiteralDict(pub String); ); impl AlwaysAutofixableViolation for UnnecessaryLiteralDict { + #[derive_message_formats] fn message(&self) -> String { let UnnecessaryLiteralDict(obj_type) = self; format!("Unnecessary `{obj_type}` literal (rewrite as a `dict` literal)") @@ -1917,16 +1584,13 @@ impl AlwaysAutofixableViolation for UnnecessaryLiteralDict { fn autofix_title(&self) -> String { "Rewrite as a `dict` literal".to_string() } - - fn placeholder() -> Self { - UnnecessaryLiteralDict("(list|tuple)".to_string()) - } } define_violation!( pub struct UnnecessaryCollectionCall(pub String); ); impl AlwaysAutofixableViolation for UnnecessaryCollectionCall { + #[derive_message_formats] fn message(&self) -> String { let UnnecessaryCollectionCall(obj_type) = self; format!("Unnecessary `{obj_type}` call (rewrite as a literal)") @@ -1935,16 +1599,13 @@ impl AlwaysAutofixableViolation for UnnecessaryCollectionCall { fn autofix_title(&self) -> String { "Rewrite as a literal".to_string() } - - fn placeholder() -> Self { - UnnecessaryCollectionCall("(dict|list|tuple)".to_string()) - } } define_violation!( pub struct UnnecessaryLiteralWithinTupleCall(pub String); ); impl AlwaysAutofixableViolation for UnnecessaryLiteralWithinTupleCall { + #[derive_message_formats] fn message(&self) -> String { let UnnecessaryLiteralWithinTupleCall(literal) = self; if literal == "list" { @@ -1970,16 +1631,13 @@ impl AlwaysAutofixableViolation for UnnecessaryLiteralWithinTupleCall { } } } - - fn placeholder() -> Self { - UnnecessaryLiteralWithinTupleCall("(list|tuple)".to_string()) - } } define_violation!( pub struct UnnecessaryLiteralWithinListCall(pub String); ); impl AlwaysAutofixableViolation for UnnecessaryLiteralWithinListCall { + #[derive_message_formats] fn message(&self) -> String { let UnnecessaryLiteralWithinListCall(literal) = self; if literal == "list" { @@ -2004,33 +1662,27 @@ impl AlwaysAutofixableViolation for UnnecessaryLiteralWithinListCall { } } } - - fn placeholder() -> Self { - UnnecessaryLiteralWithinListCall("(list|tuple)".to_string()) - } } define_violation!( pub struct UnnecessaryListCall; ); impl AlwaysAutofixableViolation for UnnecessaryListCall { + #[derive_message_formats] fn message(&self) -> String { - "Unnecessary `list` call (remove the outer call to `list()`)".to_string() + format!("Unnecessary `list` call (remove the outer call to `list()`)") } fn autofix_title(&self) -> String { "Remove outer `list` call".to_string() } - - fn placeholder() -> Self { - UnnecessaryListCall - } } define_violation!( pub struct UnnecessaryCallAroundSorted(pub String); ); impl AlwaysAutofixableViolation for UnnecessaryCallAroundSorted { + #[derive_message_formats] fn message(&self) -> String { let UnnecessaryCallAroundSorted(func) = self; format!("Unnecessary `{func}` call around `sorted()`") @@ -2040,47 +1692,35 @@ impl AlwaysAutofixableViolation for UnnecessaryCallAroundSorted { let UnnecessaryCallAroundSorted(func) = self; format!("Remove unnecessary `{func}` call") } - - fn placeholder() -> Self { - UnnecessaryCallAroundSorted("(list|reversed)".to_string()) - } } define_violation!( pub struct UnnecessaryDoubleCastOrProcess(pub String, pub String); ); impl Violation for UnnecessaryDoubleCastOrProcess { + #[derive_message_formats] fn message(&self) -> String { let UnnecessaryDoubleCastOrProcess(inner, outer) = self; format!("Unnecessary `{inner}` call within `{outer}()`") } - - fn placeholder() -> Self { - UnnecessaryDoubleCastOrProcess( - "(list|reversed|set|sorted|tuple)".to_string(), - "(list|set|sorted|tuple)".to_string(), - ) - } } define_violation!( pub struct UnnecessarySubscriptReversal(pub String); ); impl Violation for UnnecessarySubscriptReversal { + #[derive_message_formats] fn message(&self) -> String { let UnnecessarySubscriptReversal(func) = self; format!("Unnecessary subscript reversal of iterable within `{func}()`") } - - fn placeholder() -> Self { - UnnecessarySubscriptReversal("(reversed|set|sorted)".to_string()) - } } define_violation!( pub struct UnnecessaryComprehension(pub String); ); impl AlwaysAutofixableViolation for UnnecessaryComprehension { + #[derive_message_formats] fn message(&self) -> String { let UnnecessaryComprehension(obj_type) = self; format!("Unnecessary `{obj_type}` comprehension (rewrite using `{obj_type}()`)") @@ -2090,28 +1730,21 @@ impl AlwaysAutofixableViolation for UnnecessaryComprehension { let UnnecessaryComprehension(obj_type) = self; format!("Rewrite using `{obj_type}()`") } - - fn placeholder() -> Self { - UnnecessaryComprehension("(list|set)".to_string()) - } } define_violation!( pub struct UnnecessaryMap(pub String); ); impl Violation for UnnecessaryMap { + #[derive_message_formats] fn message(&self) -> String { let UnnecessaryMap(obj_type) = self; if obj_type == "generator" { - "Unnecessary `map` usage (rewrite using a generator expression)".to_string() + format!("Unnecessary `map` usage (rewrite using a generator expression)") } else { format!("Unnecessary `map` usage (rewrite using a `{obj_type}` comprehension)") } } - - fn placeholder() -> Self { - UnnecessaryMap("(list|set|dict)".to_string()) - } } // flake8-debugger @@ -2120,6 +1753,7 @@ define_violation!( pub struct Debugger(pub DebuggerUsingType); ); impl Violation for Debugger { + #[derive_message_formats] fn message(&self) -> String { let Debugger(using_type) = self; match using_type { @@ -2127,10 +1761,6 @@ impl Violation for Debugger { DebuggerUsingType::Import(name) => format!("Import for `{name}` found"), } } - - fn placeholder() -> Self { - Debugger(DebuggerUsingType::Import("...".to_string())) - } } // mccabe @@ -2139,14 +1769,11 @@ define_violation!( pub struct FunctionIsTooComplex(pub String, pub usize); ); impl Violation for FunctionIsTooComplex { + #[derive_message_formats] fn message(&self) -> String { let FunctionIsTooComplex(name, complexity) = self; format!("`{name}` is too complex ({complexity})") } - - fn placeholder() -> Self { - FunctionIsTooComplex("...".to_string(), 10) - } } // flake8-return @@ -2155,65 +1782,53 @@ define_violation!( pub struct UnnecessaryReturnNone; ); impl AlwaysAutofixableViolation for UnnecessaryReturnNone { + #[derive_message_formats] fn message(&self) -> String { - "Do not explicitly `return None` in function if it is the only possible return value" - .to_string() + format!( + "Do not explicitly `return None` in function if it is the only possible return value" + ) } fn autofix_title(&self) -> String { "Remove explicit `return None`".to_string() } - - fn placeholder() -> Self { - UnnecessaryReturnNone - } } define_violation!( pub struct ImplicitReturnValue; ); impl AlwaysAutofixableViolation for ImplicitReturnValue { + #[derive_message_formats] fn message(&self) -> String { - "Do not implicitly `return None` in function able to return non-`None` value".to_string() + format!("Do not implicitly `return None` in function able to return non-`None` value") } fn autofix_title(&self) -> String { "Add explicit `None` return value".to_string() } - - fn placeholder() -> Self { - ImplicitReturnValue - } } define_violation!( pub struct ImplicitReturn; ); impl AlwaysAutofixableViolation for ImplicitReturn { + #[derive_message_formats] fn message(&self) -> String { - "Missing explicit `return` at the end of function able to return non-`None` value" - .to_string() + format!("Missing explicit `return` at the end of function able to return non-`None` value") } fn autofix_title(&self) -> String { "Add explicit `return` statement".to_string() } - - fn placeholder() -> Self { - ImplicitReturn - } } define_violation!( pub struct UnnecessaryAssign; ); impl Violation for UnnecessaryAssign { + #[derive_message_formats] fn message(&self) -> String { - "Unnecessary variable assignment before `return` statement".to_string() - } - - fn placeholder() -> Self { - UnnecessaryAssign + format!("Unnecessary variable assignment before `return` statement") } } @@ -2236,56 +1851,44 @@ define_violation!( pub struct SuperfluousElseReturn(pub Branch); ); impl Violation for SuperfluousElseReturn { + #[derive_message_formats] fn message(&self) -> String { let SuperfluousElseReturn(branch) = self; format!("Unnecessary `{branch}` after `return` statement") } - - fn placeholder() -> Self { - SuperfluousElseReturn(Branch::Else) - } } define_violation!( pub struct SuperfluousElseRaise(pub Branch); ); impl Violation for SuperfluousElseRaise { + #[derive_message_formats] fn message(&self) -> String { let SuperfluousElseRaise(branch) = self; format!("Unnecessary `{branch}` after `raise` statement") } - - fn placeholder() -> Self { - SuperfluousElseRaise(Branch::Else) - } } define_violation!( pub struct SuperfluousElseContinue(pub Branch); ); impl Violation for SuperfluousElseContinue { + #[derive_message_formats] fn message(&self) -> String { let SuperfluousElseContinue(branch) = self; format!("Unnecessary `{branch}` after `continue` statement") } - - fn placeholder() -> Self { - SuperfluousElseContinue(Branch::Else) - } } define_violation!( pub struct SuperfluousElseBreak(pub Branch); ); impl Violation for SuperfluousElseBreak { + #[derive_message_formats] fn message(&self) -> String { let SuperfluousElseBreak(branch) = self; format!("Unnecessary `{branch}` after `break` statement") } - - fn placeholder() -> Self { - SuperfluousElseBreak(Branch::Else) - } } // flake8-implicit-str-concat @@ -2294,12 +1897,9 @@ define_violation!( pub struct SingleLineImplicitStringConcatenation; ); impl Violation for SingleLineImplicitStringConcatenation { + #[derive_message_formats] fn message(&self) -> String { - "Implicitly concatenated string literals on one line".to_string() - } - - fn placeholder() -> Self { - SingleLineImplicitStringConcatenation + format!("Implicitly concatenated string literals on one line") } } @@ -2307,12 +1907,9 @@ define_violation!( pub struct MultiLineImplicitStringConcatenation; ); impl Violation for MultiLineImplicitStringConcatenation { + #[derive_message_formats] fn message(&self) -> String { - "Implicitly concatenated string literals over continuation line".to_string() - } - - fn placeholder() -> Self { - MultiLineImplicitStringConcatenation + format!("Implicitly concatenated string literals over continuation line") } } @@ -2320,12 +1917,9 @@ define_violation!( pub struct ExplicitStringConcatenation; ); impl Violation for ExplicitStringConcatenation { + #[derive_message_formats] fn message(&self) -> String { - "Explicitly concatenated string should be implicitly concatenated".to_string() - } - - fn placeholder() -> Self { - ExplicitStringConcatenation + format!("Explicitly concatenated string should be implicitly concatenated") } } @@ -2335,34 +1929,28 @@ define_violation!( pub struct PrintFound; ); impl AlwaysAutofixableViolation for PrintFound { + #[derive_message_formats] fn message(&self) -> String { - "`print` found".to_string() + format!("`print` found") } fn autofix_title(&self) -> String { "Remove `print`".to_string() } - - fn placeholder() -> Self { - PrintFound - } } define_violation!( pub struct PPrintFound; ); impl AlwaysAutofixableViolation for PPrintFound { + #[derive_message_formats] fn message(&self) -> String { - "`pprint` found".to_string() + format!("`pprint` found") } fn autofix_title(&self) -> String { "Remove `pprint`".to_string() } - - fn placeholder() -> Self { - PPrintFound - } } // flake8-quotes @@ -2371,11 +1959,12 @@ define_violation!( pub struct BadQuotesInlineString(pub Quote); ); impl AlwaysAutofixableViolation for BadQuotesInlineString { + #[derive_message_formats] fn message(&self) -> String { let BadQuotesInlineString(quote) = self; match quote { - Quote::Single => "Double quotes found but single quotes preferred".to_string(), - Quote::Double => "Single quotes found but double quotes preferred".to_string(), + Quote::Single => format!("Double quotes found but single quotes preferred"), + Quote::Double => format!("Single quotes found but double quotes preferred"), } } @@ -2386,21 +1975,18 @@ impl AlwaysAutofixableViolation for BadQuotesInlineString { Quote::Double => "Replace single quotes with double quotes".to_string(), } } - - fn placeholder() -> Self { - BadQuotesInlineString(Quote::Double) - } } define_violation!( pub struct BadQuotesMultilineString(pub Quote); ); impl AlwaysAutofixableViolation for BadQuotesMultilineString { + #[derive_message_formats] fn message(&self) -> String { let BadQuotesMultilineString(quote) = self; match quote { - Quote::Single => "Double quote multiline found but single quotes preferred".to_string(), - Quote::Double => "Single quote multiline found but double quotes preferred".to_string(), + Quote::Single => format!("Double quote multiline found but single quotes preferred"), + Quote::Double => format!("Single quote multiline found but double quotes preferred"), } } @@ -2411,21 +1997,18 @@ impl AlwaysAutofixableViolation for BadQuotesMultilineString { Quote::Double => "Replace single multiline quotes with double quotes".to_string(), } } - - fn placeholder() -> Self { - BadQuotesMultilineString(Quote::Double) - } } define_violation!( pub struct BadQuotesDocstring(pub Quote); ); impl AlwaysAutofixableViolation for BadQuotesDocstring { + #[derive_message_formats] fn message(&self) -> String { let BadQuotesDocstring(quote) = self; match quote { - Quote::Single => "Double quote docstring found but single quotes preferred".to_string(), - Quote::Double => "Single quote docstring found but double quotes preferred".to_string(), + Quote::Single => format!("Double quote docstring found but single quotes preferred"), + Quote::Double => format!("Single quote docstring found but double quotes preferred"), } } @@ -2436,27 +2019,20 @@ impl AlwaysAutofixableViolation for BadQuotesDocstring { Quote::Double => "Replace single quotes docstring with double quotes".to_string(), } } - - fn placeholder() -> Self { - BadQuotesDocstring(Quote::Double) - } } define_violation!( pub struct AvoidQuoteEscape; ); impl AlwaysAutofixableViolation for AvoidQuoteEscape { + #[derive_message_formats] fn message(&self) -> String { - "Change outer quotes to avoid escaping inner quotes".to_string() + format!("Change outer quotes to avoid escaping inner quotes") } fn autofix_title(&self) -> String { "Change outer quotes to avoid escaping inner quotes".to_string() } - - fn placeholder() -> Self { - AvoidQuoteEscape - } } // flake8-annotations @@ -2465,104 +2041,84 @@ define_violation!( pub struct MissingTypeFunctionArgument(pub String); ); impl Violation for MissingTypeFunctionArgument { + #[derive_message_formats] fn message(&self) -> String { let MissingTypeFunctionArgument(name) = self; format!("Missing type annotation for function argument `{name}`") } - - fn placeholder() -> Self { - MissingTypeFunctionArgument("...".to_string()) - } } define_violation!( pub struct MissingTypeArgs(pub String); ); impl Violation for MissingTypeArgs { + #[derive_message_formats] fn message(&self) -> String { let MissingTypeArgs(name) = self; format!("Missing type annotation for `*{name}`") } - - fn placeholder() -> Self { - MissingTypeArgs("...".to_string()) - } } define_violation!( pub struct MissingTypeKwargs(pub String); ); impl Violation for MissingTypeKwargs { + #[derive_message_formats] fn message(&self) -> String { let MissingTypeKwargs(name) = self; format!("Missing type annotation for `**{name}`") } - - fn placeholder() -> Self { - MissingTypeKwargs("...".to_string()) - } } define_violation!( pub struct MissingTypeSelf(pub String); ); impl Violation for MissingTypeSelf { + #[derive_message_formats] fn message(&self) -> String { let MissingTypeSelf(name) = self; format!("Missing type annotation for `{name}` in method") } - - fn placeholder() -> Self { - MissingTypeSelf("...".to_string()) - } } define_violation!( pub struct MissingTypeCls(pub String); ); impl Violation for MissingTypeCls { + #[derive_message_formats] fn message(&self) -> String { let MissingTypeCls(name) = self; format!("Missing type annotation for `{name}` in classmethod") } - - fn placeholder() -> Self { - MissingTypeCls("...".to_string()) - } } define_violation!( pub struct MissingReturnTypePublicFunction(pub String); ); impl Violation for MissingReturnTypePublicFunction { + #[derive_message_formats] fn message(&self) -> String { let MissingReturnTypePublicFunction(name) = self; format!("Missing return type annotation for public function `{name}`") } - - fn placeholder() -> Self { - MissingReturnTypePublicFunction("...".to_string()) - } } define_violation!( pub struct MissingReturnTypePrivateFunction(pub String); ); impl Violation for MissingReturnTypePrivateFunction { + #[derive_message_formats] fn message(&self) -> String { let MissingReturnTypePrivateFunction(name) = self; format!("Missing return type annotation for private function `{name}`") } - - fn placeholder() -> Self { - MissingReturnTypePrivateFunction("...".to_string()) - } } define_violation!( pub struct MissingReturnTypeSpecialMethod(pub String); ); impl AlwaysAutofixableViolation for MissingReturnTypeSpecialMethod { + #[derive_message_formats] fn message(&self) -> String { let MissingReturnTypeSpecialMethod(name) = self; format!("Missing return type annotation for special method `{name}`") @@ -2571,52 +2127,39 @@ impl AlwaysAutofixableViolation for MissingReturnTypeSpecialMethod { fn autofix_title(&self) -> String { "Add `None` return type".to_string() } - - fn placeholder() -> Self { - MissingReturnTypeSpecialMethod("...".to_string()) - } } define_violation!( pub struct MissingReturnTypeStaticMethod(pub String); ); impl Violation for MissingReturnTypeStaticMethod { + #[derive_message_formats] fn message(&self) -> String { let MissingReturnTypeStaticMethod(name) = self; format!("Missing return type annotation for staticmethod `{name}`") } - - fn placeholder() -> Self { - MissingReturnTypeStaticMethod("...".to_string()) - } } define_violation!( pub struct MissingReturnTypeClassMethod(pub String); ); impl Violation for MissingReturnTypeClassMethod { + #[derive_message_formats] fn message(&self) -> String { let MissingReturnTypeClassMethod(name) = self; format!("Missing return type annotation for classmethod `{name}`") } - - fn placeholder() -> Self { - MissingReturnTypeClassMethod("...".to_string()) - } } define_violation!( pub struct DynamicallyTypedExpression(pub String); ); impl Violation for DynamicallyTypedExpression { + #[derive_message_formats] fn message(&self) -> String { let DynamicallyTypedExpression(name) = self; format!("Dynamically typed expressions (typing.Any) are disallowed in `{name}`") } - - fn placeholder() -> Self { - DynamicallyTypedExpression("...".to_string()) - } } // flake8-2020 @@ -2625,12 +2168,9 @@ define_violation!( pub struct SysVersionSlice3Referenced; ); impl Violation for SysVersionSlice3Referenced { + #[derive_message_formats] fn message(&self) -> String { - "`sys.version[:3]` referenced (python3.10), use `sys.version_info`".to_string() - } - - fn placeholder() -> Self { - SysVersionSlice3Referenced + format!("`sys.version[:3]` referenced (python3.10), use `sys.version_info`") } } @@ -2638,12 +2178,9 @@ define_violation!( pub struct SysVersion2Referenced; ); impl Violation for SysVersion2Referenced { + #[derive_message_formats] fn message(&self) -> String { - "`sys.version[2]` referenced (python3.10), use `sys.version_info`".to_string() - } - - fn placeholder() -> Self { - SysVersion2Referenced + format!("`sys.version[2]` referenced (python3.10), use `sys.version_info`") } } @@ -2651,12 +2188,9 @@ define_violation!( pub struct SysVersionCmpStr3; ); impl Violation for SysVersionCmpStr3 { + #[derive_message_formats] fn message(&self) -> String { - "`sys.version` compared to string (python3.10), use `sys.version_info`".to_string() - } - - fn placeholder() -> Self { - SysVersionCmpStr3 + format!("`sys.version` compared to string (python3.10), use `sys.version_info`") } } @@ -2664,12 +2198,9 @@ define_violation!( pub struct SysVersionInfo0Eq3Referenced; ); impl Violation for SysVersionInfo0Eq3Referenced { + #[derive_message_formats] fn message(&self) -> String { - "`sys.version_info[0] == 3` referenced (python4), use `>=`".to_string() - } - - fn placeholder() -> Self { - SysVersionInfo0Eq3Referenced + format!("`sys.version_info[0] == 3` referenced (python4), use `>=`") } } @@ -2677,12 +2208,9 @@ define_violation!( pub struct SixPY3Referenced; ); impl Violation for SixPY3Referenced { + #[derive_message_formats] fn message(&self) -> String { - "`six.PY3` referenced (python4), use `not six.PY2`".to_string() - } - - fn placeholder() -> Self { - SixPY3Referenced + format!("`six.PY3` referenced (python4), use `not six.PY2`") } } @@ -2690,13 +2218,12 @@ define_violation!( pub struct SysVersionInfo1CmpInt; ); impl Violation for SysVersionInfo1CmpInt { + #[derive_message_formats] fn message(&self) -> String { - "`sys.version_info[1]` compared to integer (python4), compare `sys.version_info` to tuple" - .to_string() - } - - fn placeholder() -> Self { - SysVersionInfo1CmpInt + format!( + "`sys.version_info[1]` compared to integer (python4), compare `sys.version_info` to \ + tuple" + ) } } @@ -2704,14 +2231,12 @@ define_violation!( pub struct SysVersionInfoMinorCmpInt; ); impl Violation for SysVersionInfoMinorCmpInt { + #[derive_message_formats] fn message(&self) -> String { - "`sys.version_info.minor` compared to integer (python4), compare `sys.version_info` to \ - tuple" - .to_string() - } - - fn placeholder() -> Self { - SysVersionInfoMinorCmpInt + format!( + "`sys.version_info.minor` compared to integer (python4), compare `sys.version_info` \ + to tuple" + ) } } @@ -2719,12 +2244,9 @@ define_violation!( pub struct SysVersion0Referenced; ); impl Violation for SysVersion0Referenced { + #[derive_message_formats] fn message(&self) -> String { - "`sys.version[0]` referenced (python10), use `sys.version_info`".to_string() - } - - fn placeholder() -> Self { - SysVersion0Referenced + format!("`sys.version[0]` referenced (python10), use `sys.version_info`") } } @@ -2732,12 +2254,9 @@ define_violation!( pub struct SysVersionCmpStr10; ); impl Violation for SysVersionCmpStr10 { + #[derive_message_formats] fn message(&self) -> String { - "`sys.version` compared to string (python10), use `sys.version_info`".to_string() - } - - fn placeholder() -> Self { - SysVersionCmpStr10 + format!("`sys.version` compared to string (python10), use `sys.version_info`") } } @@ -2745,12 +2264,9 @@ define_violation!( pub struct SysVersionSlice1Referenced; ); impl Violation for SysVersionSlice1Referenced { + #[derive_message_formats] fn message(&self) -> String { - "`sys.version[:1]` referenced (python10), use `sys.version_info`".to_string() - } - - fn placeholder() -> Self { - SysVersionSlice1Referenced + format!("`sys.version[:1]` referenced (python10), use `sys.version_info`") } } @@ -2760,12 +2276,9 @@ define_violation!( pub struct OpenFileWithContextHandler; ); impl Violation for OpenFileWithContextHandler { + #[derive_message_formats] fn message(&self) -> String { - "Use context handler for opening files".to_string() - } - - fn placeholder() -> Self { - OpenFileWithContextHandler + format!("Use context handler for opening files") } } @@ -2773,6 +2286,7 @@ define_violation!( pub struct UseCapitalEnvironmentVariables(pub String, pub String); ); impl AlwaysAutofixableViolation for UseCapitalEnvironmentVariables { + #[derive_message_formats] fn message(&self) -> String { let UseCapitalEnvironmentVariables(expected, original) = self; format!("Use capitalized environment variable `{expected}` instead of `{original}`") @@ -2782,16 +2296,13 @@ impl AlwaysAutofixableViolation for UseCapitalEnvironmentVariables { let UseCapitalEnvironmentVariables(expected, original) = self; format!("Replace `{original}` with `{expected}`") } - - fn placeholder() -> Self { - UseCapitalEnvironmentVariables("...".to_string(), "...".to_string()) - } } define_violation!( pub struct DuplicateIsinstanceCall(pub String); ); impl AlwaysAutofixableViolation for DuplicateIsinstanceCall { + #[derive_message_formats] fn message(&self) -> String { let DuplicateIsinstanceCall(name) = self; format!("Multiple `isinstance` calls for `{name}`, merge into a single call") @@ -2801,33 +2312,27 @@ impl AlwaysAutofixableViolation for DuplicateIsinstanceCall { let DuplicateIsinstanceCall(name) = self; format!("Merge `isinstance` calls for `{name}`") } - - fn placeholder() -> Self { - DuplicateIsinstanceCall("...".to_string()) - } } define_violation!( pub struct NestedIfStatements; ); impl AlwaysAutofixableViolation for NestedIfStatements { + #[derive_message_formats] fn message(&self) -> String { - "Use a single `if` statement instead of nested `if` statements".to_string() + format!("Use a single `if` statement instead of nested `if` statements") } fn autofix_title(&self) -> String { "Combine `if` statements using `and`".to_string() } - - fn placeholder() -> Self { - NestedIfStatements - } } define_violation!( pub struct ReturnBoolConditionDirectly(pub String); ); impl AlwaysAutofixableViolation for ReturnBoolConditionDirectly { + #[derive_message_formats] fn message(&self) -> String { let ReturnBoolConditionDirectly(cond) = self; format!("Return the condition `{cond}` directly") @@ -2837,36 +2342,26 @@ impl AlwaysAutofixableViolation for ReturnBoolConditionDirectly { let ReturnBoolConditionDirectly(cond) = self; format!("Replace with `return {cond}`") } - - fn placeholder() -> Self { - ReturnBoolConditionDirectly("...".to_string()) - } } define_violation!( pub struct UseContextlibSuppress(pub String); ); impl Violation for UseContextlibSuppress { + #[derive_message_formats] fn message(&self) -> String { let UseContextlibSuppress(exception) = self; format!("Use `contextlib.suppress({exception})` instead of try-except-pass") } - - fn placeholder() -> Self { - UseContextlibSuppress("...".to_string()) - } } define_violation!( pub struct ReturnInTryExceptFinally; ); impl Violation for ReturnInTryExceptFinally { + #[derive_message_formats] fn message(&self) -> String { - "Don't use `return` in `try`/`except` and `finally`".to_string() - } - - fn placeholder() -> Self { - ReturnInTryExceptFinally + format!("Don't use `return` in `try`/`except` and `finally`") } } @@ -2874,6 +2369,7 @@ define_violation!( pub struct UseTernaryOperator(pub String); ); impl AlwaysAutofixableViolation for UseTernaryOperator { + #[derive_message_formats] fn message(&self) -> String { let UseTernaryOperator(contents) = self; format!("Use ternary operator `{contents}` instead of if-else-block") @@ -2883,10 +2379,6 @@ impl AlwaysAutofixableViolation for UseTernaryOperator { let UseTernaryOperator(contents) = self; format!("Replace if-else-block with `{contents}`") } - - fn placeholder() -> Self { - UseTernaryOperator("...".to_string()) - } } define_violation!( @@ -2895,6 +2387,7 @@ define_violation!( } ); impl AlwaysAutofixableViolation for CompareWithTuple { + #[derive_message_formats] fn message(&self) -> String { let CompareWithTuple { replacement } = self; format!("Use `{replacement}` instead of multiple equality comparisons") @@ -2904,18 +2397,13 @@ impl AlwaysAutofixableViolation for CompareWithTuple { let CompareWithTuple { replacement, .. } = self; format!("Replace with `{replacement}`") } - - fn placeholder() -> Self { - CompareWithTuple { - replacement: "value in (... ,...)".to_string(), - } - } } define_violation!( pub struct ConvertLoopToAny(pub String); ); impl AlwaysAutofixableViolation for ConvertLoopToAny { + #[derive_message_formats] fn message(&self) -> String { let ConvertLoopToAny(any) = self; format!("Use `{any}` instead of `for` loop") @@ -2925,16 +2413,13 @@ impl AlwaysAutofixableViolation for ConvertLoopToAny { let ConvertLoopToAny(any) = self; format!("Replace with `{any}`") } - - fn placeholder() -> Self { - ConvertLoopToAny("return any(x for x in y)".to_string()) - } } define_violation!( pub struct ConvertLoopToAll(pub String); ); impl AlwaysAutofixableViolation for ConvertLoopToAll { + #[derive_message_formats] fn message(&self) -> String { let ConvertLoopToAll(all) = self; format!("Use `{all}` instead of `for` loop") @@ -2944,34 +2429,30 @@ impl AlwaysAutofixableViolation for ConvertLoopToAll { let ConvertLoopToAll(all) = self; format!("Replace with `{all}`") } - - fn placeholder() -> Self { - ConvertLoopToAll("return all(x for x in y)".to_string()) - } } define_violation!( pub struct MultipleWithStatements; ); impl AlwaysAutofixableViolation for MultipleWithStatements { + #[derive_message_formats] fn message(&self) -> String { - "Use a single `with` statement with multiple contexts instead of nested `with` statements" - .to_string() + format!( + "Use a single `with` statement with multiple contexts instead of nested `with` \ + statements" + ) } fn autofix_title(&self) -> String { "Combine `with` statements".to_string() } - - fn placeholder() -> Self { - MultipleWithStatements - } } define_violation!( pub struct KeyInDict(pub String, pub String); ); impl AlwaysAutofixableViolation for KeyInDict { + #[derive_message_formats] fn message(&self) -> String { let KeyInDict(key, dict) = self; format!("Use `{key} in {dict}` instead of `{key} in {dict}.keys()`") @@ -2981,16 +2462,13 @@ impl AlwaysAutofixableViolation for KeyInDict { let KeyInDict(key, dict) = self; format!("Convert to `{key} in {dict}`") } - - fn placeholder() -> Self { - KeyInDict("key".to_string(), "dict".to_string()) - } } define_violation!( pub struct NegateEqualOp(pub String, pub String); ); impl AlwaysAutofixableViolation for NegateEqualOp { + #[derive_message_formats] fn message(&self) -> String { let NegateEqualOp(left, right) = self; format!("Use `{left} != {right}` instead of `not {left} == {right}`") @@ -2999,16 +2477,13 @@ impl AlwaysAutofixableViolation for NegateEqualOp { fn autofix_title(&self) -> String { "Replace with `!=` operator".to_string() } - - fn placeholder() -> Self { - NegateEqualOp("left".to_string(), "right".to_string()) - } } define_violation!( pub struct NegateNotEqualOp(pub String, pub String); ); impl AlwaysAutofixableViolation for NegateNotEqualOp { + #[derive_message_formats] fn message(&self) -> String { let NegateNotEqualOp(left, right) = self; format!("Use `{left} == {right}` instead of `not {left} != {right}`") @@ -3017,16 +2492,13 @@ impl AlwaysAutofixableViolation for NegateNotEqualOp { fn autofix_title(&self) -> String { "Replace with `==` operator".to_string() } - - fn placeholder() -> Self { - NegateNotEqualOp("left".to_string(), "right".to_string()) - } } define_violation!( pub struct DoubleNegation(pub String); ); impl AlwaysAutofixableViolation for DoubleNegation { + #[derive_message_formats] fn message(&self) -> String { let DoubleNegation(expr) = self; format!("Use `{expr}` instead of `not (not {expr})`") @@ -3036,16 +2508,13 @@ impl AlwaysAutofixableViolation for DoubleNegation { let DoubleNegation(expr) = self; format!("Replace with `{expr}`") } - - fn placeholder() -> Self { - DoubleNegation("expr".to_string()) - } } define_violation!( pub struct AAndNotA(pub String); ); impl AlwaysAutofixableViolation for AAndNotA { + #[derive_message_formats] fn message(&self) -> String { let AAndNotA(name) = self; format!("Use `False` instead of `{name} and not {name}`") @@ -3054,16 +2523,13 @@ impl AlwaysAutofixableViolation for AAndNotA { fn autofix_title(&self) -> String { "Replace with `False`".to_string() } - - fn placeholder() -> Self { - AAndNotA("...".to_string()) - } } define_violation!( pub struct AOrNotA(pub String); ); impl AlwaysAutofixableViolation for AOrNotA { + #[derive_message_formats] fn message(&self) -> String { let AOrNotA(name) = self; format!("Use `True` instead of `{name} or not {name}`") @@ -3072,44 +2538,34 @@ impl AlwaysAutofixableViolation for AOrNotA { fn autofix_title(&self) -> String { "Replace with `True`".to_string() } - - fn placeholder() -> Self { - AOrNotA("...".to_string()) - } } define_violation!( pub struct OrTrue; ); impl AlwaysAutofixableViolation for OrTrue { + #[derive_message_formats] fn message(&self) -> String { - "Use `True` instead of `... or True`".to_string() + format!("Use `True` instead of `... or True`") } fn autofix_title(&self) -> String { "Replace with `True`".to_string() } - - fn placeholder() -> Self { - OrTrue - } } define_violation!( pub struct AndFalse; ); impl AlwaysAutofixableViolation for AndFalse { + #[derive_message_formats] fn message(&self) -> String { - "Use `False` instead of `... and False`".to_string() + format!("Use `False` instead of `... and False`") } fn autofix_title(&self) -> String { "Replace with `False`".to_string() } - - fn placeholder() -> Self { - AndFalse - } } define_violation!( @@ -3118,6 +2574,7 @@ define_violation!( } ); impl AlwaysAutofixableViolation for YodaConditions { + #[derive_message_formats] fn message(&self) -> String { let YodaConditions { suggestion } = self; format!("Yoda conditions are discouraged, use `{suggestion}` instead") @@ -3127,18 +2584,13 @@ impl AlwaysAutofixableViolation for YodaConditions { let YodaConditions { suggestion } = self; format!("Replace Yoda condition with `{suggestion}`") } - - fn placeholder() -> Self { - YodaConditions { - suggestion: "x == 1".to_string(), - } - } } define_violation!( pub struct IfExprWithTrueFalse(pub String); ); impl AlwaysAutofixableViolation for IfExprWithTrueFalse { + #[derive_message_formats] fn message(&self) -> String { let IfExprWithTrueFalse(expr) = self; format!("Use `bool({expr})` instead of `True if {expr} else False`") @@ -3148,16 +2600,13 @@ impl AlwaysAutofixableViolation for IfExprWithTrueFalse { let IfExprWithTrueFalse(expr) = self; format!("Replace with `not {expr}") } - - fn placeholder() -> Self { - IfExprWithTrueFalse("expr".to_string()) - } } define_violation!( pub struct IfExprWithFalseTrue(pub String); ); impl AlwaysAutofixableViolation for IfExprWithFalseTrue { + #[derive_message_formats] fn message(&self) -> String { let IfExprWithFalseTrue(expr) = self; format!("Use `not {expr}` instead of `False if {expr} else True`") @@ -3167,16 +2616,13 @@ impl AlwaysAutofixableViolation for IfExprWithFalseTrue { let IfExprWithFalseTrue(expr) = self; format!("Replace with `bool({expr})") } - - fn placeholder() -> Self { - IfExprWithFalseTrue("expr".to_string()) - } } define_violation!( pub struct IfExprWithTwistedArms(pub String, pub String); ); impl AlwaysAutofixableViolation for IfExprWithTwistedArms { + #[derive_message_formats] fn message(&self) -> String { let IfExprWithTwistedArms(expr_body, expr_else) = self; format!( @@ -3189,16 +2635,13 @@ impl AlwaysAutofixableViolation for IfExprWithTwistedArms { let IfExprWithTwistedArms(expr_body, expr_else) = self; format!("Replace with `{expr_else} if {expr_else} else {expr_body}`") } - - fn placeholder() -> Self { - IfExprWithTwistedArms("a".to_string(), "b".to_string()) - } } define_violation!( pub struct DictGetWithDefault(pub String); ); impl AlwaysAutofixableViolation for DictGetWithDefault { + #[derive_message_formats] fn message(&self) -> String { let DictGetWithDefault(contents) = self; format!("Use `{contents}` instead of an `if` block") @@ -3208,10 +2651,6 @@ impl AlwaysAutofixableViolation for DictGetWithDefault { let DictGetWithDefault(contents) = self; format!("Replace with `{contents}`") } - - fn placeholder() -> Self { - DictGetWithDefault("var = dict.get(key, \"default\")".to_string()) - } } // pyupgrade @@ -3219,23 +2658,21 @@ define_violation!( pub struct UselessMetaclassType; ); impl AlwaysAutofixableViolation for UselessMetaclassType { + #[derive_message_formats] fn message(&self) -> String { - "`__metaclass__ = type` is implied".to_string() + format!("`__metaclass__ = type` is implied") } fn autofix_title(&self) -> String { "Remove `__metaclass__ = type`".to_string() } - - fn placeholder() -> Self { - UselessMetaclassType - } } define_violation!( pub struct TypeOfPrimitive(pub Primitive); ); impl AlwaysAutofixableViolation for TypeOfPrimitive { + #[derive_message_formats] fn message(&self) -> String { let TypeOfPrimitive(primitive) = self; format!("Use `{}` instead of `type(...)`", primitive.builtin()) @@ -3245,16 +2682,13 @@ impl AlwaysAutofixableViolation for TypeOfPrimitive { let TypeOfPrimitive(primitive) = self; format!("Replace `type(...)` with `{}`", primitive.builtin()) } - - fn placeholder() -> Self { - TypeOfPrimitive(Primitive::Str) - } } define_violation!( pub struct UselessObjectInheritance(pub String); ); impl AlwaysAutofixableViolation for UselessObjectInheritance { + #[derive_message_formats] fn message(&self) -> String { let UselessObjectInheritance(name) = self; format!("Class `{name}` inherits from `object`") @@ -3263,16 +2697,13 @@ impl AlwaysAutofixableViolation for UselessObjectInheritance { fn autofix_title(&self) -> String { "Remove `object` inheritance".to_string() } - - fn placeholder() -> Self { - UselessObjectInheritance("...".to_string()) - } } define_violation!( pub struct DeprecatedUnittestAlias(pub String, pub String); ); impl AlwaysAutofixableViolation for DeprecatedUnittestAlias { + #[derive_message_formats] fn message(&self) -> String { let DeprecatedUnittestAlias(alias, target) = self; format!("`{alias}` is deprecated, use `{target}`") @@ -3282,16 +2713,13 @@ impl AlwaysAutofixableViolation for DeprecatedUnittestAlias { let DeprecatedUnittestAlias(alias, target) = self; format!("Replace `{target}` with `{alias}`") } - - fn placeholder() -> Self { - DeprecatedUnittestAlias("assertEquals".to_string(), "assertEqual".to_string()) - } } define_violation!( pub struct UsePEP585Annotation(pub String); ); impl AlwaysAutofixableViolation for UsePEP585Annotation { + #[derive_message_formats] fn message(&self) -> String { let UsePEP585Annotation(name) = self; format!( @@ -3305,67 +2733,55 @@ impl AlwaysAutofixableViolation for UsePEP585Annotation { let UsePEP585Annotation(name) = self; format!("Replace `{name}` with `{}`", name.to_lowercase(),) } - - fn placeholder() -> Self { - UsePEP585Annotation("List".to_string()) - } } define_violation!( pub struct UsePEP604Annotation; ); impl AlwaysAutofixableViolation for UsePEP604Annotation { + #[derive_message_formats] fn message(&self) -> String { - "Use `X | Y` for type annotations".to_string() + format!("Use `X | Y` for type annotations") } fn autofix_title(&self) -> String { "Convert to `X | Y`".to_string() } - - fn placeholder() -> Self { - UsePEP604Annotation - } } define_violation!( pub struct SuperCallWithParameters; ); impl AlwaysAutofixableViolation for SuperCallWithParameters { + #[derive_message_formats] fn message(&self) -> String { - "Use `super()` instead of `super(__class__, self)`".to_string() + format!("Use `super()` instead of `super(__class__, self)`") } fn autofix_title(&self) -> String { "Remove `__super__` parameters".to_string() } - - fn placeholder() -> Self { - SuperCallWithParameters - } } define_violation!( pub struct PEP3120UnnecessaryCodingComment; ); impl AlwaysAutofixableViolation for PEP3120UnnecessaryCodingComment { + #[derive_message_formats] fn message(&self) -> String { - "UTF-8 encoding declaration is unnecessary".to_string() + format!("UTF-8 encoding declaration is unnecessary") } fn autofix_title(&self) -> String { "Remove unnecessary coding comment".to_string() } - - fn placeholder() -> Self { - PEP3120UnnecessaryCodingComment - } } define_violation!( pub struct UnnecessaryFutureImport(pub Vec); ); impl AlwaysAutofixableViolation for UnnecessaryFutureImport { + #[derive_message_formats] fn message(&self) -> String { let UnnecessaryFutureImport(names) = self; if names.len() == 1 { @@ -3380,50 +2796,41 @@ impl AlwaysAutofixableViolation for UnnecessaryFutureImport { fn autofix_title(&self) -> String { "Remove unnecessary `__future__` import".to_string() } - - fn placeholder() -> Self { - UnnecessaryFutureImport(vec!["...".to_string()]) - } } define_violation!( pub struct LRUCacheWithoutParameters; ); impl AlwaysAutofixableViolation for LRUCacheWithoutParameters { + #[derive_message_formats] fn message(&self) -> String { - "Unnecessary parameters to `functools.lru_cache`".to_string() + format!("Unnecessary parameters to `functools.lru_cache`") } fn autofix_title(&self) -> String { "Remove unnecessary parameters".to_string() } - - fn placeholder() -> Self { - LRUCacheWithoutParameters - } } define_violation!( pub struct UnnecessaryEncodeUTF8; ); impl AlwaysAutofixableViolation for UnnecessaryEncodeUTF8 { + #[derive_message_formats] fn message(&self) -> String { - "Unnecessary call to `encode` as UTF-8".to_string() + format!("Unnecessary call to `encode` as UTF-8") } fn autofix_title(&self) -> String { "Remove unnecessary `encode`".to_string() } - - fn placeholder() -> Self { - UnnecessaryEncodeUTF8 - } } define_violation!( pub struct ConvertTypedDictFunctionalToClass(pub String); ); impl AlwaysAutofixableViolation for ConvertTypedDictFunctionalToClass { + #[derive_message_formats] fn message(&self) -> String { let ConvertTypedDictFunctionalToClass(name) = self; format!("Convert `{name}` from `TypedDict` functional to class syntax") @@ -3433,16 +2840,13 @@ impl AlwaysAutofixableViolation for ConvertTypedDictFunctionalToClass { let ConvertTypedDictFunctionalToClass(name) = self; format!("Convert `{name}` to class syntax") } - - fn placeholder() -> Self { - ConvertTypedDictFunctionalToClass("...".to_string()) - } } define_violation!( pub struct ConvertNamedTupleFunctionalToClass(pub String); ); impl AlwaysAutofixableViolation for ConvertNamedTupleFunctionalToClass { + #[derive_message_formats] fn message(&self) -> String { let ConvertNamedTupleFunctionalToClass(name) = self; format!("Convert `{name}` from `NamedTuple` functional to class syntax") @@ -3452,20 +2856,17 @@ impl AlwaysAutofixableViolation for ConvertNamedTupleFunctionalToClass { let ConvertNamedTupleFunctionalToClass(name) = self; format!("Convert `{name}` to class syntax") } - - fn placeholder() -> Self { - ConvertNamedTupleFunctionalToClass("...".to_string()) - } } define_violation!( pub struct RedundantOpenModes(pub Option); ); impl AlwaysAutofixableViolation for RedundantOpenModes { + #[derive_message_formats] fn message(&self) -> String { let RedundantOpenModes(replacement) = self; match replacement { - None => "Unnecessary open mode parameters".to_string(), + None => format!("Unnecessary open mode parameters"), Some(replacement) => { format!("Unnecessary open mode parameters, use \"{replacement}\"") } @@ -3481,27 +2882,20 @@ impl AlwaysAutofixableViolation for RedundantOpenModes { } } } - - fn placeholder() -> Self { - RedundantOpenModes(None) - } } define_violation!( pub struct RemoveSixCompat; ); impl AlwaysAutofixableViolation for RemoveSixCompat { + #[derive_message_formats] fn message(&self) -> String { - "Unnecessary `six` compatibility usage".to_string() + format!("Unnecessary `six` compatibility usage") } fn autofix_title(&self) -> String { "Remove `six` usage".to_string() } - - fn placeholder() -> Self { - RemoveSixCompat - } } define_violation!( @@ -3512,8 +2906,9 @@ define_violation!( impl Violation for DatetimeTimezoneUTC { const AUTOFIX: Option = Some(AutofixKind::new(Availability::Always)); + #[derive_message_formats] fn message(&self) -> String { - "Use `datetime.UTC` alias".to_string() + format!("Use `datetime.UTC` alias") } fn autofix_title_formatter(&self) -> Option String> { @@ -3523,12 +2918,6 @@ impl Violation for DatetimeTimezoneUTC { None } } - - fn placeholder() -> Self { - DatetimeTimezoneUTC { - straight_import: true, - } - } } #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -3550,6 +2939,7 @@ define_violation!( pub struct NativeLiterals(pub LiteralType); ); impl AlwaysAutofixableViolation for NativeLiterals { + #[derive_message_formats] fn message(&self) -> String { let NativeLiterals(literal_type) = self; format!("Unnecessary call to `{literal_type}`") @@ -3559,103 +2949,85 @@ impl AlwaysAutofixableViolation for NativeLiterals { let NativeLiterals(literal_type) = self; format!("Replace with `{literal_type}`") } - - fn placeholder() -> Self { - NativeLiterals(LiteralType::Str) - } } define_violation!( pub struct TypingTextStrAlias; ); impl AlwaysAutofixableViolation for TypingTextStrAlias { + #[derive_message_formats] fn message(&self) -> String { - "`typing.Text` is deprecated, use `str`".to_string() + format!("`typing.Text` is deprecated, use `str`") } fn autofix_title(&self) -> String { "Replace with `str`".to_string() } - - fn placeholder() -> Self { - TypingTextStrAlias - } } define_violation!( pub struct OpenAlias; ); impl AlwaysAutofixableViolation for OpenAlias { + #[derive_message_formats] fn message(&self) -> String { - "Use builtin `open`".to_string() + format!("Use builtin `open`") } fn autofix_title(&self) -> String { "Replace with builtin `open`".to_string() } - - fn placeholder() -> Self { - OpenAlias - } } define_violation!( pub struct ReplaceUniversalNewlines; ); impl AlwaysAutofixableViolation for ReplaceUniversalNewlines { + #[derive_message_formats] fn message(&self) -> String { - "`universal_newlines` is deprecated, use `text`".to_string() + format!("`universal_newlines` is deprecated, use `text`") } fn autofix_title(&self) -> String { "Replace with `text` keyword argument".to_string() } - - fn placeholder() -> Self { - ReplaceUniversalNewlines - } } define_violation!( pub struct ReplaceStdoutStderr; ); impl AlwaysAutofixableViolation for ReplaceStdoutStderr { + #[derive_message_formats] fn message(&self) -> String { - "Sending stdout and stderr to pipe is deprecated, use `capture_output`".to_string() + format!("Sending stdout and stderr to pipe is deprecated, use `capture_output`") } fn autofix_title(&self) -> String { "Replace with `capture_output` keyword argument".to_string() } - - fn placeholder() -> Self { - ReplaceStdoutStderr - } } define_violation!( pub struct RewriteCElementTree; ); impl AlwaysAutofixableViolation for RewriteCElementTree { + #[derive_message_formats] fn message(&self) -> String { - "`cElementTree` is deprecated, use `ElementTree`".to_string() + format!("`cElementTree` is deprecated, use `ElementTree`") } fn autofix_title(&self) -> String { "Replace with `ElementTree`".to_string() } - - fn placeholder() -> Self { - RewriteCElementTree - } } define_violation!( pub struct OSErrorAlias(pub Option); ); impl AlwaysAutofixableViolation for OSErrorAlias { + #[derive_message_formats] fn message(&self) -> String { - "Replace aliased errors with `OSError`".to_string() + format!("Replace aliased errors with `OSError`") } fn autofix_title(&self) -> String { @@ -3665,27 +3037,20 @@ impl AlwaysAutofixableViolation for OSErrorAlias { Some(name) => format!("Replace `{name}` with builtin `OSError`"), } } - - fn placeholder() -> Self { - OSErrorAlias(None) - } } define_violation!( pub struct RewriteUnicodeLiteral; ); impl AlwaysAutofixableViolation for RewriteUnicodeLiteral { + #[derive_message_formats] fn message(&self) -> String { - "Remove unicode literals from strings".to_string() + format!("Remove unicode literals from strings") } fn autofix_title(&self) -> String { "Remove unicode prefix".to_string() } - - fn placeholder() -> Self { - RewriteUnicodeLiteral - } } #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -3698,8 +3063,9 @@ define_violation!( pub struct RewriteMockImport(pub MockReference); ); impl AlwaysAutofixableViolation for RewriteMockImport { + #[derive_message_formats] fn message(&self) -> String { - "`mock` is deprecated, use `unittest.mock`".to_string() + format!("`mock` is deprecated, use `unittest.mock`") } fn autofix_title(&self) -> String { @@ -3709,50 +3075,41 @@ impl AlwaysAutofixableViolation for RewriteMockImport { MockReference::Attribute => "Replace `mock.mock` with `mock`".to_string(), } } - - fn placeholder() -> Self { - RewriteMockImport(MockReference::Import) - } } define_violation!( pub struct RewriteListComprehension; ); impl AlwaysAutofixableViolation for RewriteListComprehension { + #[derive_message_formats] fn message(&self) -> String { - "Replace unpacked list comprehension with a generator expression".to_string() + format!("Replace unpacked list comprehension with a generator expression") } fn autofix_title(&self) -> String { "Replace with generator expression".to_string() } - - fn placeholder() -> Self { - RewriteListComprehension - } } define_violation!( pub struct RewriteYieldFrom; ); impl AlwaysAutofixableViolation for RewriteYieldFrom { + #[derive_message_formats] fn message(&self) -> String { - "Replace `yield` over `for` loop with `yield from`".to_string() + format!("Replace `yield` over `for` loop with `yield from`") } fn autofix_title(&self) -> String { "Replace with `yield from`".to_string() } - - fn placeholder() -> Self { - RewriteYieldFrom - } } define_violation!( pub struct UnnecessaryBuiltinImport(pub Vec); ); impl AlwaysAutofixableViolation for UnnecessaryBuiltinImport { + #[derive_message_formats] fn message(&self) -> String { let UnnecessaryBuiltinImport(names) = self; if names.len() == 1 { @@ -3767,61 +3124,48 @@ impl AlwaysAutofixableViolation for UnnecessaryBuiltinImport { fn autofix_title(&self) -> String { "Remove unnecessary builtin import".to_string() } - - fn placeholder() -> Self { - UnnecessaryBuiltinImport(vec!["...".to_string()]) - } } define_violation!( pub struct FormatLiterals; ); impl AlwaysAutofixableViolation for FormatLiterals { + #[derive_message_formats] fn message(&self) -> String { - "Use implicit references for positional format fields".to_string() + format!("Use implicit references for positional format fields") } fn autofix_title(&self) -> String { "Remove explicit positional indexes".to_string() } - - fn placeholder() -> Self { - FormatLiterals - } } define_violation!( pub struct FString; ); impl AlwaysAutofixableViolation for FString { + #[derive_message_formats] fn message(&self) -> String { - "Use f-string instead of `format` call".to_string() + format!("Use f-string instead of `format` call") } fn autofix_title(&self) -> String { "Convert to f-string".to_string() } - - fn placeholder() -> Self { - FString - } } define_violation!( pub struct FunctoolsCache; ); impl AlwaysAutofixableViolation for FunctoolsCache { + #[derive_message_formats] fn message(&self) -> String { - "Use `@functools.cache` instead of `@functools.lru_cache(maxsize=None)`".to_string() + format!("Use `@functools.cache` instead of `@functools.lru_cache(maxsize=None)`") } fn autofix_title(&self) -> String { "Rewrite with `@functools.cache".to_string() } - - fn placeholder() -> Self { - FunctoolsCache - } } // pydocstyle @@ -3830,12 +3174,9 @@ define_violation!( pub struct PublicModule; ); impl Violation for PublicModule { + #[derive_message_formats] fn message(&self) -> String { - "Missing docstring in public module".to_string() - } - - fn placeholder() -> Self { - PublicModule + format!("Missing docstring in public module") } } @@ -3843,12 +3184,9 @@ define_violation!( pub struct PublicClass; ); impl Violation for PublicClass { + #[derive_message_formats] fn message(&self) -> String { - "Missing docstring in public class".to_string() - } - - fn placeholder() -> Self { - PublicClass + format!("Missing docstring in public class") } } @@ -3856,12 +3194,9 @@ define_violation!( pub struct PublicMethod; ); impl Violation for PublicMethod { + #[derive_message_formats] fn message(&self) -> String { - "Missing docstring in public method".to_string() - } - - fn placeholder() -> Self { - PublicMethod + format!("Missing docstring in public method") } } @@ -3869,12 +3204,9 @@ define_violation!( pub struct PublicFunction; ); impl Violation for PublicFunction { + #[derive_message_formats] fn message(&self) -> String { - "Missing docstring in public function".to_string() - } - - fn placeholder() -> Self { - PublicFunction + format!("Missing docstring in public function") } } @@ -3882,12 +3214,9 @@ define_violation!( pub struct PublicPackage; ); impl Violation for PublicPackage { + #[derive_message_formats] fn message(&self) -> String { - "Missing docstring in public package".to_string() - } - - fn placeholder() -> Self { - PublicPackage + format!("Missing docstring in public package") } } @@ -3895,12 +3224,9 @@ define_violation!( pub struct MagicMethod; ); impl Violation for MagicMethod { + #[derive_message_formats] fn message(&self) -> String { - "Missing docstring in magic method".to_string() - } - - fn placeholder() -> Self { - MagicMethod + format!("Missing docstring in magic method") } } @@ -3908,12 +3234,9 @@ define_violation!( pub struct PublicNestedClass; ); impl Violation for PublicNestedClass { + #[derive_message_formats] fn message(&self) -> String { - "Missing docstring in public nested class".to_string() - } - - fn placeholder() -> Self { - PublicNestedClass + format!("Missing docstring in public nested class") } } @@ -3921,12 +3244,9 @@ define_violation!( pub struct PublicInit; ); impl Violation for PublicInit { + #[derive_message_formats] fn message(&self) -> String { - "Missing docstring in `__init__`".to_string() - } - - fn placeholder() -> Self { - PublicInit + format!("Missing docstring in `__init__`") } } @@ -3934,12 +3254,9 @@ define_violation!( pub struct FitsOnOneLine; ); impl Violation for FitsOnOneLine { + #[derive_message_formats] fn message(&self) -> String { - "One-line docstring should fit on one line".to_string() - } - - fn placeholder() -> Self { - FitsOnOneLine + format!("One-line docstring should fit on one line") } } @@ -3947,6 +3264,7 @@ define_violation!( pub struct NoBlankLineBeforeFunction(pub usize); ); impl AlwaysAutofixableViolation for NoBlankLineBeforeFunction { + #[derive_message_formats] fn message(&self) -> String { let NoBlankLineBeforeFunction(num_lines) = self; format!("No blank lines allowed before function docstring (found {num_lines})") @@ -3955,16 +3273,13 @@ impl AlwaysAutofixableViolation for NoBlankLineBeforeFunction { fn autofix_title(&self) -> String { "Remove blank line(s) before function docstring".to_string() } - - fn placeholder() -> Self { - NoBlankLineBeforeFunction(1) - } } define_violation!( pub struct NoBlankLineAfterFunction(pub usize); ); impl AlwaysAutofixableViolation for NoBlankLineAfterFunction { + #[derive_message_formats] fn message(&self) -> String { let NoBlankLineAfterFunction(num_lines) = self; format!("No blank lines allowed after function docstring (found {num_lines})") @@ -3973,44 +3288,34 @@ impl AlwaysAutofixableViolation for NoBlankLineAfterFunction { fn autofix_title(&self) -> String { "Remove blank line(s) after function docstring".to_string() } - - fn placeholder() -> Self { - NoBlankLineAfterFunction(1) - } } define_violation!( pub struct OneBlankLineBeforeClass(pub usize); ); impl AlwaysAutofixableViolation for OneBlankLineBeforeClass { + #[derive_message_formats] fn message(&self) -> String { - "1 blank line required before class docstring".to_string() + format!("1 blank line required before class docstring") } fn autofix_title(&self) -> String { "Insert 1 blank line before class docstring".to_string() } - - fn placeholder() -> Self { - OneBlankLineBeforeClass(0) - } } define_violation!( pub struct OneBlankLineAfterClass(pub usize); ); impl AlwaysAutofixableViolation for OneBlankLineAfterClass { + #[derive_message_formats] fn message(&self) -> String { - "1 blank line required after class docstring".to_string() + format!("1 blank line required after class docstring") } fn autofix_title(&self) -> String { "Insert 1 blank line after class docstring".to_string() } - - fn placeholder() -> Self { - OneBlankLineAfterClass(0) - } } define_violation!( @@ -4022,10 +3327,11 @@ fn fmt_blank_line_after_summary_autofix_msg(_: &BlankLineAfterSummary) -> String impl Violation for BlankLineAfterSummary { const AUTOFIX: Option = Some(AutofixKind::new(Availability::Always)); + #[derive_message_formats] fn message(&self) -> String { let BlankLineAfterSummary(num_lines) = self; if *num_lines == 0 { - "1 blank line required between summary line and description".to_string() + format!("1 blank line required between summary line and description") } else { format!( "1 blank line required between summary line and description (found {num_lines})" @@ -4040,22 +3346,15 @@ impl Violation for BlankLineAfterSummary { } None } - - fn placeholder() -> Self { - BlankLineAfterSummary(2) - } } define_violation!( pub struct IndentWithSpaces; ); impl Violation for IndentWithSpaces { + #[derive_message_formats] fn message(&self) -> String { - "Docstring should be indented with spaces, not tabs".to_string() - } - - fn placeholder() -> Self { - IndentWithSpaces + format!("Docstring should be indented with spaces, not tabs") } } @@ -4063,97 +3362,79 @@ define_violation!( pub struct NoUnderIndentation; ); impl AlwaysAutofixableViolation for NoUnderIndentation { + #[derive_message_formats] fn message(&self) -> String { - "Docstring is under-indented".to_string() + format!("Docstring is under-indented") } fn autofix_title(&self) -> String { "Increase indentation".to_string() } - - fn placeholder() -> Self { - NoUnderIndentation - } } define_violation!( pub struct NoOverIndentation; ); impl AlwaysAutofixableViolation for NoOverIndentation { + #[derive_message_formats] fn message(&self) -> String { - "Docstring is over-indented".to_string() + format!("Docstring is over-indented") } fn autofix_title(&self) -> String { "Remove over-indentation".to_string() } - - fn placeholder() -> Self { - NoOverIndentation - } } define_violation!( pub struct NewLineAfterLastParagraph; ); impl AlwaysAutofixableViolation for NewLineAfterLastParagraph { + #[derive_message_formats] fn message(&self) -> String { - "Multi-line docstring closing quotes should be on a separate line".to_string() + format!("Multi-line docstring closing quotes should be on a separate line") } fn autofix_title(&self) -> String { "Move closing quotes to new line".to_string() } - - fn placeholder() -> Self { - NewLineAfterLastParagraph - } } define_violation!( pub struct NoSurroundingWhitespace; ); impl AlwaysAutofixableViolation for NoSurroundingWhitespace { + #[derive_message_formats] fn message(&self) -> String { - "No whitespaces allowed surrounding docstring text".to_string() + format!("No whitespaces allowed surrounding docstring text") } fn autofix_title(&self) -> String { "Trim surrounding whitespace".to_string() } - - fn placeholder() -> Self { - NoSurroundingWhitespace - } } define_violation!( pub struct NoBlankLineBeforeClass(pub usize); ); impl AlwaysAutofixableViolation for NoBlankLineBeforeClass { + #[derive_message_formats] fn message(&self) -> String { - "No blank lines allowed before class docstring".to_string() + format!("No blank lines allowed before class docstring") } fn autofix_title(&self) -> String { "Remove blank line(s) before class docstring".to_string() } - - fn placeholder() -> Self { - NoBlankLineBeforeClass(1) - } } define_violation!( pub struct MultiLineSummaryFirstLine; ); impl Violation for MultiLineSummaryFirstLine { + #[derive_message_formats] fn message(&self) -> String { - "Multi-line docstring summary should start at the first line".to_string() - } - - fn placeholder() -> Self { - MultiLineSummaryFirstLine + format!("Multi-line docstring summary should start at the first line") } } @@ -4161,19 +3442,17 @@ define_violation!( pub struct MultiLineSummarySecondLine; ); impl Violation for MultiLineSummarySecondLine { + #[derive_message_formats] fn message(&self) -> String { - "Multi-line docstring summary should start at the second line".to_string() + format!("Multi-line docstring summary should start at the second line") } - - fn placeholder() -> Self { - MultiLineSummarySecondLine - } -} +} define_violation!( pub struct SectionNotOverIndented(pub String); ); impl AlwaysAutofixableViolation for SectionNotOverIndented { + #[derive_message_formats] fn message(&self) -> String { let SectionNotOverIndented(name) = self; format!("Section is over-indented (\"{name}\")") @@ -4183,16 +3462,13 @@ impl AlwaysAutofixableViolation for SectionNotOverIndented { let SectionNotOverIndented(name) = self; format!("Remove over-indentation from \"{name}\"") } - - fn placeholder() -> Self { - SectionNotOverIndented("Returns".to_string()) - } } define_violation!( pub struct SectionUnderlineNotOverIndented(pub String); ); impl AlwaysAutofixableViolation for SectionUnderlineNotOverIndented { + #[derive_message_formats] fn message(&self) -> String { let SectionUnderlineNotOverIndented(name) = self; format!("Section underline is over-indented (\"{name}\")") @@ -4202,22 +3478,15 @@ impl AlwaysAutofixableViolation for SectionUnderlineNotOverIndented { let SectionUnderlineNotOverIndented(name) = self; format!("Remove over-indentation from \"{name}\" underline") } - - fn placeholder() -> Self { - SectionUnderlineNotOverIndented("Returns".to_string()) - } } define_violation!( pub struct UsesTripleQuotes; ); impl Violation for UsesTripleQuotes { + #[derive_message_formats] fn message(&self) -> String { - r#"Use """triple double quotes""""#.to_string() - } - - fn placeholder() -> Self { - UsesTripleQuotes + format!(r#"Use """triple double quotes""""#) } } @@ -4225,12 +3494,9 @@ define_violation!( pub struct UsesRPrefixForBackslashedContent; ); impl Violation for UsesRPrefixForBackslashedContent { + #[derive_message_formats] fn message(&self) -> String { - r#"Use r""" if any backslashes in a docstring"#.to_string() - } - - fn placeholder() -> Self { - UsesRPrefixForBackslashedContent + format!(r#"Use r""" if any backslashes in a docstring"#) } } @@ -4238,29 +3504,23 @@ define_violation!( pub struct EndsInPeriod; ); impl AlwaysAutofixableViolation for EndsInPeriod { + #[derive_message_formats] fn message(&self) -> String { - "First line should end with a period".to_string() + format!("First line should end with a period") } fn autofix_title(&self) -> String { "Add period".to_string() } - - fn placeholder() -> Self { - EndsInPeriod - } } define_violation!( pub struct NoSignature; ); impl Violation for NoSignature { + #[derive_message_formats] fn message(&self) -> String { - "First line should not be the function's signature".to_string() - } - - fn placeholder() -> Self { - NoSignature + format!("First line should not be the function's signature") } } @@ -4268,12 +3528,9 @@ define_violation!( pub struct FirstLineCapitalized; ); impl Violation for FirstLineCapitalized { + #[derive_message_formats] fn message(&self) -> String { - "First word of the first line should be properly capitalized".to_string() - } - - fn placeholder() -> Self { - FirstLineCapitalized + format!("First word of the first line should be properly capitalized") } } @@ -4281,12 +3538,9 @@ define_violation!( pub struct NoThisPrefix; ); impl Violation for NoThisPrefix { + #[derive_message_formats] fn message(&self) -> String { - r#"First word of the docstring should not be "This""#.to_string() - } - - fn placeholder() -> Self { - NoThisPrefix + format!(r#"First word of the docstring should not be "This""#) } } @@ -4294,6 +3548,7 @@ define_violation!( pub struct CapitalizeSectionName(pub String); ); impl AlwaysAutofixableViolation for CapitalizeSectionName { + #[derive_message_formats] fn message(&self) -> String { let CapitalizeSectionName(name) = self; format!("Section name should be properly capitalized (\"{name}\")") @@ -4303,16 +3558,13 @@ impl AlwaysAutofixableViolation for CapitalizeSectionName { let CapitalizeSectionName(name) = self; format!("Capitalize \"{name}\"") } - - fn placeholder() -> Self { - CapitalizeSectionName("returns".to_string()) - } } define_violation!( pub struct NewLineAfterSectionName(pub String); ); impl AlwaysAutofixableViolation for NewLineAfterSectionName { + #[derive_message_formats] fn message(&self) -> String { let NewLineAfterSectionName(name) = self; format!("Section name should end with a newline (\"{name}\")") @@ -4322,16 +3574,13 @@ impl AlwaysAutofixableViolation for NewLineAfterSectionName { let NewLineAfterSectionName(name) = self; format!("Add newline after \"{name}\"") } - - fn placeholder() -> Self { - NewLineAfterSectionName("Returns".to_string()) - } } define_violation!( pub struct DashedUnderlineAfterSection(pub String); ); impl AlwaysAutofixableViolation for DashedUnderlineAfterSection { + #[derive_message_formats] fn message(&self) -> String { let DashedUnderlineAfterSection(name) = self; format!("Missing dashed underline after section (\"{name}\")") @@ -4341,16 +3590,13 @@ impl AlwaysAutofixableViolation for DashedUnderlineAfterSection { let DashedUnderlineAfterSection(name) = self; format!("Add dashed line under \"{name}\"") } - - fn placeholder() -> Self { - DashedUnderlineAfterSection("Returns".to_string()) - } } define_violation!( pub struct SectionUnderlineAfterName(pub String); ); impl AlwaysAutofixableViolation for SectionUnderlineAfterName { + #[derive_message_formats] fn message(&self) -> String { let SectionUnderlineAfterName(name) = self; format!("Section underline should be in the line following the section's name (\"{name}\")") @@ -4360,16 +3606,13 @@ impl AlwaysAutofixableViolation for SectionUnderlineAfterName { let SectionUnderlineAfterName(name) = self; format!("Add underline to \"{name}\"") } - - fn placeholder() -> Self { - SectionUnderlineAfterName("Returns".to_string()) - } } define_violation!( pub struct SectionUnderlineMatchesSectionLength(pub String); ); impl AlwaysAutofixableViolation for SectionUnderlineMatchesSectionLength { + #[derive_message_formats] fn message(&self) -> String { let SectionUnderlineMatchesSectionLength(name) = self; format!("Section underline should match the length of its name (\"{name}\")") @@ -4379,16 +3622,13 @@ impl AlwaysAutofixableViolation for SectionUnderlineMatchesSectionLength { let SectionUnderlineMatchesSectionLength(name) = self; format!("Adjust underline length to match \"{name}\"") } - - fn placeholder() -> Self { - SectionUnderlineMatchesSectionLength("Returns".to_string()) - } } define_violation!( pub struct BlankLineAfterSection(pub String); ); impl AlwaysAutofixableViolation for BlankLineAfterSection { + #[derive_message_formats] fn message(&self) -> String { let BlankLineAfterSection(name) = self; format!("Missing blank line after section (\"{name}\")") @@ -4398,16 +3638,13 @@ impl AlwaysAutofixableViolation for BlankLineAfterSection { let BlankLineAfterSection(name) = self; format!("Add blank line after \"{name}\"") } - - fn placeholder() -> Self { - BlankLineAfterSection("Returns".to_string()) - } } define_violation!( pub struct BlankLineBeforeSection(pub String); ); impl AlwaysAutofixableViolation for BlankLineBeforeSection { + #[derive_message_formats] fn message(&self) -> String { let BlankLineBeforeSection(name) = self; format!("Missing blank line before section (\"{name}\")") @@ -4417,16 +3654,13 @@ impl AlwaysAutofixableViolation for BlankLineBeforeSection { let BlankLineBeforeSection(name) = self; format!("Add blank line before \"{name}\"") } - - fn placeholder() -> Self { - BlankLineBeforeSection("Returns".to_string()) - } } define_violation!( pub struct NoBlankLinesBetweenHeaderAndContent(pub String); ); impl AlwaysAutofixableViolation for NoBlankLinesBetweenHeaderAndContent { + #[derive_message_formats] fn message(&self) -> String { let NoBlankLinesBetweenHeaderAndContent(name) = self; format!("No blank lines allowed between a section header and its content (\"{name}\")") @@ -4435,16 +3669,13 @@ impl AlwaysAutofixableViolation for NoBlankLinesBetweenHeaderAndContent { fn autofix_title(&self) -> String { "Remove blank line(s)".to_string() } - - fn placeholder() -> Self { - NoBlankLinesBetweenHeaderAndContent("Returns".to_string()) - } } define_violation!( pub struct BlankLineAfterLastSection(pub String); ); impl AlwaysAutofixableViolation for BlankLineAfterLastSection { + #[derive_message_formats] fn message(&self) -> String { let BlankLineAfterLastSection(name) = self; format!("Missing blank line after last section (\"{name}\")") @@ -4454,47 +3685,38 @@ impl AlwaysAutofixableViolation for BlankLineAfterLastSection { let BlankLineAfterLastSection(name) = self; format!("Add blank line after \"{name}\"") } - - fn placeholder() -> Self { - BlankLineAfterLastSection("Returns".to_string()) - } } define_violation!( pub struct NonEmptySection(pub String); ); impl Violation for NonEmptySection { + #[derive_message_formats] fn message(&self) -> String { let NonEmptySection(name) = self; format!("Section has no content (\"{name}\")") } - - fn placeholder() -> Self { - NonEmptySection("Returns".to_string()) - } } define_violation!( pub struct EndsInPunctuation; ); impl AlwaysAutofixableViolation for EndsInPunctuation { + #[derive_message_formats] fn message(&self) -> String { - "First line should end with a period, question mark, or exclamation point".to_string() + format!("First line should end with a period, question mark, or exclamation point") } fn autofix_title(&self) -> String { "Add closing punctuation".to_string() } - - fn placeholder() -> Self { - EndsInPunctuation - } } define_violation!( pub struct SectionNameEndsInColon(pub String); ); impl AlwaysAutofixableViolation for SectionNameEndsInColon { + #[derive_message_formats] fn message(&self) -> String { let SectionNameEndsInColon(name) = self; format!("Section name should end with a colon (\"{name}\")") @@ -4504,16 +3726,13 @@ impl AlwaysAutofixableViolation for SectionNameEndsInColon { let SectionNameEndsInColon(name) = self; format!("Add colon to \"{name}\"") } - - fn placeholder() -> Self { - SectionNameEndsInColon("Returns".to_string()) - } } define_violation!( pub struct DocumentAllArguments(pub Vec); ); impl Violation for DocumentAllArguments { + #[derive_message_formats] fn message(&self) -> String { let DocumentAllArguments(names) = self; if names.len() == 1 { @@ -4524,22 +3743,15 @@ impl Violation for DocumentAllArguments { format!("Missing argument descriptions in the docstring: {names}") } } - - fn placeholder() -> Self { - DocumentAllArguments(vec!["x".to_string(), "y".to_string()]) - } } define_violation!( pub struct SkipDocstring; ); impl Violation for SkipDocstring { + #[derive_message_formats] fn message(&self) -> String { - "Function decorated with `@overload` shouldn't contain a docstring".to_string() - } - - fn placeholder() -> Self { - SkipDocstring + format!("Function decorated with `@overload` shouldn't contain a docstring") } } @@ -4547,12 +3759,9 @@ define_violation!( pub struct NonEmpty; ); impl Violation for NonEmpty { + #[derive_message_formats] fn message(&self) -> String { - "Docstring is empty".to_string() - } - - fn placeholder() -> Self { - NonEmpty + format!("Docstring is empty") } } @@ -4562,54 +3771,42 @@ define_violation!( pub struct InvalidClassName(pub String); ); impl Violation for InvalidClassName { + #[derive_message_formats] fn message(&self) -> String { let InvalidClassName(name) = self; format!("Class name `{name}` should use CapWords convention ") } - - fn placeholder() -> Self { - InvalidClassName("...".to_string()) - } } define_violation!( pub struct InvalidFunctionName(pub String); ); impl Violation for InvalidFunctionName { + #[derive_message_formats] fn message(&self) -> String { let InvalidFunctionName(name) = self; format!("Function name `{name}` should be lowercase") } - - fn placeholder() -> Self { - InvalidFunctionName("...".to_string()) - } } define_violation!( pub struct InvalidArgumentName(pub String); ); impl Violation for InvalidArgumentName { + #[derive_message_formats] fn message(&self) -> String { let InvalidArgumentName(name) = self; format!("Argument name `{name}` should be lowercase") } - - fn placeholder() -> Self { - InvalidArgumentName("...".to_string()) - } } define_violation!( pub struct InvalidFirstArgumentNameForClassMethod; ); impl Violation for InvalidFirstArgumentNameForClassMethod { + #[derive_message_formats] fn message(&self) -> String { - "First argument of a class method should be named `cls`".to_string() - } - - fn placeholder() -> Self { - InvalidFirstArgumentNameForClassMethod + format!("First argument of a class method should be named `cls`") } } @@ -4617,12 +3814,9 @@ define_violation!( pub struct InvalidFirstArgumentNameForMethod; ); impl Violation for InvalidFirstArgumentNameForMethod { + #[derive_message_formats] fn message(&self) -> String { - "First argument of a method should be named `self`".to_string() - } - - fn placeholder() -> Self { - InvalidFirstArgumentNameForMethod + format!("First argument of a method should be named `self`") } } @@ -4630,26 +3824,20 @@ define_violation!( pub struct NonLowercaseVariableInFunction(pub String); ); impl Violation for NonLowercaseVariableInFunction { + #[derive_message_formats] fn message(&self) -> String { let NonLowercaseVariableInFunction(name) = self; format!("Variable `{name}` in function should be lowercase") } - - fn placeholder() -> Self { - NonLowercaseVariableInFunction("...".to_string()) - } } define_violation!( pub struct DunderFunctionName; ); impl Violation for DunderFunctionName { + #[derive_message_formats] fn message(&self) -> String { - "Function name should not start and end with `__`".to_string() - } - - fn placeholder() -> Self { - DunderFunctionName + format!("Function name should not start and end with `__`") } } @@ -4657,112 +3845,88 @@ define_violation!( pub struct ConstantImportedAsNonConstant(pub String, pub String); ); impl Violation for ConstantImportedAsNonConstant { + #[derive_message_formats] fn message(&self) -> String { let ConstantImportedAsNonConstant(name, asname) = self; format!("Constant `{name}` imported as non-constant `{asname}`") } - - fn placeholder() -> Self { - ConstantImportedAsNonConstant("...".to_string(), "...".to_string()) - } } define_violation!( pub struct LowercaseImportedAsNonLowercase(pub String, pub String); ); impl Violation for LowercaseImportedAsNonLowercase { + #[derive_message_formats] fn message(&self) -> String { let LowercaseImportedAsNonLowercase(name, asname) = self; format!("Lowercase `{name}` imported as non-lowercase `{asname}`") } - - fn placeholder() -> Self { - LowercaseImportedAsNonLowercase("...".to_string(), "...".to_string()) - } } define_violation!( pub struct CamelcaseImportedAsLowercase(pub String, pub String); ); impl Violation for CamelcaseImportedAsLowercase { + #[derive_message_formats] fn message(&self) -> String { let CamelcaseImportedAsLowercase(name, asname) = self; format!("Camelcase `{name}` imported as lowercase `{asname}`") } - - fn placeholder() -> Self { - CamelcaseImportedAsLowercase("...".to_string(), "...".to_string()) - } } define_violation!( pub struct CamelcaseImportedAsConstant(pub String, pub String); ); impl Violation for CamelcaseImportedAsConstant { + #[derive_message_formats] fn message(&self) -> String { let CamelcaseImportedAsConstant(name, asname) = self; format!("Camelcase `{name}` imported as constant `{asname}`") } - - fn placeholder() -> Self { - CamelcaseImportedAsConstant("...".to_string(), "...".to_string()) - } } define_violation!( pub struct MixedCaseVariableInClassScope(pub String); ); impl Violation for MixedCaseVariableInClassScope { + #[derive_message_formats] fn message(&self) -> String { let MixedCaseVariableInClassScope(name) = self; format!("Variable `{name}` in class scope should not be mixedCase") } - - fn placeholder() -> Self { - MixedCaseVariableInClassScope("mixedCase".to_string()) - } } define_violation!( pub struct MixedCaseVariableInGlobalScope(pub String); ); impl Violation for MixedCaseVariableInGlobalScope { + #[derive_message_formats] fn message(&self) -> String { let MixedCaseVariableInGlobalScope(name) = self; format!("Variable `{name}` in global scope should not be mixedCase") } - - fn placeholder() -> Self { - MixedCaseVariableInGlobalScope("mixedCase".to_string()) - } } define_violation!( pub struct CamelcaseImportedAsAcronym(pub String, pub String); ); impl Violation for CamelcaseImportedAsAcronym { + #[derive_message_formats] fn message(&self) -> String { let CamelcaseImportedAsAcronym(name, asname) = self; format!("Camelcase `{name}` imported as acronym `{asname}`") } - - fn placeholder() -> Self { - CamelcaseImportedAsAcronym("...".to_string(), "...".to_string()) - } } define_violation!( pub struct ErrorSuffixOnExceptionName(pub String); ); impl Violation for ErrorSuffixOnExceptionName { + #[derive_message_formats] fn message(&self) -> String { let ErrorSuffixOnExceptionName(name) = self; format!("Exception name `{name}` should be named with an Error suffix") } - - fn placeholder() -> Self { - ErrorSuffixOnExceptionName("...".to_string()) - } } // isort @@ -4771,23 +3935,21 @@ define_violation!( pub struct UnsortedImports; ); impl AlwaysAutofixableViolation for UnsortedImports { + #[derive_message_formats] fn message(&self) -> String { - "Import block is un-sorted or un-formatted".to_string() + format!("Import block is un-sorted or un-formatted") } fn autofix_title(&self) -> String { "Organize imports".to_string() } - - fn placeholder() -> Self { - UnsortedImports - } } define_violation!( pub struct MissingRequiredImport(pub String); ); impl AlwaysAutofixableViolation for MissingRequiredImport { + #[derive_message_formats] fn message(&self) -> String { let MissingRequiredImport(name) = self; format!("Missing required import: `{name}`") @@ -4797,10 +3959,6 @@ impl AlwaysAutofixableViolation for MissingRequiredImport { let MissingRequiredImport(name) = self; format!("Insert required import: `{name}`") } - - fn placeholder() -> Self { - MissingRequiredImport("from __future__ import ...".to_string()) - } } // eradicate @@ -4809,17 +3967,14 @@ define_violation!( pub struct CommentedOutCode; ); impl AlwaysAutofixableViolation for CommentedOutCode { + #[derive_message_formats] fn message(&self) -> String { - "Found commented-out code".to_string() + format!("Found commented-out code") } fn autofix_title(&self) -> String { "Remove commented-out code".to_string() } - - fn placeholder() -> Self { - CommentedOutCode - } } // flake8-bandit @@ -4828,34 +3983,30 @@ define_violation!( pub struct Jinja2AutoescapeFalse(pub bool); ); impl Violation for Jinja2AutoescapeFalse { + #[derive_message_formats] fn message(&self) -> String { let Jinja2AutoescapeFalse(value) = self; match value { - true => "Using jinja2 templates with `autoescape=False` is dangerous and can lead to \ - XSS. Ensure `autoescape=True` or use the `select_autoescape` function." - .to_string(), - false => "By default, jinja2 sets `autoescape` to `False`. Consider using \ - `autoescape=True` or the `select_autoescape` function to mitigate XSS \ - vulnerabilities." - .to_string(), + true => format!( + "Using jinja2 templates with `autoescape=False` is dangerous and can lead to XSS. \ + Ensure `autoescape=True` or use the `select_autoescape` function." + ), + false => format!( + "By default, jinja2 sets `autoescape` to `False`. Consider using \ + `autoescape=True` or the `select_autoescape` function to mitigate XSS \ + vulnerabilities." + ), } } - - fn placeholder() -> Self { - Jinja2AutoescapeFalse(false) - } } define_violation!( pub struct AssertUsed; ); impl Violation for AssertUsed { + #[derive_message_formats] fn message(&self) -> String { - "Use of `assert` detected".to_string() - } - - fn placeholder() -> Self { - AssertUsed + format!("Use of `assert` detected") } } @@ -4863,12 +4014,9 @@ define_violation!( pub struct ExecUsed; ); impl Violation for ExecUsed { + #[derive_message_formats] fn message(&self) -> String { - "Use of `exec` detected".to_string() - } - - fn placeholder() -> Self { - ExecUsed + format!("Use of `exec` detected") } } @@ -4876,26 +4024,20 @@ define_violation!( pub struct BadFilePermissions(pub u16); ); impl Violation for BadFilePermissions { + #[derive_message_formats] fn message(&self) -> String { let BadFilePermissions(mask) = self; format!("`os.chmod` setting a permissive mask `{mask:#o}` on file or directory",) } - - fn placeholder() -> Self { - BadFilePermissions(0o777) - } } define_violation!( pub struct HardcodedBindAllInterfaces; ); impl Violation for HardcodedBindAllInterfaces { + #[derive_message_formats] fn message(&self) -> String { - "Possible binding to all interfaces".to_string() - } - - fn placeholder() -> Self { - HardcodedBindAllInterfaces + format!("Possible binding to all interfaces") } } @@ -4903,48 +4045,40 @@ define_violation!( pub struct HardcodedPasswordString(pub String); ); impl Violation for HardcodedPasswordString { + #[derive_message_formats] fn message(&self) -> String { let HardcodedPasswordString(string) = self; format!("Possible hardcoded password: \"{}\"", string.escape_debug()) } - - fn placeholder() -> Self { - HardcodedPasswordString("...".to_string()) - } } define_violation!( pub struct HardcodedPasswordFuncArg(pub String); ); impl Violation for HardcodedPasswordFuncArg { + #[derive_message_formats] fn message(&self) -> String { let HardcodedPasswordFuncArg(string) = self; format!("Possible hardcoded password: \"{}\"", string.escape_debug()) } - - fn placeholder() -> Self { - HardcodedPasswordFuncArg("...".to_string()) - } } define_violation!( pub struct HardcodedPasswordDefault(pub String); ); impl Violation for HardcodedPasswordDefault { + #[derive_message_formats] fn message(&self) -> String { let HardcodedPasswordDefault(string) = self; format!("Possible hardcoded password: \"{}\"", string.escape_debug()) } - - fn placeholder() -> Self { - HardcodedPasswordDefault("...".to_string()) - } } define_violation!( pub struct HardcodedTempFile(pub String); ); impl Violation for HardcodedTempFile { + #[derive_message_formats] fn message(&self) -> String { let HardcodedTempFile(string) = self; format!( @@ -4952,35 +4086,29 @@ impl Violation for HardcodedTempFile { string.escape_debug() ) } - - fn placeholder() -> Self { - HardcodedTempFile("...".to_string()) - } } define_violation!( pub struct RequestWithoutTimeout(pub Option); ); impl Violation for RequestWithoutTimeout { + #[derive_message_formats] fn message(&self) -> String { let RequestWithoutTimeout(timeout) = self; match timeout { Some(value) => { format!("Probable use of requests call with timeout set to `{value}`") } - None => "Probable use of requests call without timeout".to_string(), + None => format!("Probable use of requests call without timeout"), } } - - fn placeholder() -> Self { - RequestWithoutTimeout(None) - } } define_violation!( pub struct HashlibInsecureHashFunction(pub String); ); impl Violation for HashlibInsecureHashFunction { + #[derive_message_formats] fn message(&self) -> String { let HashlibInsecureHashFunction(string) = self; format!( @@ -4988,32 +4116,26 @@ impl Violation for HashlibInsecureHashFunction { string.escape_debug() ) } - - fn placeholder() -> Self { - HashlibInsecureHashFunction("...".to_string()) - } } define_violation!( pub struct RequestWithNoCertValidation(pub String); ); impl Violation for RequestWithNoCertValidation { + #[derive_message_formats] fn message(&self) -> String { let RequestWithNoCertValidation(string) = self; format!( "Probable use of `{string}` call with `verify=False` disabling SSL certificate checks" ) } - - fn placeholder() -> Self { - RequestWithNoCertValidation("...".to_string()) - } } define_violation!( pub struct UnsafeYAMLLoad(pub Option); ); impl Violation for UnsafeYAMLLoad { + #[derive_message_formats] fn message(&self) -> String { let UnsafeYAMLLoad(loader) = self; match loader { @@ -5023,27 +4145,21 @@ impl Violation for UnsafeYAMLLoad { instantiation of arbitrary objects. Consider `yaml.safe_load`." ) } - None => "Probable use of unsafe `yaml.load`. Allows instantiation of arbitrary \ - objects. Consider `yaml.safe_load`." - .to_string(), + None => format!( + "Probable use of unsafe `yaml.load`. Allows instantiation of arbitrary objects. \ + Consider `yaml.safe_load`." + ), } } - - fn placeholder() -> Self { - UnsafeYAMLLoad(None) - } } define_violation!( pub struct SnmpInsecureVersion; ); impl Violation for SnmpInsecureVersion { + #[derive_message_formats] fn message(&self) -> String { - "The use of SNMPv1 and SNMPv2 is insecure. Use SNMPv3 if able.".to_string() - } - - fn placeholder() -> Self { - SnmpInsecureVersion + format!("The use of SNMPv1 and SNMPv2 is insecure. Use SNMPv3 if able.") } } @@ -5051,13 +4167,12 @@ define_violation!( pub struct SnmpWeakCryptography; ); impl Violation for SnmpWeakCryptography { + #[derive_message_formats] fn message(&self) -> String { - "You should not use SNMPv3 without encryption. `noAuthNoPriv` & `authNoPriv` is insecure." - .to_string() - } - - fn placeholder() -> Self { - SnmpWeakCryptography + format!( + "You should not use SNMPv3 without encryption. `noAuthNoPriv` & `authNoPriv` is \ + insecure." + ) } } @@ -5067,12 +4182,9 @@ define_violation!( pub struct BooleanPositionalArgInFunctionDefinition; ); impl Violation for BooleanPositionalArgInFunctionDefinition { + #[derive_message_formats] fn message(&self) -> String { - "Boolean positional arg in function definition".to_string() - } - - fn placeholder() -> Self { - BooleanPositionalArgInFunctionDefinition + format!("Boolean positional arg in function definition") } } @@ -5080,12 +4192,9 @@ define_violation!( pub struct BooleanDefaultValueInFunctionDefinition; ); impl Violation for BooleanDefaultValueInFunctionDefinition { + #[derive_message_formats] fn message(&self) -> String { - "Boolean default value in function definition".to_string() - } - - fn placeholder() -> Self { - BooleanDefaultValueInFunctionDefinition + format!("Boolean default value in function definition") } } @@ -5093,12 +4202,9 @@ define_violation!( pub struct BooleanPositionalValueInFunctionCall; ); impl Violation for BooleanPositionalValueInFunctionCall { + #[derive_message_formats] fn message(&self) -> String { - "Boolean positional value in function call".to_string() - } - - fn placeholder() -> Self { - BooleanPositionalValueInFunctionCall + format!("Boolean positional value in function call") } } @@ -5108,70 +4214,55 @@ define_violation!( pub struct UnusedFunctionArgument(pub String); ); impl Violation for UnusedFunctionArgument { + #[derive_message_formats] fn message(&self) -> String { let UnusedFunctionArgument(name) = self; format!("Unused function argument: `{name}`") } - - fn placeholder() -> Self { - UnusedFunctionArgument("...".to_string()) - } } define_violation!( pub struct UnusedMethodArgument(pub String); ); impl Violation for UnusedMethodArgument { + #[derive_message_formats] fn message(&self) -> String { let UnusedMethodArgument(name) = self; format!("Unused method argument: `{name}`") } - - fn placeholder() -> Self { - UnusedMethodArgument("...".to_string()) - } } define_violation!( pub struct UnusedClassMethodArgument(pub String); ); impl Violation for UnusedClassMethodArgument { + #[derive_message_formats] fn message(&self) -> String { let UnusedClassMethodArgument(name) = self; format!("Unused class method argument: `{name}`") } - - fn placeholder() -> Self { - UnusedClassMethodArgument("...".to_string()) - } } define_violation!( pub struct UnusedStaticMethodArgument(pub String); ); impl Violation for UnusedStaticMethodArgument { + #[derive_message_formats] fn message(&self) -> String { let UnusedStaticMethodArgument(name) = self; format!("Unused static method argument: `{name}`") } - - fn placeholder() -> Self { - UnusedStaticMethodArgument("...".to_string()) - } } define_violation!( pub struct UnusedLambdaArgument(pub String); ); impl Violation for UnusedLambdaArgument { + #[derive_message_formats] fn message(&self) -> String { let UnusedLambdaArgument(name) = self; format!("Unused lambda argument: `{name}`") } - - fn placeholder() -> Self { - UnusedLambdaArgument("...".to_string()) - } } // flake8-import-conventions @@ -5180,14 +4271,11 @@ define_violation!( pub struct ImportAliasIsNotConventional(pub String, pub String); ); impl Violation for ImportAliasIsNotConventional { + #[derive_message_formats] fn message(&self) -> String { let ImportAliasIsNotConventional(name, asname) = self; format!("`{name}` should be imported as `{asname}`") } - - fn placeholder() -> Self { - ImportAliasIsNotConventional("...".to_string(), "...".to_string()) - } } // flake8-datetimez @@ -5196,12 +4284,9 @@ define_violation!( pub struct CallDatetimeWithoutTzinfo; ); impl Violation for CallDatetimeWithoutTzinfo { + #[derive_message_formats] fn message(&self) -> String { - "The use of `datetime.datetime()` without `tzinfo` argument is not allowed".to_string() - } - - fn placeholder() -> Self { - CallDatetimeWithoutTzinfo + format!("The use of `datetime.datetime()` without `tzinfo` argument is not allowed") } } @@ -5209,51 +4294,39 @@ define_violation!( pub struct CallDatetimeToday; ); impl Violation for CallDatetimeToday { + #[derive_message_formats] fn message(&self) -> String { format!("The use of `datetime.datetime.today()` is not allowed") } - - fn placeholder() -> Self { - CallDatetimeToday - } } define_violation!( pub struct CallDatetimeUtcnow; ); impl Violation for CallDatetimeUtcnow { + #[derive_message_formats] fn message(&self) -> String { format!("The use of `datetime.datetime.utcnow()` is not allowed") } - - fn placeholder() -> Self { - CallDatetimeUtcnow - } } define_violation!( pub struct CallDatetimeUtcfromtimestamp; ); impl Violation for CallDatetimeUtcfromtimestamp { + #[derive_message_formats] fn message(&self) -> String { format!("The use of `datetime.datetime.utcfromtimestamp()` is not allowed") } - - fn placeholder() -> Self { - CallDatetimeUtcfromtimestamp - } } define_violation!( pub struct CallDatetimeNowWithoutTzinfo; ); impl Violation for CallDatetimeNowWithoutTzinfo { + #[derive_message_formats] fn message(&self) -> String { - "The use of `datetime.datetime.now()` without `tz` argument is not allowed".to_string() - } - - fn placeholder() -> Self { - CallDatetimeNowWithoutTzinfo + format!("The use of `datetime.datetime.now()` without `tz` argument is not allowed") } } @@ -5261,13 +4334,11 @@ define_violation!( pub struct CallDatetimeFromtimestamp; ); impl Violation for CallDatetimeFromtimestamp { + #[derive_message_formats] fn message(&self) -> String { - "The use of `datetime.datetime.fromtimestamp()` without `tz` argument is not allowed" - .to_string() - } - - fn placeholder() -> Self { - CallDatetimeFromtimestamp + format!( + "The use of `datetime.datetime.fromtimestamp()` without `tz` argument is not allowed" + ) } } @@ -5275,14 +4346,12 @@ define_violation!( pub struct CallDatetimeStrptimeWithoutZone; ); impl Violation for CallDatetimeStrptimeWithoutZone { + #[derive_message_formats] fn message(&self) -> String { - "The use of `datetime.datetime.strptime()` without %z must be followed by \ - `.replace(tzinfo=)`" - .to_string() - } - - fn placeholder() -> Self { - CallDatetimeStrptimeWithoutZone + format!( + "The use of `datetime.datetime.strptime()` without %z must be followed by \ + `.replace(tzinfo=)`" + ) } } @@ -5290,26 +4359,20 @@ define_violation!( pub struct CallDateToday; ); impl Violation for CallDateToday { + #[derive_message_formats] fn message(&self) -> String { format!("The use of `datetime.date.today()` is not allowed.") } - - fn placeholder() -> Self { - CallDateToday - } } define_violation!( pub struct CallDateFromtimestamp; ); impl Violation for CallDateFromtimestamp { + #[derive_message_formats] fn message(&self) -> String { format!("The use of `datetime.date.fromtimestamp()` is not allowed") } - - fn placeholder() -> Self { - CallDateFromtimestamp - } } // pygrep-hooks @@ -5318,12 +4381,9 @@ define_violation!( pub struct NoEval; ); impl Violation for NoEval { + #[derive_message_formats] fn message(&self) -> String { - "No builtin `eval()` allowed".to_string() - } - - fn placeholder() -> Self { - NoEval + format!("No builtin `eval()` allowed") } } @@ -5331,12 +4391,9 @@ define_violation!( pub struct DeprecatedLogWarn; ); impl Violation for DeprecatedLogWarn { + #[derive_message_formats] fn message(&self) -> String { - "`warn` is deprecated in favor of `warning`".to_string() - } - - fn placeholder() -> Self { - DeprecatedLogWarn + format!("`warn` is deprecated in favor of `warning`") } } @@ -5344,12 +4401,9 @@ define_violation!( pub struct BlanketTypeIgnore; ); impl Violation for BlanketTypeIgnore { + #[derive_message_formats] fn message(&self) -> String { - "Use specific rule codes when ignoring type issues".to_string() - } - - fn placeholder() -> Self { - BlanketTypeIgnore + format!("Use specific rule codes when ignoring type issues") } } @@ -5357,12 +4411,9 @@ define_violation!( pub struct BlanketNOQA; ); impl Violation for BlanketNOQA { + #[derive_message_formats] fn message(&self) -> String { - "Use specific rule codes when using `noqa`".to_string() - } - - fn placeholder() -> Self { - BlanketNOQA + format!("Use specific rule codes when using `noqa`") } } @@ -5372,12 +4423,9 @@ define_violation!( pub struct UseOfInplaceArgument; ); impl Violation for UseOfInplaceArgument { + #[derive_message_formats] fn message(&self) -> String { - "`inplace=True` should be avoided; it has inconsistent behavior".to_string() - } - - fn placeholder() -> Self { - UseOfInplaceArgument + format!("`inplace=True` should be avoided; it has inconsistent behavior") } } @@ -5385,12 +4433,9 @@ define_violation!( pub struct UseOfDotIsNull; ); impl Violation for UseOfDotIsNull { + #[derive_message_formats] fn message(&self) -> String { - "`.isna` is preferred to `.isnull`; functionality is equivalent".to_string() - } - - fn placeholder() -> Self { - UseOfDotIsNull + format!("`.isna` is preferred to `.isnull`; functionality is equivalent") } } @@ -5398,12 +4443,9 @@ define_violation!( pub struct UseOfDotNotNull; ); impl Violation for UseOfDotNotNull { + #[derive_message_formats] fn message(&self) -> String { - "`.notna` is preferred to `.notnull`; functionality is equivalent".to_string() - } - - fn placeholder() -> Self { - UseOfDotNotNull + format!("`.notna` is preferred to `.notnull`; functionality is equivalent") } } @@ -5411,12 +4453,9 @@ define_violation!( pub struct UseOfDotIx; ); impl Violation for UseOfDotIx { + #[derive_message_formats] fn message(&self) -> String { - "`.ix` is deprecated; use more explicit `.loc` or `.iloc`".to_string() - } - - fn placeholder() -> Self { - UseOfDotIx + format!("`.ix` is deprecated; use more explicit `.loc` or `.iloc`") } } @@ -5424,12 +4463,9 @@ define_violation!( pub struct UseOfDotAt; ); impl Violation for UseOfDotAt { + #[derive_message_formats] fn message(&self) -> String { - "Use `.loc` instead of `.at`. If speed is important, use numpy.".to_string() - } - - fn placeholder() -> Self { - UseOfDotAt + format!("Use `.loc` instead of `.at`. If speed is important, use numpy.") } } @@ -5437,12 +4473,9 @@ define_violation!( pub struct UseOfDotIat; ); impl Violation for UseOfDotIat { + #[derive_message_formats] fn message(&self) -> String { - "Use `.iloc` instead of `.iat`. If speed is important, use numpy.".to_string() - } - - fn placeholder() -> Self { - UseOfDotIat + format!("Use `.iloc` instead of `.iat`. If speed is important, use numpy.") } } @@ -5450,13 +4483,11 @@ define_violation!( pub struct UseOfDotPivotOrUnstack; ); impl Violation for UseOfDotPivotOrUnstack { + #[derive_message_formats] fn message(&self) -> String { - "`.pivot_table` is preferred to `.pivot` or `.unstack`; provides same functionality" - .to_string() - } - - fn placeholder() -> Self { - UseOfDotPivotOrUnstack + format!( + "`.pivot_table` is preferred to `.pivot` or `.unstack`; provides same functionality" + ) } } @@ -5464,12 +4495,9 @@ define_violation!( pub struct UseOfDotValues; ); impl Violation for UseOfDotValues { + #[derive_message_formats] fn message(&self) -> String { - "Use `.to_numpy()` instead of `.values`".to_string() - } - - fn placeholder() -> Self { - UseOfDotValues + format!("Use `.to_numpy()` instead of `.values`") } } @@ -5477,12 +4505,9 @@ define_violation!( pub struct UseOfDotReadTable; ); impl Violation for UseOfDotReadTable { + #[derive_message_formats] fn message(&self) -> String { - "`.read_csv` is preferred to `.read_table`; provides same functionality".to_string() - } - - fn placeholder() -> Self { - UseOfDotReadTable + format!("`.read_csv` is preferred to `.read_table`; provides same functionality") } } @@ -5490,12 +4515,9 @@ define_violation!( pub struct UseOfDotStack; ); impl Violation for UseOfDotStack { + #[derive_message_formats] fn message(&self) -> String { - "`.melt` is preferred to `.stack`; provides same functionality".to_string() - } - - fn placeholder() -> Self { - UseOfDotStack + format!("`.melt` is preferred to `.stack`; provides same functionality") } } @@ -5503,13 +4525,12 @@ define_violation!( pub struct UseOfPdMerge; ); impl Violation for UseOfPdMerge { + #[derive_message_formats] fn message(&self) -> String { - "Use `.merge` method instead of `pd.merge` function. They have equivalent functionality." - .to_string() - } - - fn placeholder() -> Self { - UseOfPdMerge + format!( + "Use `.merge` method instead of `pd.merge` function. They have equivalent \ + functionality." + ) } } @@ -5517,12 +4538,9 @@ define_violation!( pub struct DfIsABadVariableName; ); impl Violation for DfIsABadVariableName { + #[derive_message_formats] fn message(&self) -> String { - "`df` is a bad variable name. Be kinder to your future self.".to_string() - } - - fn placeholder() -> Self { - DfIsABadVariableName + format!("`df` is a bad variable name. Be kinder to your future self.") } } @@ -5532,12 +4550,9 @@ define_violation!( pub struct RawStringInException; ); impl Violation for RawStringInException { + #[derive_message_formats] fn message(&self) -> String { - "Exception must not use a string literal, assign to variable first".to_string() - } - - fn placeholder() -> Self { - RawStringInException + format!("Exception must not use a string literal, assign to variable first") } } @@ -5545,12 +4560,9 @@ define_violation!( pub struct FStringInException; ); impl Violation for FStringInException { + #[derive_message_formats] fn message(&self) -> String { - "Exception must not use an f-string literal, assign to variable first".to_string() - } - - fn placeholder() -> Self { - FStringInException + format!("Exception must not use an f-string literal, assign to variable first") } } @@ -5558,12 +4570,9 @@ define_violation!( pub struct DotFormatInException; ); impl Violation for DotFormatInException { + #[derive_message_formats] fn message(&self) -> String { - "Exception must not use a `.format()` string directly, assign to variable first".to_string() - } - - fn placeholder() -> Self { - DotFormatInException + format!("Exception must not use a `.format()` string directly, assign to variable first") } } @@ -5573,6 +4582,7 @@ define_violation!( pub struct IncorrectFixtureParenthesesStyle(pub String, pub String); ); impl AlwaysAutofixableViolation for IncorrectFixtureParenthesesStyle { + #[derive_message_formats] fn message(&self) -> String { let IncorrectFixtureParenthesesStyle(expected_parens, actual_parens) = self; format!("Use `@pytest.fixture{expected_parens}` over `@pytest.fixture{actual_parens}`") @@ -5581,36 +4591,26 @@ impl AlwaysAutofixableViolation for IncorrectFixtureParenthesesStyle { fn autofix_title(&self) -> String { "Add/remove parentheses".to_string() } - - fn placeholder() -> Self { - IncorrectFixtureParenthesesStyle("()".to_string(), String::new()) - } } define_violation!( pub struct FixturePositionalArgs(pub String); ); impl Violation for FixturePositionalArgs { + #[derive_message_formats] fn message(&self) -> String { let FixturePositionalArgs(function) = self; format!("Configuration for fixture `{function}` specified via positional args, use kwargs") } - - fn placeholder() -> Self { - FixturePositionalArgs("...".to_string()) - } } define_violation!( pub struct ExtraneousScopeFunction; ); impl Violation for ExtraneousScopeFunction { + #[derive_message_formats] fn message(&self) -> String { - "`scope='function'` is implied in `@pytest.fixture()`".to_string() - } - - fn placeholder() -> Self { - ExtraneousScopeFunction + format!("`scope='function'` is implied in `@pytest.fixture()`") } } @@ -5618,34 +4618,29 @@ define_violation!( pub struct MissingFixtureNameUnderscore(pub String); ); impl Violation for MissingFixtureNameUnderscore { + #[derive_message_formats] fn message(&self) -> String { let MissingFixtureNameUnderscore(function) = self; format!("Fixture `{function}` does not return anything, add leading underscore") } - - fn placeholder() -> Self { - MissingFixtureNameUnderscore("...".to_string()) - } } define_violation!( pub struct IncorrectFixtureNameUnderscore(pub String); ); impl Violation for IncorrectFixtureNameUnderscore { + #[derive_message_formats] fn message(&self) -> String { let IncorrectFixtureNameUnderscore(function) = self; format!("Fixture `{function}` returns a value, remove leading underscore") } - - fn placeholder() -> Self { - IncorrectFixtureNameUnderscore("...".to_string()) - } } define_violation!( pub struct ParametrizeNamesWrongType(pub ParametrizeNameType); ); impl AlwaysAutofixableViolation for ParametrizeNamesWrongType { + #[derive_message_formats] fn message(&self) -> String { let ParametrizeNamesWrongType(expected) = self; format!("Wrong name(s) type in `@pytest.mark.parametrize`, expected `{expected}`") @@ -5655,36 +4650,26 @@ impl AlwaysAutofixableViolation for ParametrizeNamesWrongType { let ParametrizeNamesWrongType(expected) = self; format!("Use a `{expected}` for parameter names") } - - fn placeholder() -> Self { - ParametrizeNamesWrongType(ParametrizeNameType::Tuple) - } } define_violation!( pub struct ParametrizeValuesWrongType(pub ParametrizeValuesType, pub ParametrizeValuesRowType); ); impl Violation for ParametrizeValuesWrongType { + #[derive_message_formats] fn message(&self) -> String { let ParametrizeValuesWrongType(values, row) = self; format!("Wrong values type in `@pytest.mark.parametrize` expected `{values}` of `{row}`") } - - fn placeholder() -> Self { - ParametrizeValuesWrongType(ParametrizeValuesType::List, ParametrizeValuesRowType::Tuple) - } } define_violation!( pub struct PatchWithLambda; ); impl Violation for PatchWithLambda { + #[derive_message_formats] fn message(&self) -> String { - "Use `return_value=` instead of patching with `lambda`".to_string() - } - - fn placeholder() -> Self { - PatchWithLambda + format!("Use `return_value=` instead of patching with `lambda`") } } @@ -5692,6 +4677,7 @@ define_violation!( pub struct UnittestAssertion(pub String); ); impl AlwaysAutofixableViolation for UnittestAssertion { + #[derive_message_formats] fn message(&self) -> String { let UnittestAssertion(assertion) = self; format!("Use a regular `assert` instead of unittest-style `{assertion}`") @@ -5701,22 +4687,15 @@ impl AlwaysAutofixableViolation for UnittestAssertion { let UnittestAssertion(assertion) = self; format!("Replace `{assertion}(...)` with `assert ...`") } - - fn placeholder() -> Self { - UnittestAssertion("...".to_string()) - } } define_violation!( pub struct RaisesWithoutException; ); impl Violation for RaisesWithoutException { + #[derive_message_formats] fn message(&self) -> String { - "set the expected exception in `pytest.raises()`".to_string() - } - - fn placeholder() -> Self { - RaisesWithoutException + format!("set the expected exception in `pytest.raises()`") } } @@ -5724,6 +4703,7 @@ define_violation!( pub struct RaisesTooBroad(pub String); ); impl Violation for RaisesTooBroad { + #[derive_message_formats] fn message(&self) -> String { let RaisesTooBroad(exception) = self; format!( @@ -5731,22 +4711,15 @@ impl Violation for RaisesTooBroad { specific exception" ) } - - fn placeholder() -> Self { - RaisesTooBroad("...".to_string()) - } } define_violation!( pub struct RaisesWithMultipleStatements; ); impl Violation for RaisesWithMultipleStatements { + #[derive_message_formats] fn message(&self) -> String { - "`pytest.raises()` block should contain a single simple statement".to_string() - } - - fn placeholder() -> Self { - RaisesWithMultipleStatements + format!("`pytest.raises()` block should contain a single simple statement") } } @@ -5754,12 +4727,9 @@ define_violation!( pub struct IncorrectPytestImport; ); impl Violation for IncorrectPytestImport { + #[derive_message_formats] fn message(&self) -> String { - "Found incorrect import of pytest, use simple `import pytest` instead".to_string() - } - - fn placeholder() -> Self { - IncorrectPytestImport + format!("Found incorrect import of pytest, use simple `import pytest` instead") } } @@ -5767,12 +4737,9 @@ define_violation!( pub struct AssertAlwaysFalse; ); impl Violation for AssertAlwaysFalse { + #[derive_message_formats] fn message(&self) -> String { - "Assertion always fails, replace with `pytest.fail()`".to_string() - } - - fn placeholder() -> Self { - AssertAlwaysFalse + format!("Assertion always fails, replace with `pytest.fail()`") } } @@ -5780,12 +4747,9 @@ define_violation!( pub struct FailWithoutMessage; ); impl Violation for FailWithoutMessage { + #[derive_message_formats] fn message(&self) -> String { - "No message passed to `pytest.fail()`".to_string() - } - - fn placeholder() -> Self { - FailWithoutMessage + format!("No message passed to `pytest.fail()`") } } @@ -5793,28 +4757,22 @@ define_violation!( pub struct AssertInExcept(pub String); ); impl Violation for AssertInExcept { + #[derive_message_formats] fn message(&self) -> String { let AssertInExcept(name) = self; format!( "Found assertion on exception `{name}` in except block, use `pytest.raises()` instead" ) } - - fn placeholder() -> Self { - AssertInExcept("...".to_string()) - } } define_violation!( pub struct CompositeAssertion; ); impl Violation for CompositeAssertion { + #[derive_message_formats] fn message(&self) -> String { - "Assertion should be broken down into multiple parts".to_string() - } - - fn placeholder() -> Self { - CompositeAssertion + format!("Assertion should be broken down into multiple parts") } } @@ -5822,6 +4780,7 @@ define_violation!( pub struct FixtureParamWithoutValue(pub String); ); impl Violation for FixtureParamWithoutValue { + #[derive_message_formats] fn message(&self) -> String { let FixtureParamWithoutValue(name) = self; format!( @@ -5829,22 +4788,15 @@ impl Violation for FixtureParamWithoutValue { `@pytest.mark.usefixtures` instead" ) } - - fn placeholder() -> Self { - FixtureParamWithoutValue("...".to_string()) - } } define_violation!( pub struct DeprecatedYieldFixture; ); impl Violation for DeprecatedYieldFixture { + #[derive_message_formats] fn message(&self) -> String { - "`@pytest.yield_fixture` is deprecated, use `@pytest.fixture`".to_string() - } - - fn placeholder() -> Self { - DeprecatedYieldFixture + format!("`@pytest.yield_fixture` is deprecated, use `@pytest.fixture`") } } @@ -5852,12 +4804,9 @@ define_violation!( pub struct FixtureFinalizerCallback; ); impl Violation for FixtureFinalizerCallback { + #[derive_message_formats] fn message(&self) -> String { - "Use `yield` instead of `request.addfinalizer`".to_string() - } - - fn placeholder() -> Self { - FixtureFinalizerCallback + format!("Use `yield` instead of `request.addfinalizer`") } } @@ -5865,6 +4814,7 @@ define_violation!( pub struct UselessYieldFixture(pub String); ); impl AlwaysAutofixableViolation for UselessYieldFixture { + #[derive_message_formats] fn message(&self) -> String { let UselessYieldFixture(name) = self; format!("No teardown in fixture `{name}`, use `return` instead of `yield`") @@ -5873,16 +4823,13 @@ impl AlwaysAutofixableViolation for UselessYieldFixture { fn autofix_title(&self) -> String { "Replace `yield` with `return`".to_string() } - - fn placeholder() -> Self { - UselessYieldFixture("...".to_string()) - } } define_violation!( pub struct IncorrectMarkParenthesesStyle(pub String, pub String, pub String); ); impl AlwaysAutofixableViolation for IncorrectMarkParenthesesStyle { + #[derive_message_formats] fn message(&self) -> String { let IncorrectMarkParenthesesStyle(mark_name, expected_parens, actual_parens) = self; format!( @@ -5894,61 +4841,48 @@ impl AlwaysAutofixableViolation for IncorrectMarkParenthesesStyle { fn autofix_title(&self) -> String { "Add/remove parentheses".to_string() } - - fn placeholder() -> Self { - IncorrectMarkParenthesesStyle("...".to_string(), String::new(), "()".to_string()) - } } define_violation!( pub struct UnnecessaryAsyncioMarkOnFixture; ); impl AlwaysAutofixableViolation for UnnecessaryAsyncioMarkOnFixture { + #[derive_message_formats] fn message(&self) -> String { - "`pytest.mark.asyncio` is unnecessary for fixtures".to_string() + format!("`pytest.mark.asyncio` is unnecessary for fixtures") } fn autofix_title(&self) -> String { "Remove `pytest.mark.asyncio`".to_string() } - - fn placeholder() -> Self { - UnnecessaryAsyncioMarkOnFixture - } } define_violation!( pub struct ErroneousUseFixturesOnFixture; ); impl AlwaysAutofixableViolation for ErroneousUseFixturesOnFixture { + #[derive_message_formats] fn message(&self) -> String { - "`pytest.mark.usefixtures` has no effect on fixtures".to_string() + format!("`pytest.mark.usefixtures` has no effect on fixtures") } fn autofix_title(&self) -> String { "Remove `pytest.mark.usefixtures`".to_string() } - - fn placeholder() -> Self { - ErroneousUseFixturesOnFixture - } } define_violation!( pub struct UseFixturesWithoutParameters; ); impl AlwaysAutofixableViolation for UseFixturesWithoutParameters { + #[derive_message_formats] fn message(&self) -> String { - "Useless `pytest.mark.usefixtures` without parameters".to_string() + format!("Useless `pytest.mark.usefixtures` without parameters") } fn autofix_title(&self) -> String { "Remove `usefixtures` decorator or pass parameters".to_string() } - - fn placeholder() -> Self { - UseFixturesWithoutParameters - } } // flake8-pie @@ -5957,23 +4891,21 @@ define_violation!( pub struct NoUnnecessaryPass; ); impl AlwaysAutofixableViolation for NoUnnecessaryPass { + #[derive_message_formats] fn message(&self) -> String { - "Unnecessary `pass` statement".to_string() + format!("Unnecessary `pass` statement") } fn autofix_title(&self) -> String { "Remove unnecessary `pass`".to_string() } - - fn placeholder() -> Self { - NoUnnecessaryPass - } } define_violation!( pub struct DupeClassFieldDefinitions(pub String); ); impl AlwaysAutofixableViolation for DupeClassFieldDefinitions { + #[derive_message_formats] fn message(&self) -> String { let DupeClassFieldDefinitions(name) = self; format!("Class field `{name}` is defined multiple times") @@ -5983,10 +4915,6 @@ impl AlwaysAutofixableViolation for DupeClassFieldDefinitions { let DupeClassFieldDefinitions(name) = self; format!("Remove duplicate field definition for `{name}`") } - - fn placeholder() -> Self { - DupeClassFieldDefinitions("...".to_string()) - } } define_violation!( @@ -5995,33 +4923,25 @@ define_violation!( } ); impl Violation for PreferUniqueEnums { + #[derive_message_formats] fn message(&self) -> String { let PreferUniqueEnums { value } = self; format!("Enum contains duplicate value: `{value}`") } - - fn placeholder() -> Self { - PreferUniqueEnums { - value: "...".to_string(), - } - } } define_violation!( pub struct PreferListBuiltin; ); impl AlwaysAutofixableViolation for PreferListBuiltin { + #[derive_message_formats] fn message(&self) -> String { - "Prefer `list()` over useless lambda".to_string() + format!("Prefer `list()` over useless lambda") } fn autofix_title(&self) -> String { "Replace with `list`".to_string() } - - fn placeholder() -> Self { - PreferListBuiltin - } } // flake8-commas @@ -6030,29 +4950,23 @@ define_violation!( pub struct TrailingCommaMissing; ); impl AlwaysAutofixableViolation for TrailingCommaMissing { + #[derive_message_formats] fn message(&self) -> String { - "Trailing comma missing".to_string() + format!("Trailing comma missing") } fn autofix_title(&self) -> String { "Add trailing comma".to_string() } - - fn placeholder() -> Self { - TrailingCommaMissing - } } define_violation!( pub struct TrailingCommaOnBareTupleProhibited; ); impl Violation for TrailingCommaOnBareTupleProhibited { + #[derive_message_formats] fn message(&self) -> String { - "Trailing comma on bare tuple prohibited".to_string() - } - - fn placeholder() -> Self { - TrailingCommaOnBareTupleProhibited + format!("Trailing comma on bare tuple prohibited") } } @@ -6060,17 +4974,14 @@ define_violation!( pub struct TrailingCommaProhibited; ); impl AlwaysAutofixableViolation for TrailingCommaProhibited { + #[derive_message_formats] fn message(&self) -> String { - "Trailing comma prohibited".to_string() + format!("Trailing comma prohibited") } fn autofix_title(&self) -> String { "Remove trailing comma".to_string() } - - fn placeholder() -> Self { - TrailingCommaProhibited - } } // flake8-no-pep420 @@ -6079,14 +4990,11 @@ define_violation!( pub struct ImplicitNamespacePackage(pub String); ); impl Violation for ImplicitNamespacePackage { + #[derive_message_formats] fn message(&self) -> String { let ImplicitNamespacePackage(filename) = self; format!("File `{filename}` is part of an implicit namespace package. Add an `__init__.py`.") } - - fn placeholder() -> Self { - ImplicitNamespacePackage("...".to_string()) - } } // Ruff @@ -6098,6 +5006,7 @@ define_violation!( } ); impl AlwaysAutofixableViolation for AmbiguousUnicodeCharacterString { + #[derive_message_formats] fn message(&self) -> String { let AmbiguousUnicodeCharacterString { confusable, @@ -6116,13 +5025,6 @@ impl AlwaysAutofixableViolation for AmbiguousUnicodeCharacterString { } = self; format!("Replace '{confusable}' with '{representant}'") } - - fn placeholder() -> Self { - AmbiguousUnicodeCharacterString { - confusable: '𝐁', - representant: 'B', - } - } } define_violation!( @@ -6132,6 +5034,7 @@ define_violation!( } ); impl AlwaysAutofixableViolation for AmbiguousUnicodeCharacterDocstring { + #[derive_message_formats] fn message(&self) -> String { let AmbiguousUnicodeCharacterDocstring { confusable, @@ -6150,13 +5053,6 @@ impl AlwaysAutofixableViolation for AmbiguousUnicodeCharacterDocstring { } = self; format!("Replace '{confusable}' with '{representant}'") } - - fn placeholder() -> Self { - AmbiguousUnicodeCharacterDocstring { - confusable: '𝐁', - representant: 'B', - } - } } define_violation!( @@ -6166,6 +5062,7 @@ define_violation!( } ); impl AlwaysAutofixableViolation for AmbiguousUnicodeCharacterComment { + #[derive_message_formats] fn message(&self) -> String { let AmbiguousUnicodeCharacterComment { confusable, @@ -6184,27 +5081,17 @@ impl AlwaysAutofixableViolation for AmbiguousUnicodeCharacterComment { } = self; format!("Replace '{confusable}' with '{representant}'") } - - fn placeholder() -> Self { - AmbiguousUnicodeCharacterComment { - confusable: '𝐁', - representant: 'B', - } - } } define_violation!( pub struct KeywordArgumentBeforeStarArgument(pub String); ); impl Violation for KeywordArgumentBeforeStarArgument { + #[derive_message_formats] fn message(&self) -> String { let KeywordArgumentBeforeStarArgument(name) = self; format!("Keyword argument `{name}` must come after starred arguments") } - - fn placeholder() -> Self { - KeywordArgumentBeforeStarArgument("...".to_string()) - } } #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -6218,10 +5105,11 @@ define_violation!( pub struct UnusedNOQA(pub Option); ); impl AlwaysAutofixableViolation for UnusedNOQA { + #[derive_message_formats] fn message(&self) -> String { let UnusedNOQA(codes) = self; match codes { - None => "Unused blanket `noqa` directive".to_string(), + None => format!("Unused blanket `noqa` directive"), Some(codes) => { let mut codes_by_reason = vec![]; if !codes.unmatched.is_empty() { @@ -6255,7 +5143,7 @@ impl AlwaysAutofixableViolation for UnusedNOQA { )); } if codes_by_reason.is_empty() { - "Unused `noqa` directive".to_string() + format!("Unused `noqa` directive") } else { format!("Unused `noqa` directive ({})", codes_by_reason.join("; ")) } @@ -6266,8 +5154,4 @@ impl AlwaysAutofixableViolation for UnusedNOQA { fn autofix_title(&self) -> String { "Remove unused `noqa` directive".to_string() } - - fn placeholder() -> Self { - UnusedNOQA(None) - } }