Skip to content

Commit 0c22014

Browse files
Apply ruff formatting to patchcheck.py after adding type hints
1 parent 9c6a1f8 commit 0c22014

File tree

1 file changed

+72
-59
lines changed

1 file changed

+72
-59
lines changed

Tools/patchcheck/patchcheck.py

Lines changed: 72 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,35 @@
11
#!/usr/bin/env python3
22
"""Check proposed changes for common issues."""
3+
34
import sys
45
import os.path
56
import subprocess
67
import sysconfig
8+
from typing import Callable, Optional
79

810

9-
def get_python_source_dir():
10-
src_dir = sysconfig.get_config_var('abs_srcdir')
11+
def get_python_source_dir() -> str:
12+
src_dir = sysconfig.get_config_var("abs_srcdir")
1113
if not src_dir:
12-
src_dir = sysconfig.get_config_var('srcdir')
14+
src_dir = sysconfig.get_config_var("srcdir")
1315
return os.path.abspath(src_dir)
1416

1517

1618
SRCDIR = get_python_source_dir()
1719

1820

19-
def n_files_str(count):
21+
def n_files_str(count: int) -> str:
2022
"""Return 'N file(s)' with the proper plurality on 'file'."""
2123
s = "s" if count != 1 else ""
2224
return f"{count} file{s}"
2325

2426

25-
def status(message, modal=False, info=None):
27+
def status(message: str, modal: bool = False, info: Optional[Callable] = None):
2628
"""Decorator to output status info to stdout."""
29+
2730
def decorated_fxn(fxn):
2831
def call_fxn(*args, **kwargs):
29-
sys.stdout.write(message + ' ... ')
32+
sys.stdout.write(message + " ... ")
3033
sys.stdout.flush()
3134
result = fxn(*args, **kwargs)
3235
if not modal and not info:
@@ -36,23 +39,24 @@ def call_fxn(*args, **kwargs):
3639
else:
3740
print("yes" if result else "NO")
3841
return result
42+
3943
return call_fxn
44+
4045
return decorated_fxn
4146

4247

43-
def get_git_branch():
48+
def get_git_branch() -> Optional[str]:
4449
"""Get the symbolic name for the current git branch"""
4550
cmd = "git rev-parse --abbrev-ref HEAD".split()
4651
try:
47-
return subprocess.check_output(cmd,
48-
stderr=subprocess.DEVNULL,
49-
cwd=SRCDIR,
50-
encoding='UTF-8')
52+
return subprocess.check_output(
53+
cmd, stderr=subprocess.DEVNULL, cwd=SRCDIR, encoding="UTF-8"
54+
)
5155
except subprocess.CalledProcessError:
5256
return None
5357

5458

55-
def get_git_upstream_remote():
59+
def get_git_upstream_remote() -> str:
5660
"""
5761
Get the remote name to use for upstream branches
5862
@@ -63,14 +67,12 @@ def get_git_upstream_remote():
6367
"""
6468
cmd = "git remote -v".split()
6569
output = subprocess.check_output(
66-
cmd,
67-
stderr=subprocess.DEVNULL,
68-
cwd=SRCDIR,
69-
encoding="UTF-8"
70+
cmd, stderr=subprocess.DEVNULL, cwd=SRCDIR, encoding="UTF-8"
7071
)
7172
# Filter to desired remotes, accounting for potential uppercasing
7273
filtered_remotes = {
73-
remote.split("\t")[0].lower() for remote in output.split('\n')
74+
remote.split("\t")[0].lower()
75+
for remote in output.split("\n")
7476
if "python/cpython" in remote.lower() and remote.endswith("(fetch)")
7577
}
7678
if len(filtered_remotes) == 1:
@@ -80,7 +82,7 @@ def get_git_upstream_remote():
8082
if remote_name in filtered_remotes:
8183
return remote_name
8284
remotes_found = "\n".join(
83-
{remote for remote in output.split('\n') if remote.endswith("(fetch)")}
85+
{remote for remote in output.split("\n") if remote.endswith("(fetch)")}
8486
)
8587
raise ValueError(
8688
f"Patchcheck was unable to find an unambiguous upstream remote, "
@@ -89,23 +91,25 @@ def get_git_upstream_remote():
8991
f"https://devguide.python.org/getting-started/"
9092
f"git-boot-camp/#cloning-a-forked-cpython-repository "
9193
f"\nRemotes found: \n{remotes_found}"
92-
)
94+
)
9395

