blob: d9cceb5d5acdfd3d9b251061d55e4c40e1caf5b4 [file] [log] [blame]
Éric Araujoa0e92a82011-07-26 18:01:08 +02001#!/usr/bin/env python3
Brett Cannon70cb1872017-06-24 16:51:23 -07002"""Check proposed changes for common issues."""
Georg Brandla9afb682010-10-21 12:49:28 +00003import re
4import sys
5import shutil
Christian Heimesada8c3b2008-03-18 18:26:33 +00006import os.path
7import subprocess
Éric Araujoa3e072b2011-07-30 21:34:04 +02008import sysconfig
Christian Heimesada8c3b2008-03-18 18:26:33 +00009
10import reindent
Georg Brandla9afb682010-10-21 12:49:28 +000011import untabify
Christian Heimesada8c3b2008-03-18 18:26:33 +000012
13
Victor Stinner4a347ce2017-08-17 16:29:15 +020014# Excluded directories which are copies of external libraries:
15# don't check their coding style
16EXCLUDE_DIRS = [os.path.join('Modules', '_ctypes', 'libffi_osx'),
17 os.path.join('Modules', '_ctypes', 'libffi_msvc'),
18 os.path.join('Modules', '_decimal', 'libmpdec'),
19 os.path.join('Modules', 'expat'),
20 os.path.join('Modules', 'zlib')]
Éric Araujoa3e072b2011-07-30 21:34:04 +020021SRCDIR = sysconfig.get_config_var('srcdir')
22
Victor Stinner4a347ce2017-08-17 16:29:15 +020023
Brett Cannon058173e2010-07-04 22:05:34 +000024def n_files_str(count):
25 """Return 'N file(s)' with the proper plurality on 'file'."""
26 return "{} file{}".format(count, "s" if count != 1 else "")
27
Florent Xiclunae4a33802010-08-09 12:24:20 +000028
Christian Heimesada8c3b2008-03-18 18:26:33 +000029def status(message, modal=False, info=None):
30 """Decorator to output status info to stdout."""
31 def decorated_fxn(fxn):
32 def call_fxn(*args, **kwargs):
33 sys.stdout.write(message + ' ... ')
34 sys.stdout.flush()
35 result = fxn(*args, **kwargs)
36 if not modal and not info:
37 print("done")
38 elif info:
39 print(info(result))
40 else:
Florent Xiclunae4a33802010-08-09 12:24:20 +000041 print("yes" if result else "NO")
Christian Heimesada8c3b2008-03-18 18:26:33 +000042 return result
43 return call_fxn
44 return decorated_fxn
45
Florent Xiclunae4a33802010-08-09 12:24:20 +000046
Nick Coghlan482f7a22017-03-12 13:19:08 +100047def get_git_branch():
48 """Get the symbolic name for the current git branch"""
49 cmd = "git rev-parse --abbrev-ref HEAD".split()
50 try:
Alexey Izbyshevaa95bfb2018-10-20 03:49:41 +030051 return subprocess.check_output(cmd,
52 stderr=subprocess.DEVNULL,
Miss Islington (bot)4cc83692021-05-10 11:58:42 -070053 cwd=SRCDIR,
54 encoding='UTF-8')
Nick Coghlan482f7a22017-03-12 13:19:08 +100055 except subprocess.CalledProcessError:
56 return None
57
58
59def get_git_upstream_remote():
60 """Get the remote name to use for upstream branches
61
62 Uses "upstream" if it exists, "origin" otherwise
63 """
64 cmd = "git remote get-url upstream".split()
65 try:
Alexey Izbyshevaa95bfb2018-10-20 03:49:41 +030066 subprocess.check_output(cmd,
67 stderr=subprocess.DEVNULL,
Miss Islington (bot)4cc83692021-05-10 11:58:42 -070068 cwd=SRCDIR,
69 encoding='UTF-8')
Nick Coghlan482f7a22017-03-12 13:19:08 +100070 except subprocess.CalledProcessError:
71 return "origin"
72 return "upstream"
73
74
Miss Islington (bot)4cc83692021-05-10 11:58:42 -070075def get_git_remote_default_branch(remote_name):
76 """Get the name of the default branch for the given remote
77
78 It is typically called 'main', but may differ
79 """
80 cmd = "git remote show {}".format(remote_name).split()
81 try:
82 remote_info = subprocess.check_output(cmd,
83 stderr=subprocess.DEVNULL,
84 cwd=SRCDIR,
85 encoding='UTF-8')
86 except subprocess.CalledProcessError:
87 return None
88 for line in remote_info.splitlines():
89 if "HEAD branch:" in line:
90 base_branch = line.split(":")[1].strip()
91 return base_branch
92 return None
93
94
Nick Coghlan482f7a22017-03-12 13:19:08 +100095@status("Getting base branch for PR",
96 info=lambda x: x if x is not None else "not a PR branch")
97def get_base_branch():
Nick Coghlan2abfdf52017-04-09 18:33:03 +100098 if not os.path.exists(os.path.join(SRCDIR, '.git')):
Nick Coghlan482f7a22017-03-12 13:19:08 +100099 # Not a git checkout, so there's no base branch
100 return None
Miss Islington (bot)4cc83692021-05-10 11:58:42 -0700101 upstream_remote = get_git_upstream_remote()
Nick Coghlan482f7a22017-03-12 13:19:08 +1000102 version = sys.version_info
103 if version.releaselevel == 'alpha':
Miss Islington (bot)4cc83692021-05-10 11:58:42 -0700104 base_branch = get_git_remote_default_branch(upstream_remote)
Nick Coghlan482f7a22017-03-12 13:19:08 +1000105 else:
106 base_branch = "{0.major}.{0.minor}".format(version)
107 this_branch = get_git_branch()
108 if this_branch is None or this_branch == base_branch:
109 # Not on a git PR branch, so there's no base branch
110 return None
Nick Coghlan482f7a22017-03-12 13:19:08 +1000111 return upstream_remote + "/" + base_branch
112
113
Christian Heimesada8c3b2008-03-18 18:26:33 +0000114@status("Getting the list of files that have been added/changed",
Georg Brandla9afb682010-10-21 12:49:28 +0000115 info=lambda x: n_files_str(len(x)))
Nick Coghlan482f7a22017-03-12 13:19:08 +1000116def changed_files(base_branch=None):
Benjamin Petersonb8c08452018-06-05 22:40:12 -0700117 """Get the list of changed or added files from git."""
118 if os.path.exists(os.path.join(SRCDIR, '.git')):
Nick Coghlan6a6d0902017-03-12 19:37:09 +1000119 # We just use an existence check here as:
120 # directory = normal git checkout/clone
121 # file = git worktree directory
Nick Coghlan482f7a22017-03-12 13:19:08 +1000122 if base_branch:
123 cmd = 'git diff --name-status ' + base_branch
124 else:
125 cmd = 'git status --porcelain'
Christian Heimesd98c6772015-04-23 11:24:14 +0200126 filenames = []
Alexey Izbyshevaa95bfb2018-10-20 03:49:41 +0300127 with subprocess.Popen(cmd.split(),
128 stdout=subprocess.PIPE,
129 cwd=SRCDIR) as st:
Christian Heimesd98c6772015-04-23 11:24:14 +0200130 for line in st.stdout:
131 line = line.decode().rstrip()
Nick Coghlan482f7a22017-03-12 13:19:08 +1000132 status_text, filename = line.split(maxsplit=1)
133 status = set(status_text)
Christian Heimesd98c6772015-04-23 11:24:14 +0200134 # modified, added or unmerged files
135 if not status.intersection('MAU'):
136 continue
Christian Heimesd98c6772015-04-23 11:24:14 +0200137 if ' -> ' in filename:
138 # file is renamed
139 filename = filename.split(' -> ', 2)[1].strip()
140 filenames.append(filename)
Christian Heimesd98c6772015-04-23 11:24:14 +0200141 else:
Benjamin Petersonb8c08452018-06-05 22:40:12 -0700142 sys.exit('need a git checkout to get modified files')
Florent Xiclunae4a33802010-08-09 12:24:20 +0000143
Victor Stinner4a347ce2017-08-17 16:29:15 +0200144 filenames2 = []
145 for filename in filenames:
146 # Normalize the path to be able to match using .startswith()
147 filename = os.path.normpath(filename)
148 if any(filename.startswith(path) for path in EXCLUDE_DIRS):
149 # Exclude the file
150 continue
151 filenames2.append(filename)
152
153 return filenames2
154
Christian Heimesada8c3b2008-03-18 18:26:33 +0000155
Brett Cannon058173e2010-07-04 22:05:34 +0000156def report_modified_files(file_paths):
157 count = len(file_paths)
158 if count == 0:
159 return n_files_str(count)
160 else:
161 lines = ["{}:".format(n_files_str(count))]
162 for path in file_paths:
163 lines.append(" {}".format(path))
164 return "\n".join(lines)
165
Florent Xiclunae4a33802010-08-09 12:24:20 +0000166
Brett Cannon70cb1872017-06-24 16:51:23 -0700167@status("Fixing Python file whitespace", info=report_modified_files)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000168def normalize_whitespace(file_paths):
169 """Make sure that the whitespace for .py files have been normalized."""
170 reindent.makebackup = False # No need to create backups.
Benjamin Peterson4177eff2011-06-27 18:25:06 -0500171 fixed = [path for path in file_paths if path.endswith('.py') and
Éric Araujoad548b82011-07-31 18:33:00 +0200172 reindent.check(os.path.join(SRCDIR, path))]
Brett Cannon058173e2010-07-04 22:05:34 +0000173 return fixed
Christian Heimesada8c3b2008-03-18 18:26:33 +0000174
Florent Xiclunae4a33802010-08-09 12:24:20 +0000175
Georg Brandla9afb682010-10-21 12:49:28 +0000176@status("Fixing C file whitespace", info=report_modified_files)
177def normalize_c_whitespace(file_paths):
178 """Report if any C files """
179 fixed = []
180 for path in file_paths:
Éric Araujoa3e072b2011-07-30 21:34:04 +0200181 abspath = os.path.join(SRCDIR, path)
182 with open(abspath, 'r') as f:
Georg Brandla9afb682010-10-21 12:49:28 +0000183 if '\t' not in f.read():
184 continue
Éric Araujoa3e072b2011-07-30 21:34:04 +0200185 untabify.process(abspath, 8, verbose=False)
Georg Brandla9afb682010-10-21 12:49:28 +0000186 fixed.append(path)
187 return fixed
188
189
190ws_re = re.compile(br'\s+(\r?\n)$')
191
192@status("Fixing docs whitespace", info=report_modified_files)
193def normalize_docs_whitespace(file_paths):
194 fixed = []
195 for path in file_paths:
Éric Araujoa3e072b2011-07-30 21:34:04 +0200196 abspath = os.path.join(SRCDIR, path)
Georg Brandla9afb682010-10-21 12:49:28 +0000197 try:
Éric Araujoa3e072b2011-07-30 21:34:04 +0200198 with open(abspath, 'rb') as f:
Georg Brandla9afb682010-10-21 12:49:28 +0000199 lines = f.readlines()
200 new_lines = [ws_re.sub(br'\1', line) for line in lines]
201 if new_lines != lines:
Éric Araujoa3e072b2011-07-30 21:34:04 +0200202 shutil.copyfile(abspath, abspath + '.bak')
203 with open(abspath, 'wb') as f:
Georg Brandla9afb682010-10-21 12:49:28 +0000204 f.writelines(new_lines)
205 fixed.append(path)
206 except Exception as err:
207 print('Cannot fix %s: %s' % (path, err))
208 return fixed
209
210
Christian Heimesada8c3b2008-03-18 18:26:33 +0000211@status("Docs modified", modal=True)
212def docs_modified(file_paths):
Brett Cannon058173e2010-07-04 22:05:34 +0000213 """Report if any file in the Doc directory has been changed."""
214 return bool(file_paths)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000215
Florent Xiclunae4a33802010-08-09 12:24:20 +0000216
Christian Heimesada8c3b2008-03-18 18:26:33 +0000217@status("Misc/ACKS updated", modal=True)
218def credit_given(file_paths):
219 """Check if Misc/ACKS has been changed."""
Terry Jan Reedy6e2711b2013-07-21 20:57:44 -0400220 return os.path.join('Misc', 'ACKS') in file_paths
Christian Heimesada8c3b2008-03-18 18:26:33 +0000221
Florent Xiclunae4a33802010-08-09 12:24:20 +0000222
Antoine Pitrou1ba94692017-06-25 03:21:49 +0200223@status("Misc/NEWS.d updated with `blurb`", modal=True)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000224def reported_news(file_paths):
Antoine Pitrou1ba94692017-06-25 03:21:49 +0200225 """Check if Misc/NEWS.d has been changed."""
226 return any(p.startswith(os.path.join('Misc', 'NEWS.d', 'next'))
227 for p in file_paths)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000228
Ross Lagerwall6c52c572012-03-11 19:21:07 +0200229@status("configure regenerated", modal=True, info=str)
230def regenerated_configure(file_paths):
231 """Check if configure has been regenerated."""
Matthias Klose5ce31cc2012-03-14 23:17:31 +0100232 if 'configure.ac' in file_paths:
Ross Lagerwall6c52c572012-03-11 19:21:07 +0200233 return "yes" if 'configure' in file_paths else "no"
234 else:
235 return "not needed"
236
237@status("pyconfig.h.in regenerated", modal=True, info=str)
238def regenerated_pyconfig_h_in(file_paths):
239 """Check if pyconfig.h.in has been regenerated."""
Matthias Klose5ce31cc2012-03-14 23:17:31 +0100240 if 'configure.ac' in file_paths:
Ross Lagerwall6c52c572012-03-11 19:21:07 +0200241 return "yes" if 'pyconfig.h.in' in file_paths else "no"
242 else:
243 return "not needed"
Christian Heimesada8c3b2008-03-18 18:26:33 +0000244
Brett Cannon70cb1872017-06-24 16:51:23 -0700245def travis(pull_request):
246 if pull_request == 'false':
247 print('Not a pull request; skipping')
248 return
249 base_branch = get_base_branch()
250 file_paths = changed_files(base_branch)
251 python_files = [fn for fn in file_paths if fn.endswith('.py')]
252 c_files = [fn for fn in file_paths if fn.endswith(('.c', '.h'))]
253 doc_files = [fn for fn in file_paths if fn.startswith('Doc') and
254 fn.endswith(('.rst', '.inc'))]
255 fixed = []
256 fixed.extend(normalize_whitespace(python_files))
257 fixed.extend(normalize_c_whitespace(c_files))
258 fixed.extend(normalize_docs_whitespace(doc_files))
259 if not fixed:
260 print('No whitespace issues found')
261 else:
262 print(f'Please fix the {len(fixed)} file(s) with whitespace issues')
263 print('(on UNIX you can run `make patchcheck` to make the fixes)')
264 sys.exit(1)
265
Christian Heimesada8c3b2008-03-18 18:26:33 +0000266def main():
Nick Coghlan482f7a22017-03-12 13:19:08 +1000267 base_branch = get_base_branch()
268 file_paths = changed_files(base_branch)
Brett Cannon058173e2010-07-04 22:05:34 +0000269 python_files = [fn for fn in file_paths if fn.endswith('.py')]
270 c_files = [fn for fn in file_paths if fn.endswith(('.c', '.h'))]
Georg Brandl24f07172014-10-19 11:54:08 +0200271 doc_files = [fn for fn in file_paths if fn.startswith('Doc') and
272 fn.endswith(('.rst', '.inc'))]
Antoine Pitrou1ba94692017-06-25 03:21:49 +0200273 misc_files = {p for p in file_paths if p.startswith('Misc')}
Brett Cannon058173e2010-07-04 22:05:34 +0000274 # PEP 8 whitespace rules enforcement.
275 normalize_whitespace(python_files)
Georg Brandla9afb682010-10-21 12:49:28 +0000276 # C rules enforcement.
277 normalize_c_whitespace(c_files)
278 # Doc whitespace enforcement.
279 normalize_docs_whitespace(doc_files)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000280 # Docs updated.
Georg Brandla9afb682010-10-21 12:49:28 +0000281 docs_modified(doc_files)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000282 # Misc/ACKS changed.
Terry Jan Reedy6e2711b2013-07-21 20:57:44 -0400283 credit_given(misc_files)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000284 # Misc/NEWS changed.
Terry Jan Reedy6e2711b2013-07-21 20:57:44 -0400285 reported_news(misc_files)
Ross Lagerwall6c52c572012-03-11 19:21:07 +0200286 # Regenerated configure, if necessary.
287 regenerated_configure(file_paths)
288 # Regenerated pyconfig.h.in, if necessary.
289 regenerated_pyconfig_h_in(file_paths)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000290
291 # Test suite run and passed.
Éric Araujofbc5ff62011-08-12 17:50:08 +0200292 if python_files or c_files:
Ezio Melotti5e12bb72013-01-11 14:07:47 +0200293 end = " and check for refleaks?" if c_files else "?"
Éric Araujofbc5ff62011-08-12 17:50:08 +0200294 print()
Ezio Melotti5e12bb72013-01-11 14:07:47 +0200295 print("Did you run the test suite" + end)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000296
297
298if __name__ == '__main__':
Brett Cannon70cb1872017-06-24 16:51:23 -0700299 import argparse
300 parser = argparse.ArgumentParser(description=__doc__)
301 parser.add_argument('--travis',
302 help='Perform pass/fail checks')
303 args = parser.parse_args()
304 if args.travis:
305 travis(args.travis)
306 else:
307 main()