Skip to content

Commit 9ff9f53

Browse files
authored
Adopt Ruff (#62)
1 parent 71b52a0 commit 9ff9f53

20 files changed

+321
-246
lines changed

.ruff.toml

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
target-version = "py39"
2+
3+
[format]
4+
preview = true
5+
quote-style = "single"
6+
docstring-code-format = true
7+
8+
[lint]
9+
preview = true
10+
select = [
11+
"I", # isort
12+
]
13+
ignore = [
14+
"E501", # Ignore line length errors (we use auto-formatting)
15+
]

src/blurb/__main__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""Run blurb using ``python3 -m blurb``."""
2-
from blurb._cli import main
32

3+
from blurb._cli import main
44

55
if __name__ == '__main__':
66
main()

src/blurb/_add.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import tempfile
1010

1111
from blurb._blurb_file import BlurbError, Blurbs
12-
from blurb._cli import subcommand,error,prompt
12+
from blurb._cli import error, prompt, subcommand
1313
from blurb._git import flush_git_add_files, git_add_files
1414
from blurb._template import sections, template
1515

@@ -43,11 +43,11 @@ def add(*, issue: str | None = None, section: str | None = None):
4343
spaces in names can be substituted for underscores:
4444
4545
{sections}
46-
"""
46+
""" # fmt: skip
4747

4848
handle, tmp_path = tempfile.mkstemp('.rst')
4949
os.close(handle)
50-
atexit.register(lambda : os.unlink(tmp_path))
50+
atexit.register(lambda: os.unlink(tmp_path))
5151

5252
text = _blurb_template_text(issue=issue, section=section)
5353
with open(tmp_path, 'w', encoding='utf-8') as file:
@@ -72,6 +72,8 @@ def add(*, issue: str | None = None, section: str | None = None):
7272
git_add_files.append(path)
7373
flush_git_add_files()
7474
print('Ready for commit.')
75+
76+
7577
add.__doc__ = add.__doc__.format(sections='\n'.join(f'* {s}' for s in sections))
7678

7779

@@ -178,13 +180,13 @@ def _extract_section_name(section: str | None, /) -> str | None:
178180

179181
if not matches:
180182
section_list = '\n'.join(f'* {s}' for s in sections)
181-
raise SystemExit(f'Invalid section name: {section!r}\n\n'
182-
f'Valid names are:\n\n{section_list}')
183+
raise SystemExit(
184+
f'Invalid section name: {section!r}\n\nValid names are:\n\n{section_list}'
185+
)
183186

184187
if len(matches) > 1:
185188
multiple_matches = ', '.join(f'* {m}' for m in sorted(matches))
186-
raise SystemExit(f'More than one match for {section!r}:\n\n'
187-
f'{multiple_matches}')
189+
raise SystemExit(f'More than one match for {section!r}:\n\n{multiple_matches}')
188190

189191
return matches[0]
190192

src/blurb/_blurb_file.py

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -95,8 +95,13 @@ class BlurbError(RuntimeError):
9595

9696

9797
class Blurbs(list):
98-
def parse(self, text: str, *, metadata: dict[str, str] | None = None,
99-
filename: str = 'input') -> None:
98+
def parse(
99+
self,
100+
text: str,
101+
*,
102+
metadata: dict[str, str] | None = None,
103+
filename: str = 'input',
104+
) -> None:
100105
"""Parses a string.
101106
102107
Appends a list of blurb ENTRIES to self, as tuples: (metadata, body)
@@ -147,13 +152,17 @@ def finish_entry() -> None:
147152
throw(f'Invalid {issue_keys[key]} number: {value!r}')
148153

149154
if key == 'gh-issue' and int(value) < lowest_possible_gh_issue_number:
150-
throw(f'Invalid gh-issue number: {value!r} (must be >= {lowest_possible_gh_issue_number})')
155+
throw(
156+
f'Invalid gh-issue number: {value!r} (must be >= {lowest_possible_gh_issue_number})'
157+
)
151158

152159
if key == 'section':
153160
if no_changes:
154161
continue
155162
if value not in sections:
156-
throw(f'Invalid section {value!r}! You must use one of the predefined sections.')
163+
throw(
164+
f'Invalid section {value!r}! You must use one of the predefined sections.'
165+
)
157166

158167
if 'gh-issue' not in metadata and 'bpo' not in metadata:
159168
throw("'gh-issue:' or 'bpo:' must be specified in the metadata!")
@@ -232,7 +241,9 @@ def _parse_next_filename(filename: str) -> dict[str, str]:
232241
assert section in sections, f'Unknown section {section}'
233242

234243
fields = [x.strip() for x in filename.split('.')]
235-
assert len(fields) >= 4, f"Can't parse 'next' filename! filename {filename!r} fields {fields}"
244+
assert len(fields) >= 4, (
245+
f"Can't parse 'next' filename! filename {filename!r} fields {fields}"
246+
)
236247
assert fields[-1] == 'rst'
237248

238249
metadata = {'date': fields[0], 'nonce': fields[-2], 'section': section}
@@ -263,7 +274,7 @@ def ensure_metadata(self) -> None:
263274
('bpo', '0'),
264275
('date', sortable_datetime()),
265276
('nonce', generate_nonce(body)),
266-
):
277+
):
267278
if name not in metadata:
268279
metadata[name] = default
269280