9496

95-
def get_git_remote_default_branch(remote_name):
97+
def get_git_remote_default_branch(remote_name: str) -> Optional[str]:
9698
"""Get the name of the default branch for the given remote
9799
98100
It is typically called 'main', but may differ
99101
"""
100102
cmd = f"git remote show {remote_name}".split()
101103
env = os.environ.copy()
102-
env['LANG'] = 'C'
104+
env["LANG"] = "C"
103105
try:
104-
remote_info = subprocess.check_output(cmd,
105-
stderr=subprocess.DEVNULL,
106-
cwd=SRCDIR,
107-
encoding='UTF-8',
108-
env=env)
106+
remote_info = subprocess.check_output(
107+
cmd,
108+
stderr=subprocess.DEVNULL,
109+
cwd=SRCDIR,
110+
encoding="UTF-8",
111+
env=env,
112+
)
109113
except subprocess.CalledProcessError:
110114
return None
111115
for line in remote_info.splitlines():
@@ -115,15 +119,17 @@ def get_git_remote_default_branch(remote_name):
115119
return None
116120

117121

118-
@status("Getting base branch for PR",
119-
info=lambda x: x if x is not None else "not a PR branch")
120-
def get_base_branch():
121-
if not os.path.exists(os.path.join(SRCDIR, '.git')):
122+
@status(
123+
"Getting base branch for PR",
124+
info=lambda x: x if x is not None else "not a PR branch",
125+
)
126+
def get_base_branch() -> Optional[str]:
127+
if not os.path.exists(os.path.join(SRCDIR, ".git")):
122128
# Not a git checkout, so there's no base branch
123129
return None
124130
upstream_remote = get_git_upstream_remote()
125131
version = sys.version_info
126-
if version.releaselevel == 'alpha':
132+
if version.releaselevel == "alpha":
127133
base_branch = get_git_remote_default_branch(upstream_remote)
128134
else:
129135
base_branch = "{0.major}.{0.minor}".format(version)
@@ -134,38 +140,40 @@ def get_base_branch():
134140
return upstream_remote + "/" + base_branch
135141

136142

137-
@status("Getting the list of files that have been added/changed",
138-
info=lambda x: n_files_str(len(x)))
139-
def changed_files(base_branch=None):
143+
@status(
144+
"Getting the list of files that have been added/changed",
145+
info=lambda x: n_files_str(len(x)),
146+
)
147+
def changed_files(base_branch: Optional[str] = None) -> list[str]:
140148
"""Get the list of changed or added files from git."""
141-
if os.path.exists(os.path.join(SRCDIR, '.git')):
149+
if os.path.exists(os.path.join(SRCDIR, ".git")):
142150
# We just use an existence check here as:
143151
# directory = normal git checkout/clone
144152
# file = git worktree directory
145153
if base_branch:
146-
cmd = 'git diff --name-status ' + base_branch
154+
cmd = "git diff --name-status " + base_branch
147155
else:
148-
cmd = 'git status --porcelain'
156+
cmd = "git status --porcelain"
149157
filenames = []
150-
with subprocess.Popen(cmd.split(),
151-
stdout=subprocess.PIPE,
152-
cwd=SRCDIR) as st:
158+
with subprocess.Popen(
159+
cmd.split(), stdout=subprocess.PIPE, cwd=SRCDIR
160+
) as st:
153161
git_file_status, _ = st.communicate()
154162
if st.returncode != 0:
155-
sys.exit(f'error running {cmd}')
163+
sys.exit(f"error running {cmd}")
156164
for line in git_file_status.splitlines():
157165
line = line.decode().rstrip()
158166
status_text, filename = line.split(maxsplit=1)
159167
status = set(status_text)
160168
# modified, added or unmerged files
161-
if not status.intersection('MAU'):
169+
if not status.intersection("MAU"):
162170
continue
163-
if ' -> ' in filename:
171+
if " -> " in filename:
164172
# file is renamed
165-
filename = filename.split(' -> ', 2)[1].strip()
173+
filename = filename.split(" -> ", 2)[1].strip()
166174
filenames.append(filename)
167175
else:
168-
sys.exit('need a git checkout to get modified files')
176+
sys.exit("need a git checkout to get modified files")
169177

