Debian Codegraph @

Tools/patchcheck/patchcheck.py

raw
1 #!/usr/bin/env python3
2 """Check proposed changes for common issues."""
3 import sys
4 import os.path
5 import subprocess
6 import sysconfig
7
8
9 def get_python_source_dir():
10 src_dir = sysconfig.get_config_var('abs_srcdir')
11 if not src_dir:
12 src_dir = sysconfig.get_config_var('srcdir')
13 return os.path.abspath(src_dir)
14
15
16 SRCDIR = get_python_source_dir()
17
18
19 def n_files_str(count):
20 """Return 'N file(s)' with the proper plurality on 'file'."""
21 s = "s" if count != 1 else ""
22 return f"{count} file{s}"
23
24
25 def status(message, modal=False, info=None):
26 """Decorator to output status info to stdout."""
27 def decorated_fxn(fxn):
28 def call_fxn(*args, **kwargs):
29 sys.stdout.write(message + ' ... ')
30 sys.stdout.flush()
31 result = fxn(*args, **kwargs)
32 if not modal and not info:
33 print("done")
34 elif info:
35 print(info(result))
36 else:
37 print("yes" if result else "NO")
38 return result
39 return call_fxn
40 return decorated_fxn
41
42
43 def get_git_branch():
44 """Get the symbolic name for the current git branch"""
45 cmd = "git rev-parse --abbrev-ref HEAD".split()
46 try:
47 return subprocess.check_output(cmd,
48 stderr=subprocess.DEVNULL,
49 cwd=SRCDIR,
50 encoding='UTF-8')
51 except subprocess.CalledProcessError:
52 return None
53
54
55 def get_git_upstream_remote():
56 """
57 Get the remote name to use for upstream branches
58
59 Check for presence of "https://github.com/python/cpython" remote URL.
60 If only one is found, return that remote name. If multiple are found,
61 check for and return "upstream", "origin", or "python", in that
62 order. Raise an error if no valid matches are found.
63 """
64 cmd = "git remote -v".split()
65 output = subprocess.check_output(
66 cmd,
67 stderr=subprocess.DEVNULL,
68 cwd=SRCDIR,
69 encoding="UTF-8"
70 )
71 # Filter to desired remotes, accounting for potential uppercasing
72 filtered_remotes = {
73 remote.split("\t")[0].lower() for remote in output.split('\n')
74 if "python/cpython" in remote.lower() and remote.endswith("(fetch)")
75 }
76 if len(filtered_remotes) == 1:
77 [remote] = filtered_remotes
78 return remote
79 for remote_name in ["upstream", "origin", "python"]:
80 if remote_name in filtered_remotes:
81 return remote_name
82 remotes_found = "\n".join(
83 {remote for remote in output.split('\n') if remote.endswith("(fetch)")}
84 )
85 raise ValueError(
86 f"Patchcheck was unable to find an unambiguous upstream remote, "
87 f"with URL matching 'https://github.com/python/cpython'. "
88 f"For help creating an upstream remote, see Dev Guide: "
89 f"https://devguide.python.org/getting-started/"
90 f"git-boot-camp/#cloning-a-forked-cpython-repository "
91 f"\nRemotes found: \n{remotes_found}"
92 )
93
94
95 def get_git_remote_default_branch(remote_name):
96 """Get the name of the default branch for the given remote
97
98 It is typically called 'main', but may differ
99 """
100 cmd = f"git remote show {remote_name}".split()
101 env = os.environ.copy()
102 env['LANG'] = 'C'
103 try:
104 remote_info = subprocess.check_output(cmd,
105 stderr=subprocess.DEVNULL,
106 cwd=SRCDIR,
107 encoding='UTF-8',
108 env=env)
109 except subprocess.CalledProcessError:
110 return None
111 for line in remote_info.splitlines():
112 if "HEAD branch:" in line:
113 base_branch = line.split(":")[1].strip()
114 return base_branch
115 return None
116
117
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 # Not a git checkout, so there's no base branch
123 return None
124 upstream_remote = get_git_upstream_remote()
125 version = sys.version_info
126 if version.releaselevel == 'alpha':
127 base_branch = get_git_remote_default_branch(upstream_remote)
128 else:
129 base_branch = "{0.major}.{0.minor}".format(version)
130 this_branch = get_git_branch()
131 if this_branch is None or this_branch == base_branch:
132 # Not on a git PR branch, so there's no base branch
133 return None
134 return upstream_remote + "/" + base_branch
135
136
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):
140 """Get the list of changed or added files from git."""
141 if os.path.exists(os.path.join(SRCDIR, '.git')):
142 # We just use an existence check here as:
143 # directory = normal git checkout/clone
144 # file = git worktree directory
145 if base_branch:
146 cmd = 'git diff --name-status ' + base_branch
147 else:
148 cmd = 'git status --porcelain'
149 filenames = []
150 with subprocess.Popen(cmd.split(),
151 stdout=subprocess.PIPE,
152 cwd=SRCDIR) as st:
153 git_file_status, _ = st.communicate()
154 if st.returncode != 0:
155 sys.exit(f'error running {cmd}')
156 for line in git_file_status.splitlines():
157 line = line.decode().rstrip()
158 status_text, filename = line.split(maxsplit=1)
159 status = set(status_text)
160 # modified, added or unmerged files
161 if not status.intersection('MAU'):
162 continue
163 if ' -> ' in filename:
164 # file is renamed
165 filename = filename.split(' -> ', 2)[1].strip()
166 filenames.append(filename)
167 else:
168 sys.exit('need a git checkout to get modified files')
169
170 return list(map(os.path.normpath, filenames))
171
172
173 @status("Docs modified", modal=True)
174 def docs_modified(file_paths):
175 """Report if any file in the Doc directory has been changed."""
176 return bool(file_paths)
177
178
179 @status("Misc/ACKS updated", modal=True)
180 def credit_given(file_paths):
181 """Check if Misc/ACKS has been changed."""
182 return os.path.join('Misc', 'ACKS') in file_paths
183
184
185 @status("Misc/NEWS.d updated with `blurb`", modal=True)
186 def reported_news(file_paths):
187 """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)
190
191
192 @status("configure regenerated", modal=True, info=str)
193 def regenerated_configure(file_paths):
194 """Check if configure has been regenerated."""
195 if 'configure.ac' in file_paths:
196 return "yes" if 'configure' in file_paths else "no"
197 else:
198 return "not needed"
199
200
201 @status("pyconfig.h.in regenerated", modal=True, info=str)
202 def regenerated_pyconfig_h_in(file_paths):
203 """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"
206 else:
207 return "not needed"
208
209
210 def main():
211 base_branch = get_base_branch()
212 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')}
216 # Docs updated.
217 docs_modified(has_doc_files)
218 # Misc/ACKS changed.
219 credit_given(misc_files)
220 # Misc/NEWS changed.
221 reported_news(misc_files)
222 # Regenerated configure, if necessary.
223 regenerated_configure(file_paths)
224 # Regenerated pyconfig.h.in, if necessary.
225 regenerated_pyconfig_h_in(file_paths)
226
227 # 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'))
230 print()
231 if has_c_files:
232 print("Did you run the test suite and check for refleaks?")
233 elif has_python_files:
234 print("Did you run the test suite?")
235
236
237 if __name__ == '__main__':
238 main()