@@ -274,10 +285,14 @@ def _extract_next_filename(self) -> str:
274285
metadata['section'] = sanitize_section(metadata['section'])
275286
metadata['root'] = root
276287
if int(metadata['gh-issue']) > 0:
277-
path = '{root}/Misc/NEWS.d/next/{section}/{date}.gh-issue-{gh-issue}.{nonce}.rst'.format_map(metadata)
288+
path = '{root}/Misc/NEWS.d/next/{section}/{date}.gh-issue-{gh-issue}.{nonce}.rst'.format_map(
289+
metadata
290+
)
278291
elif int(metadata['bpo']) > 0:
279292
# assume it's a GH issue number
280-
path = '{root}/Misc/NEWS.d/next/{section}/{date}.bpo-{bpo}.{nonce}.rst'.format_map(metadata)
293+
path = '{root}/Misc/NEWS.d/next/{section}/{date}.bpo-{bpo}.{nonce}.rst'.format_map(
294+
metadata
295+
)
281296
for name in ('root', 'section', 'date', 'gh-issue', 'bpo', 'nonce'):
282297
del metadata[name]
283298
return path
@@ -294,4 +309,4 @@ def save_next(self) -> str:
294309

295310

296311
def sortable_datetime() -> str:
297-
return time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
312+
return time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime())

src/blurb/_cli.py

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ def prompt(prompt: str, /) -> str:
2828

2929

3030
def require_ok(prompt: str, /) -> str:
31-
prompt = f"[{prompt}> "
31+
prompt = f'[{prompt}> '
3232
while True:
3333
s = input(prompt).strip()
3434
if s == 'ok':
@@ -88,7 +88,7 @@ def help(subcommand: str | None = None) -> None:
8888
options.append(f' [-{short_option}|--{name} {metavar}]')
8989
elif p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD:
9090
positionals.append(' ')
91-
has_default = (p.default != inspect._empty)
91+
has_default = p.default != inspect._empty
9292
if has_default:
9393
positionals.append('[')
9494
nesting += 1
@@ -146,7 +146,6 @@ def _blurb_help() -> None:
146146

147147

148148
def main() -> None:
149-
150149
args = sys.argv[1:]
151150

152151
if not args:
@@ -165,6 +164,7 @@ def main() -> None:
165164
raise SystemExit(fn(*args))
166165