170178
return list(map(os.path.normpath, filenames))
171179

@@ -179,40 +187,45 @@ def docs_modified(file_paths):
179187
@status("Misc/ACKS updated", modal=True)
180188
def credit_given(file_paths):
181189
"""Check if Misc/ACKS has been changed."""
182-
return os.path.join('Misc', 'ACKS') in file_paths
190+
return os.path.join("Misc", "ACKS") in file_paths
183191

184192

185193
@status("Misc/NEWS.d updated with `blurb`", modal=True)
186194
def reported_news(file_paths):
187195
"""Check if Misc/NEWS.d has been changed."""
188-
return any(p.startswith(os.path.join('Misc', 'NEWS.d', 'next'))
189-
for p in file_paths)
196+
return any(
197+
p.startswith(os.path.join("Misc", "NEWS.d", "next"))
198+
for p in file_paths
199+
)
190200

191201

192202
@status("configure regenerated", modal=True, info=str)
193203
def regenerated_configure(file_paths):
194204
"""Check if configure has been regenerated."""
195-
if 'configure.ac' in file_paths:
196-
return "yes" if 'configure' in file_paths else "no"
205+
if "configure.ac" in file_paths:
206+
return "yes" if "configure" in file_paths else "no"
197207
else:
198208
return "not needed"
199209

200210

201211
@status("pyconfig.h.in regenerated", modal=True, info=str)
202212
def regenerated_pyconfig_h_in(file_paths):
203213
"""Check if pyconfig.h.in has been regenerated."""
204-
if 'configure.ac' in file_paths:
205-
return "yes" if 'pyconfig.h.in' in file_paths else "no"
214+
if "configure.ac" in file_paths:
215+
return "yes" if "pyconfig.h.in" in file_paths else "no"
206216
else:
207217
return "not needed"
208218

209219

210-
def main():
220+
def main() -> None:
211221
base_branch = get_base_branch()
212222
file_paths = changed_files(base_branch)
213-
has_doc_files = any(fn for fn in file_paths if fn.startswith('Doc') and
214-
fn.endswith(('.rst', '.inc')))
215-
misc_files = {p for p in file_paths if p.startswith('Misc')}
223+
has_doc_files = any(
224+
fn
225+
for fn in file_paths
226+
if fn.startswith("Doc") and fn.endswith((".rst", ".inc"))
227+
)
228+
misc_files = {p for p in file_paths if p.startswith("Misc")}
216229
# Docs updated.
217230
docs_modified(has_doc_files)
218231
# Misc/ACKS changed.
@@ -225,14 +238,14 @@ def main():
225238
regenerated_pyconfig_h_in(file_paths)
226239

227240
# Test suite run and passed.
228-
has_c_files = any(fn for fn in file_paths if fn.endswith(('.c', '.h')))
229-
has_python_files = any(fn for fn in file_paths if fn.endswith('.py'))
241+
has_c_files = any(fn for fn in file_paths if fn.endswith((".c", ".h")))
242+
has_python_files = any(fn for fn in file_paths if fn.endswith(".py"))
230243
print()
231244
if has_c_files:
232245
print("Did you run the test suite and check for refleaks?")
233246
elif has_python_files:
234247
print("Did you run the test suite?")
235248

236249

237-
if __name__ == '__main__':
250+
if __name__ == "__main__":
238251
main()

0 commit comments

Comments
 (0)