Enable the RUF100 lint in Ruff

This commit is contained in:
Adam Turner 2025-01-02 23:25:30 +00:00
parent 5f6457911d
commit b5f9ac8afc
27 changed files with 34 additions and 37 deletions

View File

@ -266,7 +266,7 @@ select = [
"RUF046", # Value being casted is already an integer
"RUF048", # `__version__` may contain non-integral-like elements
"RUF055", # Plain string pattern passed to `re` function
# "RUF100", # Unused `noqa` directive
"RUF100", # Unused `noqa` directive
"RUF101", # `{original}` is a redirect to `{target}`
"RUF200", # Failed to parse pyproject.toml: {message}
# flake8-bandit ('S')

View File

@ -179,7 +179,7 @@ nitpick_ignore = {
(
'cpp:class',
'template<typename TOuter> template<typename TInner> Wrapper::Outer<TOuter>::Inner',
), # NoQA: E501
),
('cpp:identifier', 'MyContainer'),
('js:func', 'SomeError'),
('js:func', 'number'),
@ -312,7 +312,7 @@ REDIRECT_TEMPLATE = """
<a href="{{rel_url}}">If not, click here to continue.</a>
</body>
</html>
""" # noqa: E501
""" # NoQA: E501
def build_redirects(app: Sphinx, exception: Exception | None) -> None:

View File

@ -168,11 +168,8 @@ class _RootArgumentParser(argparse.ArgumentParser):
raise ValueError(msg)
def error(self, message: str) -> NoReturn:
sys.stderr.write(
__(
"{0}: error: {1}\nRun '{0} --help' for information" # NoQA: COM812
).format(self.prog, message)
)
msg = __("{0}: error: {1}\nRun '{0} --help' for information")
sys.stderr.write(msg.format(self.prog, message))
raise SystemExit(2)

View File

@ -9,7 +9,7 @@ from typing import TYPE_CHECKING, Any
from docutils.frontend import OptionParser
import sphinx.builders.latex.nodes # NoQA: F401,E501 # Workaround: import this before writer to avoid ImportError
import sphinx.builders.latex.nodes # NoQA: F401 # Workaround: import this before writer to avoid ImportError
from sphinx import addnodes, highlighting, package_dir
from sphinx.builders import Builder
from sphinx.builders.latex.constants import (

View File

@ -545,7 +545,7 @@ class HyperlinkAvailabilityCheckWorker(Thread):
status_code = response.status_code
redirect_status_code = (
response.history[-1].status_code if response.history else None
) # NoQA: E501
)
retry_after = response.headers.get('Retry-After', '')
response_url = f'{response.url}'
response.raise_for_status()

View File

@ -273,7 +273,7 @@ def ask_user(d: dict[str, Any]) -> None:
'for custom HTML templates and "_static" for custom stylesheets and other static\n' # NoQA: E501
'files. You can enter another prefix (such as ".") to replace the underscore.'
)
) # NoQA: E501
)
d['dot'] = do_prompt(__('Name prefix for templates and static dir'), '_', ok)
if 'project' not in d:

View File

@ -762,7 +762,7 @@ class CDomain(Domain):
# generated object types
'functionParam': ObjType(
_('function parameter'), 'identifier', 'var', 'member', 'data'
), # NoQA: E501
),
}
directives = {

View File

@ -25,7 +25,7 @@ if TYPE_CHECKING:
from sphinx.environment import BuildEnvironment
from sphinx.util.cfamily import StringifyTransform
DeclarationType: TypeAlias = Union[ # NoQA: UP007
DeclarationType: TypeAlias = Union[
'ASTStruct',
'ASTUnion',
'ASTEnum',

View File

@ -933,7 +933,7 @@ class DefinitionParser(BaseParser):
header = 'Type must be either just a name or a '
header += 'typedef-like declaration.'
raise self._make_multi_error(prev_errors, header) from ex_typed
else: # NoQA: RET506
else:
# For testing purposes.
# do it again to get the proper traceback (how do you
# reliably save a traceback when an exception is

View File

@ -947,7 +947,7 @@ class CPPDomain(Domain):
# generated object types
'functionParam': ObjType(
_('function parameter'), 'identifier', 'member', 'var'
), # NoQA: E501
),
'templateParam': ObjType(
_('template parameter'),
'identifier',
@ -957,7 +957,7 @@ class CPPDomain(Domain):
'member',
'var',
'type',
), # NoQA: E501
),
}
directives = {

View File

@ -1685,7 +1685,7 @@ class DefinitionParser(BaseParser):
else:
raise AssertionError from ex_untyped
raise self._make_multi_error(prev_errors, header) from ex_typed
else: # NoQA: RET506
else:
# For testing purposes.
# do it again to get the proper traceback (how do you
# reliably save a traceback when an exception is

View File

@ -80,7 +80,7 @@ class ModuleEntry(NamedTuple):
class PyFunction(PyObject):
"""Description of a function."""
option_spec: ClassVar[OptionSpec] = PyObject.option_spec.copy() # noqa: F821
option_spec: ClassVar[OptionSpec] = PyObject.option_spec.copy()
option_spec.update({
'async': directives.flag,
})

View File

@ -219,7 +219,7 @@ class TocTreeCollector(EnvironmentCollector):
_walk_toc(subnode, secnums, depth - 1, titlenode)
numstack.pop()
titlenode = None
elif isinstance(subnode, nodes.list_item): # NoQA: SIM114
elif isinstance(subnode, nodes.list_item):
_walk_toc(subnode, secnums, depth, titlenode)
titlenode = None
elif isinstance(subnode, addnodes.only):

View File

@ -326,7 +326,7 @@ class DocTestBuilder(Builder):
date = time.strftime('%Y-%m-%d %H:%M:%S')
outpath = self.outdir.joinpath('output.txt')
self.outfile = outpath.open('w', encoding='utf-8') # NoQA: SIM115
self.outfile = outpath.open('w', encoding='utf-8')
line = '=' * len(date)
self.outfile.write(
f'Results of doctest builder run on {date}\n'

View File

@ -265,7 +265,7 @@ class Config:
Use the type annotations of class attributes that are documented in the docstring
but do not have a type in the docstring.
""" # NoQA: D301
"""
_config_values: dict[str, tuple[Any, _ConfigRebuild]] = {
'napoleon_google_docstring': (True, 'env'),

View File

@ -558,7 +558,7 @@ class GoogleDocstring:
return [(' ' * n) + line for line in lines]
def _is_indented(self, line: str, indent: int = 1) -> bool:
for i, s in enumerate(line): # NoQA: SIM110
for i, s in enumerate(line):
if i >= indent:
return True
elif not s.isspace():

View File

@ -32,7 +32,7 @@ if TYPE_CHECKING:
from pygments.style import Style
if tuple(map(int, pygments.__version__.split('.')[:2])) < (2, 18):
from pygments.formatter import Formatter # NoQA: F811
from pygments.formatter import Formatter
Formatter.__class_getitem__ = classmethod(lambda cls, name: cls) # type: ignore[attr-defined]

View File

@ -207,7 +207,7 @@ def get_translation(catalog: str, namespace: str = 'general') -> Callable[[str],
def gettext(message: str) -> str:
if not is_translator_registered(catalog, namespace):
# not initialized yet
return _TranslationProxy(catalog, namespace, message) # type: ignore[return-value] # NoQA: E501
return _TranslationProxy(catalog, namespace, message) # type: ignore[return-value]
else:
translator = get_translator(catalog, namespace)
return translator.gettext(message)

View File

@ -589,7 +589,7 @@ class SphinxComponentRegistry:
def merge_source_suffix(app: Sphinx, config: Config) -> None:
"""Merge any user-specified source_suffix with any added by extensions."""
for suffix, filetype in app.registry.source_suffix.items():
if suffix not in app.config.source_suffix: # NoQA: SIM114
if suffix not in app.config.source_suffix:
app.config.source_suffix[suffix] = filetype
elif app.config.source_suffix[suffix] == 'restructuredtext':
# The filetype is not specified (default filetype).

View File

@ -222,7 +222,7 @@ def _shared_result_cache() -> None:
@pytest.fixture
def if_graphviz_found(app: SphinxTestApp) -> None: # NoQA: PT004
def if_graphviz_found(app: SphinxTestApp) -> None:
"""
The test will be skipped when using 'if_graphviz_found' fixture and graphviz
dot command is not found.
@ -246,7 +246,7 @@ def sphinx_test_tempdir(tmp_path_factory: pytest.TempPathFactory) -> Path:
@pytest.fixture
def rollback_sysmodules() -> Iterator[None]: # NoQA: PT004
def rollback_sysmodules() -> Iterator[None]:
"""
Rollback sys.modules to its value before testing to unload modules
during tests.

View File

@ -157,7 +157,7 @@ class path(str): # NoQA: FURB189
os.utime(self, arg)
def open(self, mode: str = 'r', **kwargs: Any) -> IO[str]:
return open(self, mode, **kwargs) # NoQA: SIM115
return open(self, mode, **kwargs)
def write_text(self, text: str, encoding: str = 'utf-8', **kwargs: Any) -> None:
"""

View File

@ -29,7 +29,7 @@ report_re = re.compile(
)
if TYPE_CHECKING:
from collections.abc import Callable, Iterator # NoQA: TC003
from collections.abc import Callable, Iterator
from types import ModuleType, TracebackType
from docutils.frontend import Values
@ -378,7 +378,7 @@ def switch_source_input(state: State, content: StringList) -> Iterator[None]:
# replace it by new one
state_machine: StateMachine[None] = StateMachine([], None) # type: ignore[arg-type]
state_machine.input_lines = content
state.memo.reporter.get_source_and_line = state_machine.get_source_and_line # type: ignore[attr-defined] # NoQA: E501
state.memo.reporter.get_source_and_line = state_machine.get_source_and_line # type: ignore[attr-defined]
yield
finally:

View File

@ -2136,7 +2136,7 @@ def test_latex_code_role(app):
r'\PYG{k}{pass}'
)
assert (
r'Inline \sphinxcode{\sphinxupquote{%' # NoQA: ISC003
r'Inline \sphinxcode{\sphinxupquote{%'
+ '\n'
+ common_content
+ '%\n}} code block'

View File

@ -835,7 +835,7 @@ def test_domain_c_build_intersphinx(tmp_path, app):
.. c:type:: _type
.. c:function:: void _functionParam(int param)
""" # NoQA: F841
"""
inv_file = tmp_path / 'inventory'
inv_file.write_bytes(
b"""\
@ -858,7 +858,7 @@ _type c:type 1 index.html#c.$ -
_union c:union 1 index.html#c.$ -
_var c:member 1 index.html#c.$ -
""")
) # NoQA: W291
)
app.config.intersphinx_mapping = {
'local': ('https://localhost/intersphinx/c/', str(inv_file)),
}

