Skip to content

Commit 7b531ee

Browse files
committed
Enable more Ruff linters
1 parent 973e493 commit 7b531ee

File tree

5 files changed

+74
-62
lines changed

5 files changed

+74
-62
lines changed

.ruff.toml

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,22 @@ output-format = "full"
55
[lint]
66
preview = true
77
select = [
8+
"C4",
89
"B", # flake8-bugbear
910
"E", # pycodestyle
11+
"EM", # flake8-errmsg
1012
"F", # pyflakes
13+
"FA", # flake8-future-annotations
1114
"FLY", # flynt
15+
"FURB",# refurb
16+
"G", # flake8-logging-format
1217
"I", # isort
18+
"LOG", # flake8-logging
1319
"N", # pep8-naming
20+
"PERF",# perflint
21+
"PGH", # pygrep-hooks
22+
"PT", # flake8-pytest-style
23+
"TCH", # flake8-type-checking
1424
"UP", # pyupgrade
1525
"W", # pycodestyle
1626
]

sphinxarg/ext.py

Lines changed: 37 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@
2020

2121
def map_nested_definitions(nested_content):
2222
if nested_content is None:
23-
raise Exception('Nested content should be iterable, not null')
23+
msg = 'Nested content should be iterable, not null'
24+
raise Exception(msg)
2425
# build definition dictionary
2526
definitions = {}
2627
for item in nested_content:
@@ -37,24 +38,24 @@ def map_nested_definitions(nested_content):
3738
ci = subitem[idx]
3839
if len(ci.children) > 0:
3940
classifier = ci.children[0].astext()
40-
if classifier is not None and classifier not in (
41+
if classifier is not None and classifier not in {
4142
'@replace',
4243
'@before',
4344
'@after',
4445
'@skip',
45-
):
46-
raise Exception(f'Unknown classifier: {classifier}')
46+
}:
47+
msg = f'Unknown classifier: {classifier}'
48+
raise Exception(msg)
4749
idx = subitem.first_child_matching_class(nodes.term)
4850
if idx is not None:
4951
term = subitem[idx]
5052
if len(term.children) > 0:
5153
term = term.children[0].astext()
5254
idx = subitem.first_child_matching_class(nodes.definition)
5355
if idx is not None:
54-
subcontent = []
55-
for _ in subitem[idx]:
56-
if isinstance(_, nodes.definition_list):
57-
subcontent.append(_)
56+
subcontent = [
57+
_ for _ in subitem[idx] if isinstance(_, nodes.definition_list)
58+
]
5859
definitions[term] = (classifier, subitem[idx], subcontent)
5960