167166
import blurb._merge
167+
168168
blurb._merge.original_dir = os.getcwd()
169169
try:
170170
chdir_to_repo_root()
@@ -177,8 +177,7 @@ def main() -> None:
177177
kwargs = {}
178178
for name, p in inspect.signature(fn).parameters.items():
179179
if p.kind == inspect.Parameter.KEYWORD_ONLY:
180-
if (p.default is not None
181-
and not isinstance(p.default, (bool, str))):
180+
if p.default is not None and not isinstance(p.default, (bool, str)):
182181
raise SystemExit(
183182
'blurb command-line processing cannot handle '
184183
f'options of type {type(p.default).__qualname__}'
@@ -262,7 +261,9 @@ def handle_option(s, dict):
262261
if total != 1:
263262
middle += 's'
264263

265-
print(f'Error: Wrong number of arguments!\n\nblurb {subcommand} {middle},\nand you specified {how_many}.')
264+
print(
265+
f'Error: Wrong number of arguments!\n\nblurb {subcommand} {middle},\nand you specified {how_many}.'
266+
)
266267
print()
267268
print('usage: ', end='')
268269
help(subcommand)
@@ -293,11 +294,13 @@ def test_first_line(filename, test):
293294
return False
294295
return True
295296

296-
if not (test_first_line('README', readme_re)
297-
or test_first_line('README.rst', readme_re)):
297+
if not (
298+
test_first_line('README', readme_re)
299+
or test_first_line('README.rst', readme_re)
300+
):
298301
continue
299302

300-
if not test_first_line('LICENSE', 'A. HISTORY OF THE SOFTWARE'.__eq__):
303+
if not test_first_line('LICENSE', 'A. HISTORY OF THE SOFTWARE'.__eq__):
301304
continue
302305
if not os.path.exists('Include/Python.h'):
303306
continue
@@ -307,5 +310,6 @@ def test_first_line(filename, test):
307310
break
308311

309312
import blurb._blurb_file
313+
310314
blurb._blurb_file.root = path
311315
return path

src/blurb/_merge.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,12 +43,14 @@ def write_news(output: str, *, versions: list[str]) -> None:
4343
def prnt(msg: str = '', /):
4444
buff.append(msg)
4545

46-
prnt("""
46+
prnt(
47+
"""
4748
+++++++++++
4849
Python News
4950
+++++++++++
5051
51-
""".strip())
52+
""".strip()
53+
)
5254

5355
for version in versions:
5456
filenames = glob_blurbs(version)

src/blurb/_populate.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import os
22

33
from blurb._cli import subcommand
4-
from blurb._git import git_add_files, flush_git_add_files
4+
from blurb._git import flush_git_add_files, git_add_files
55
from blurb._template import sanitize_section, sections
66

77

@@ -17,7 +17,9 @@ def populate() -> None:
1717
os.makedirs(dir_path, exist_ok=True)
1818
readme_path = f'NEWS.d/next/{dir_name}/README.rst'
1919
with open(readme_path, 'w', encoding='utf-8') as readme:
20-
readme.write(f'Put news entry ``blurb`` files for the *{section}* section in this directory.\n')
20+
readme.write(
21+
f'Put news entry ``blurb`` files for the *{section}* section in this directory.\n'
22+
)
2123
git_add_files.append(dir_path)
2224
git_add_files.append(readme_path)
2325
flush_git_add_files()

src/blurb/_release.py

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,12 @@
66
import blurb._blurb_file
77
from blurb._blurb_file import Blurbs
88
from blurb._cli import error, subcommand
9-
from blurb._git import (flush_git_add_files, flush_git_rm_files,
10-
git_rm_files, git_add_files)
9+
from blurb._git import (
10+
flush_git_add_files,
11+
flush_git_rm_files,
12+
git_add_files,
13+
git_rm_files,
14+
)
1115
from blurb._utils.globs import glob_blurbs
1216
from blurb._utils.text import generate_nonce
1317

@@ -25,7 +29,9 @@ def release(version: str) -> None:
2529

2630
existing_filenames = glob_blurbs(version)
2731
if existing_filenames:
28-
error("Sorry, can't handle appending 'next' files to an existing version (yet).")
32+
error(
33+
"Sorry, can't handle appending 'next' files to an existing version (yet)."
34+
)
2935

3036
output = f'Misc/NEWS.d/{version}.rst'
3137
filenames = glob_blurbs('next')
@@ -35,7 +41,13 @@ def release(version: str) -> None:
3541
if not filenames:
3642
print(f'No blurbs found. Setting {version} as having no changes.')
3743
body = f'There were no new changes in version {version}.\n'
38-
metadata = {'no changes': 'True', 'gh-issue': '0', 'section': 'Library', 'date': date, 'nonce': generate_nonce(body)}
44+
metadata = {
45+
'no changes': 'True',
46+
'gh-issue': '0',
47+
'section': 'Library',
48+
'date': date,
49+
'nonce': generate_nonce(body),
50+
}
3951
blurbs.append((metadata, body))
4052
else:
4153
count = len(filenames)

src/blurb/_template.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@
5252
'C_API': 'C API',
5353
'Core_and_Builtins': 'Core and Builtins',
5454
'Tools-Demos': 'Tools/Demos',
55-
}
55+
}
5656

5757

5858
def sanitize_section(section: str, /) -> str:

src/blurb/_utils/globs.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@
22
import os
33

44
from blurb._template import (
5-
next_filename_unsanitize_sections, sanitize_section,
6-
sanitize_section_legacy, sections,
5+
next_filename_unsanitize_sections,
6+
sanitize_section,
7+
sanitize_section_legacy,
8+
sections,
79
)
810

911

0 commit comments

Comments
 (0)