Skip to content

Commit bad4e14

Browse files
authored
Use ruff Python formatter (#150)
* initial ruff config, format * Tune down strictness, add dev deps, ci: add ruff checks in ci * chore: add ruff as a dev‑dependency * misc * rebase, tweak ruff settings for our needs * Ignore uv lock file * Ignore C401 * make ruff workflow only trigger when a python file is triggered to reduce gha resource usage * update pyproject.toml
1 parent cadf842 commit bad4e14

File tree

16 files changed

+630
-403
lines changed

16 files changed

+630
-403
lines changed

.github/auto-pr-tests/test_runner.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
import subprocess
1+
import difflib
22
import re
3+
import subprocess
34
from pathlib import Path
4-
import difflib
55

66

77
def normalize_ids(text: str) -> str:

.github/workflows/ruff-lint.yml

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
name: Ruff Checks
2+
3+
on:
4+
push:
5+
branches: [main]
6+
paths:
7+
- '**/*.py'
8+
pull_request:
9+
branches: [main]
10+
paths:
11+
- '**/*.py'
12+
13+
jobs:
14+
lint-and-test:
15+
runs-on: ubuntu-latest
16+
17+
steps:
18+
- name: Checkout code
19+
uses: actions/checkout@v4
20+
21+
- name: Install UV
22+
uses: astral-sh/setup-uv@v6
23+
24+
25+
- name: Set up Python
26+
run: uv python install
27+
28+
- name: Install dependencies
29+
run: uv sync --dev
30+
31+
- name: Run Ruff checks
32+
run: uv run ruff check .

builder/build_cli.py

Lines changed: 23 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -7,20 +7,21 @@
77
# dependencies globally). Each book should have a `make.py` script that updates
88
# the submodules, import this shared module, and calls the main function here.
99

10-
from pathlib import Path
1110
import argparse
12-
import subprocess
13-
import sys
14-
import requests
1511
import json
12+
import subprocess
1613
import time
14+
from pathlib import Path
15+
16+
import requests
1717

1818
# Automatically watch the following extra directories when --serve is used.
1919
EXTRA_WATCH_DIRS = ["exts", "themes"]
2020

2121
SPEC_CHECKSUM_URL = "https://rust-lang.github.io/fls/paragraph-ids.json"
2222
SPEC_LOCKFILE = "spec.lock"
2323

24+
2425
def build_docs(
2526
root: Path,
2627
builder: str,
@@ -68,15 +69,15 @@ def build_docs(
6869
# Add configuration options as needed
6970
if not spec_lock_consistency_check:
7071
conf_opt_values.append("enable_spec_lock_consistency=0")
71-
if offline:
72+
if offline:
7273
conf_opt_values.append("offline=1")
73-
if debug:
74+
if debug:
7475
conf_opt_values.append("debug=1")
7576

7677
# Only add the --define argument if there are options to define
7778
if conf_opt_values:
7879
for opt in conf_opt_values:
79-
args.append("--define") # each option needs its own --define
80+
args.append("--define") # each option needs its own --define
8081
args.append(opt)
8182

8283
if serve:
@@ -89,7 +90,6 @@ def build_docs(
8990
args += ["-W", "--keep-going"]
9091

9192
try:
92-
9393
# Tracking build time
9494
timer_start = time.perf_counter()
9595
subprocess.run(
@@ -111,24 +111,24 @@ def build_docs(
111111
print(f"\nBuild finished in {timer_end - timer_start:.2f} seconds.")
112112
return dest / builder
113113

114-
def update_spec_lockfile(spec_checksum_location, lockfile_location):
115114

115+
def update_spec_lockfile(spec_checksum_location, lockfile_location):
116116
try:
117117
response = requests.get(spec_checksum_location, stream=True)
118118

119119
response.raise_for_status()
120120

121-
with open(lockfile_location, 'wb') as file:
121+
with open(lockfile_location, "wb") as file:
122122
for chunk in response.iter_content(chunk_size=8192):
123123
if chunk:
124124
file.write(chunk)
125125

126-
with open(lockfile_location, 'r') as file:
126+
with open(lockfile_location, "r") as file:
127127
data = json.load(file)
128128

129129
print("-- read in --")
130130

131-
with open(lockfile_location, 'w') as outfile:
131+
with open(lockfile_location, "w") as outfile:
132132
json.dump(data, outfile, indent=4, sort_keys=True)
133133

134134
print("-- wrote back out --")
@@ -139,6 +139,7 @@ def update_spec_lockfile(spec_checksum_location, lockfile_location):
139139
print(f"Error downloading file: {e}")
140140
return False
141141

142+
142143
def main(root):
143144
root = Path(root)
144145

@@ -156,12 +157,10 @@ def main(root):
156157
"--ignore-spec-lock-diff",
157158
help="ignore spec.lock file differences with live release -- for WIP branches only",
158159
default=False,
159-
action="store_true"
160+
action="store_true",
160161
)
161162
parser.add_argument(
162-
"--update-spec-lock-file",
163-
help="update spec.lock file",
164-
action="store_true"
163+
"--update-spec-lock-file", help="update spec.lock file", action="store_true"
165164
)
166165
group.add_argument(
167166
"-s",
@@ -191,7 +190,12 @@ def main(root):
191190
if args.update_spec_lock_file:
192191
update_spec_lockfile(SPEC_CHECKSUM_URL, root / "src" / SPEC_LOCKFILE)
193192

194-
rendered = build_docs(
195-
root, "xml" if args.xml else "html", args.clear, args.serve, args.debug, args.offline, not args.ignore_spec_lock_diff,
193+
build_docs(
194+
root,
195+
"xml" if args.xml else "html",
196+
args.clear,
197+
args.serve,
198+
args.debug,
199+
args.offline,
200+
not args.ignore_spec_lock_diff,
196201
)
197-

exts/coding_guidelines/__init__.py

Lines changed: 38 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,19 @@
11
# SPDX-License-Identifier: MIT OR Apache-2.0
22
# SPDX-FileCopyrightText: The Coding Guidelines Subcommittee Contributors
3-
4-
from . import fls_checks
5-
from . import write_guidelines_ids
6-
from . import std_role
7-
from . import fls_linking
8-
from . import guidelines_checks
93

10-
from .common import logger, get_tqdm, bar_format, logging
114
from sphinx.domains import Domain
125

6+
from . import (
7+
common,
8+
fls_checks,
9+
fls_linking,
10+
guidelines_checks,
11+
std_role,
12+
write_guidelines_ids,
13+
)
14+
from .common import bar_format, get_tqdm, logger, logging
15+
16+
1317
class CodingGuidelinesDomain(Domain):
1418
name = "coding-guidelines"
1519
label = "Rust Standard Library"
@@ -19,17 +23,17 @@ class CodingGuidelinesDomain(Domain):
1923
directives = {}
2024
object_types = {}
2125
indices = {}
22-
26+
2327
def get_objects(self):
2428
return []
25-
29+
2630
def merge_domaindata(self, docnames, other):
2731
pass # No domain data to merge
2832

2933

3034
def on_build_finished(app, exception):
3135
print("\nFinalizing build:")
32-
for _ in get_tqdm(iterable=range(1), desc="Finalizing",bar_format=bar_format):
36+
for _ in get_tqdm(iterable=range(1), desc="Finalizing", bar_format=bar_format):
3337
pass
3438

3539
outdir = app.outdir
@@ -39,47 +43,44 @@ def on_build_finished(app, exception):
3943
if not app.config.debug:
4044
print(f" + Build complete -> {outdir}")
4145

46+
4247
def setup(app):
43-
4448
app.add_domain(CodingGuidelinesDomain)
4549
app.add_config_value(
46-
name = "offline",
47-
default=False,
48-
rebuild= "env"
49-
) # register the offline option
50+
name="offline", default=False, rebuild="env"
51+
) # register the offline option
5052
app.add_config_value(
5153
name="spec_std_docs_url",
5254
default="https://doc.rust-lang.org/stable/std",
5355
rebuild="env", # Rebuild the environment when this changes
5456
types=[str],
5557
)
56-
app.add_config_value(name='debug',
57-
default=False,
58-
rebuild='env'
58+
app.add_config_value(name="debug", default=False, rebuild="env")
59+
app.add_config_value(
60+
name="fls_paragraph_ids_url",
61+
default="https://rust-lang.github.io/fls/paragraph-ids.json",
62+
rebuild="env",
63+
)
64+
app.add_config_value(
65+
name="enable_spec_lock_consistency", default=True, rebuild="env"
5966
)
60-
app.add_config_value(name='fls_paragraph_ids_url',
61-
default='https://rust-lang.github.io/fls/paragraph-ids.json',
62-
rebuild='env')
63-
app.add_config_value(name='enable_spec_lock_consistency',
64-
default=True,
65-
rebuild='env')
6667
app.add_config_value(
67-
name='required_guideline_fields',
68-
default=['release', 'fls', 'decidability', 'scope'],
69-
rebuild='env',
68+
name="required_guideline_fields",
69+
default=["release", "fls", "decidability", "scope"],
70+
rebuild="env",
7071
types=[list],
7172
)
7273
if app.config.debug:
7374
logger.setLevel(logging.INFO)
74-
common.disable_tqdm = True
75-
76-
app.connect('env-check-consistency', guidelines_checks.validate_required_fields)
77-
app.connect('env-check-consistency', fls_checks.check_fls)
78-
app.connect('build-finished', write_guidelines_ids.build_finished)
79-
app.connect('build-finished', fls_linking.build_finished)
80-
app.connect('build-finished', on_build_finished)
81-
75+
common.disable_tqdm = True
76+
77+
app.connect("env-check-consistency", guidelines_checks.validate_required_fields)
78+
app.connect("env-check-consistency", fls_checks.check_fls)
79+
app.connect("build-finished", write_guidelines_ids.build_finished)
80+
app.connect("build-finished", fls_linking.build_finished)
81+
app.connect("build-finished", on_build_finished)
82+
8283
return {
83-
'version': '0.1',
84-
'parallel_read_safe': True,
84+
"version": "0.1",
85+
"parallel_read_safe": True,
8586
}

exts/coding_guidelines/common.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,19 @@
1+
import logging
12

23
from tqdm import tqdm
3-
import logging
44

55
# This is a wrapper around tqdm that allows us to disable it with this global variable
6-
disable_tqdm = False
6+
disable_tqdm = False
7+
8+
79
def get_tqdm(**kwargs):
8-
kwargs['disable'] = disable_tqdm
10+
kwargs["disable"] = disable_tqdm
911
return tqdm(**kwargs)
12+
13+
1014
# Get the Sphinx logger
11-
logger = logging.getLogger('sphinx')
12-
logger.setLevel(logging.WARNING)
15+
logger = logging.getLogger("sphinx")
16+
logger.setLevel(logging.WARNING)
1317

1418
# This is what controls the progress bar format
1519
bar_format = "{l_bar}{bar}| {n_fmt}/{total_fmt} {postfix}"
16-

0 commit comments

Comments
 (0)