6061
return definitions
@@ -123,7 +124,7 @@ def print_action_groups(data, nested_content, markdown_help=False, settings=None
123124

124125
local_definitions = definitions
125126
if len(subcontent) > 0:
126-
local_definitions = {k: v for k, v in definitions.items()}
127+
local_definitions = dict(definitions.items())
127128
for k, v in map_nested_definitions(subcontent).items():
128129
local_definitions[k] = v
129130

@@ -267,23 +268,23 @@ def ensure_unique_ids(items):
267268

268269
class ArgParseDirective(Directive):
269270
has_content = True
270-
option_spec = dict(
271-
module=unchanged,
272-
func=unchanged,
273-
ref=unchanged,
274-
prog=unchanged,
275-
path=unchanged,
276-
nodefault=flag,
277-
nodefaultconst=flag,
278-
filename=unchanged,
279-
manpage=unchanged,
280-
nosubcommands=unchanged,
281-
passparser=flag,
282-
noepilog=unchanged,
283-
nodescription=unchanged,
284-
markdown=flag,
285-
markdownhelp=flag,
286-
)
271+
option_spec = {
272+
'module': unchanged,
273+
'func': unchanged,
274+
'ref': unchanged,
275+
'prog': unchanged,
276+
'path': unchanged,
277+
'nodefault': flag,
278+
'nodefaultconst': flag,
279+
'filename': unchanged,
280+
'manpage': unchanged,
281+
'nosubcommands': unchanged,
282+
'passparser': flag,
283+
'noepilog': unchanged,
284+
'nodescription': unchanged,
285+
'markdown': flag,
286+
'markdownhelp': flag,
287+
}
287288

288289
def _construct_manpage_specific_structure(self, parser_info):
289290
"""
@@ -489,25 +490,26 @@ def run(self):
489490
attr_name = self.options['func']
490491
func = mod[attr_name]
491492
else:
492-
raise self.error(
493-
':module: and :func: should be specified, or :ref:, or :filename: and :func:'
494-
)
493+
msg = ':module: and :func: should be specified, or :ref:, or :filename: and :func:'
494+
raise self.error(msg)
495495

496496
# Skip this if we're dealing with a local file, since it obviously can't be imported
497497
if 'filename' not in self.options:
498498
try:
499499
mod = importlib.import_module(module_name)
500500
except ImportError as exc:
501-
raise self.error(
501+
msg = (
502502
f'Failed to import "{attr_name}" from "{module_name}".\n'
503503
f'{sys.exc_info()[1]}'
504-
) from exc
504+
)
505+
raise self.error(msg) from exc
505506

506507
if not hasattr(mod, attr_name):
507-
raise self.error(
508+
msg = (
508509
f'Module "{module_name}" has no attribute "{attr_name}"\n'
509510
f'Incorrect argparse :module: or :func: values?'
510511
)
512+
raise self.error(msg)
511513
func = getattr(mod, attr_name)
512514

513515
if isinstance(func, ArgumentParser):
@@ -542,9 +544,9 @@ def run(self):
542544
self.state.nested_parse(self.content, self.content_offset, nested_content)
543545
nested_content = nested_content.children
544546
# add common content between
545-
for item in nested_content:
546-
if not isinstance(item, nodes.definition_list):
547-
items.append(item)
547+
items += [
548+
item for item in nested_content if not isinstance(item, nodes.definition_list)
549+
]
548550

549551
markdown_help = False
550552
if 'markdownhelp' in self.options:

sphinxarg/markdown.py

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
from __future__ import annotations
22

3+
import contextlib
4+
5+
from docutils import nodes
6+
from docutils.utils.code_analyzer import Lexer
7+
38
try:
49
from commonmark import Parser
510
except ImportError:
@@ -8,8 +13,6 @@
813
from commonmark.node import Node
914
except ImportError:
1015
from CommonMark.node import Node
11-
from docutils import nodes
12-
from docutils.utils.code_analyzer import Lexer
1316

1417

1518
def custom_walker(node, space=''):
@@ -30,10 +33,8 @@ def custom_walker(node, space=''):
3033
Spaces are used to convey nesting
3134
"""
3235
txt = ''
33-
try:
36+
with contextlib.suppress(Exception):
3437
txt = node.literal
35-
except Exception:
36-
pass
3738

3839
if txt is None or txt == '':
3940
print(f'{space}{node.t}')
@@ -124,9 +125,10 @@ def literal(node):
124125
rendered = []
125126
try:
126127
if node.info is not None:
127-
l = Lexer(node.literal, node.info, tokennames='long')
128-
for _ in l:
129-
rendered.append(node.inline(classes=_[0], text=_[1]))
128+
rendered = [
129+
node.inline(classes=_[0], text=_[1])
130+
for _ in Lexer(node.literal, node.info, tokennames='long')
131+
]
130132
except Exception:
131133
pass
132134

@@ -149,12 +151,14 @@ def literal_block(node):
149151
"""
150152
A block of code
151153
"""
154+
152155
rendered = []
153156
try:
154157
if node.info is not None:
155-
l = Lexer(node.literal, node.info, tokennames='long')
156-
for _ in l:
157-
rendered.append(node.inline(classes=_[0], text=_[1]))
158+
rendered = [
159+
node.inline(classes=_[0], text=_[1])
160+
for _ in Lexer(node.literal, node.info, tokennames='long')
161+
]
158162
except Exception:
159163
pass
160164

@@ -206,9 +210,8 @@ def section(node):
206210
This is a custom type
207211
"""
208212
title = '' # All sections need an id
209-
if node.first_child is not None:
210-
if node.first_child.t == 'heading':
211-
title = node.first_child.first_child.literal
213+
if node.first_child is not None and node.first_child.t == 'heading':
214+
title = node.first_child.first_child.literal
212215
o = nodes.section(ids=[title], names=[title])
213216
for n in markdown(node):
214217
o += n

sphinxarg/parser.py

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from __future__ import annotations
22

3+
import contextlib
34
import re
45
from argparse import _HelpAction, _StoreConstAction, _SubParsersAction
56

@@ -17,20 +18,20 @@ def parser_navigate(parser_result, path, current_path=None):
1718
if len(path) == 0:
1819
return parser_result
1920
if 'children' not in parser_result:
20-
raise NavigationException(
21-
f"Current parser has no child elements. (path: {' '.join(current_path)})"
22-
)
21+
msg = f"Current parser has no child elements. (path: {' '.join(current_path)})"
22+
raise NavigationException(msg)
2323
next_hop = path.pop(0)
2424
for child in parser_result['children']:
2525
# identifer is only used for aliased subcommands
2626
identifier = child['identifier'] if 'identifier' in child else child['name']
2727
if identifier == next_hop:
2828
current_path.append(next_hop)
2929
return parser_navigate(child, path, current_path)
30-
raise NavigationException(
30+
msg = (
3131
f"Current parser has no child element with name: {next_hop} "
3232
f"(path: {' '.join(current_path)})"
3333
)
34+
raise NavigationException(msg)
3435

3536

3637
def _try_add_parser_attribute(data, parser, attribname):
@@ -128,18 +129,13 @@ def parse_parser(parser, data=None, **kwargs):
128129
format_dict = dict(vars(action), prog=data.get('prog', ''), default=default)
129130
format_dict['default'] = default
130131
help_str = action.help or '' # Ensure we don't print None
131-
try:
132+
with contextlib.suppress(Exception):
132133
help_str = help_str % format_dict
133-
except Exception:
134-
pass
135134

136135
# Options have the option_strings set, positional arguments don't
137136
name = action.option_strings
138137
if name == []:
139-
if action.metavar is None:
140-
name = [action.dest]
141-
else:
142-
name = [action.metavar]
138+
name = [action.dest] if action.metavar is None else [action.metavar]
143139
# Skip lines for subcommands
144140
if name == ['==SUPPRESS==']:
145141
continue

test/test_default_html.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,14 +35,15 @@ def get_text(node):
3535
if all(not rex.search(get_text(node)) for node in nodes):
3636
return
3737

38-
raise AssertionError(
38+
msg = (
3939
f'{check!r} not found in any node matching path {path} in {fname}: '
4040
f'{[node.text for node in nodes]!r}'
4141
)
42+
raise AssertionError(msg)
4243

4344

4445
@pytest.mark.parametrize(
45-
'fname,expect_list',
46+
('fname', 'expect_list'),
4647
[
4748
(
4849
'index.html',

0 commit comments

Comments
 (0)