View File

@ -1863,7 +1863,7 @@ def test_domain_cpp_build_intersphinx(tmp_path, app):
.. cpp:enum-class:: _enumClass
.. cpp:function:: void _functionParam(int param)
.. cpp:function:: template<typename TParam> void _templateParam()
""" # NoQA: F841
"""
inv_file = tmp_path / 'inventory'
inv_file.write_bytes(
b"""\
@ -1893,7 +1893,7 @@ _type cpp:type 1 index.html#_CPPv45$ -
_union cpp:union 1 index.html#_CPPv46$ -
_var cpp:member 1 index.html#_CPPv44$ -
""")
) # NoQA: W291
)
app.config.intersphinx_mapping = {
'test': ('https://localhost/intersphinx/cpp/', str(inv_file)),
}

View File

@ -2881,7 +2881,7 @@ None py:data 1 none.html -
list py:class 1 list.html -
int py:class 1 int.html -
""")
) # NoQA: W291
)
app.config.intersphinx_mapping = {'python': ('127.0.0.1:5555', str(inv_file))}
validate_intersphinx_mapping(app, app.config)
load_mappings(app)

View File

@ -811,7 +811,7 @@ def test_isproperty():
def test_isgenericalias():
#: A list of int
T = List[int] # NoQA: UP006
S = list[Union[str, None]] # NoQA: UP006, UP007
S = list[Union[str, None]] # NoQA: UP007
C = Callable[[int], None] # NoQA: UP006 # a generic alias not having a doccomment