blob: 8f7924fe934601a7cc35f910d024c26cd3403e38 [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
Nadeem Vawda9f64f732012-02-22 11:46:41 +020047def mq_patches_applied():
48 """Check if there are any applied MQ patches."""
49 cmd = 'hg qapplied'
50 with subprocess.Popen(cmd.split(),
51 stdout=subprocess.PIPE,
52 stderr=subprocess.PIPE) as st:
53 bstdout, _ = st.communicate()
54 return st.returncode == 0 and bstdout
55
56
Nick Coghlan482f7a22017-03-12 13:19:08 +100057def get_git_branch():
58 """Get the symbolic name for the current git branch"""
59 cmd = "git rev-parse --abbrev-ref HEAD".split()
60 try:
61 return subprocess.check_output(cmd, stderr=subprocess.DEVNULL)
62 except subprocess.CalledProcessError:
63 return None
64
65
66def get_git_upstream_remote():
67 """Get the remote name to use for upstream branches
68
69 Uses "upstream" if it exists, "origin" otherwise
70 """
71 cmd = "git remote get-url upstream".split()
72 try:
73 subprocess.check_output(cmd, stderr=subprocess.DEVNULL)
74 except subprocess.CalledProcessError:
75 return "origin"
76 return "upstream"
77
78
79@status("Getting base branch for PR",
80 info=lambda x: x if x is not None else "not a PR branch")
81def get_base_branch():
Nick Coghlan2abfdf52017-04-09 18:33:03 +100082 if not os.path.exists(os.path.join(SRCDIR, '.git')):
Nick Coghlan482f7a22017-03-12 13:19:08 +100083 # Not a git checkout, so there's no base branch
84 return None
85 version = sys.version_info
86 if version.releaselevel == 'alpha':
87 base_branch = "master"
88 else:
89 base_branch = "{0.major}.{0.minor}".format(version)
90 this_branch = get_git_branch()
91 if this_branch is None or this_branch == base_branch:
92 # Not on a git PR branch, so there's no base branch
93 return None
94 upstream_remote = get_git_upstream_remote()
95 return upstream_remote + "/" + base_branch
96
97
Christian Heimesada8c3b2008-03-18 18:26:33 +000098@status("Getting the list of files that have been added/changed",
Georg Brandla9afb682010-10-21 12:49:28 +000099 info=lambda x: n_files_str(len(x)))
Nick Coghlan482f7a22017-03-12 13:19:08 +1000100def changed_files(base_branch=None):
Christian Heimesd98c6772015-04-23 11:24:14 +0200101 """Get the list of changed or added files from Mercurial or git."""
102 if os.path.isdir(os.path.join(SRCDIR, '.hg')):
Nick Coghlan482f7a22017-03-12 13:19:08 +1000103 if base_branch is not None:
104 sys.exit('need a git checkout to check PR status')
Christian Heimesd98c6772015-04-23 11:24:14 +0200105 cmd = 'hg status --added --modified --no-status'
106 if mq_patches_applied():
107 cmd += ' --rev qparent'
108 with subprocess.Popen(cmd.split(), stdout=subprocess.PIPE) as st:
Victor Stinner4a347ce2017-08-17 16:29:15 +0200109 filenames = [x.decode().rstrip() for x in st.stdout]
Nick Coghlan6a6d0902017-03-12 19:37:09 +1000110 elif os.path.exists(os.path.join(SRCDIR, '.git')):
111 # We just use an existence check here as:
112 # directory = normal git checkout/clone
113 # file = git worktree directory
Nick Coghlan482f7a22017-03-12 13:19:08 +1000114 if base_branch:
115 cmd = 'git diff --name-status ' + base_branch
116 else:
117 cmd = 'git status --porcelain'
Christian Heimesd98c6772015-04-23 11:24:14 +0200118 filenames = []
119 with subprocess.Popen(cmd.split(), stdout=subprocess.PIPE) as st:
120 for line in st.stdout:
121 line = line.decode().rstrip()
Nick Coghlan482f7a22017-03-12 13:19:08 +1000122 status_text, filename = line.split(maxsplit=1)
123 status = set(status_text)
Christian Heimesd98c6772015-04-23 11:24:14 +0200124 # modified, added or unmerged files
125 if not status.intersection('MAU'):
126 continue
Christian Heimesd98c6772015-04-23 11:24:14 +0200127 if ' -> ' in filename:
128 # file is renamed
129 filename = filename.split(' -> ', 2)[1].strip()
130 filenames.append(filename)
Christian Heimesd98c6772015-04-23 11:24:14 +0200131 else:
132 sys.exit('need a Mercurial or git checkout to get modified files')
Florent Xiclunae4a33802010-08-09 12:24:20 +0000133
Victor Stinner4a347ce2017-08-17 16:29:15 +0200134 filenames2 = []
135 for filename in filenames:
136 # Normalize the path to be able to match using .startswith()
137 filename = os.path.normpath(filename)
138 if any(filename.startswith(path) for path in EXCLUDE_DIRS):
139 # Exclude the file
140 continue
141 filenames2.append(filename)
142
143 return filenames2
144
Christian Heimesada8c3b2008-03-18 18:26:33 +0000145
Brett Cannon058173e2010-07-04 22:05:34 +0000146def report_modified_files(file_paths):
147 count = len(file_paths)
148 if count == 0:
149 return n_files_str(count)
150 else:
151 lines = ["{}:".format(n_files_str(count))]
152 for path in file_paths:
153 lines.append(" {}".format(path))
154 return "\n".join(lines)
155
Florent Xiclunae4a33802010-08-09 12:24:20 +0000156
Brett Cannon70cb1872017-06-24 16:51:23 -0700157@status("Fixing Python file whitespace", info=report_modified_files)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000158def normalize_whitespace(file_paths):
159 """Make sure that the whitespace for .py files have been normalized."""
160 reindent.makebackup = False # No need to create backups.
Benjamin Peterson4177eff2011-06-27 18:25:06 -0500161 fixed = [path for path in file_paths if path.endswith('.py') and
Éric Araujoad548b82011-07-31 18:33:00 +0200162 reindent.check(os.path.join(SRCDIR, path))]
Brett Cannon058173e2010-07-04 22:05:34 +0000163 return fixed
Christian Heimesada8c3b2008-03-18 18:26:33 +0000164
Florent Xiclunae4a33802010-08-09 12:24:20 +0000165
Georg Brandla9afb682010-10-21 12:49:28 +0000166@status("Fixing C file whitespace", info=report_modified_files)
167def normalize_c_whitespace(file_paths):
168 """Report if any C files """
169 fixed = []
170 for path in file_paths:
Éric Araujoa3e072b2011-07-30 21:34:04 +0200171 abspath = os.path.join(SRCDIR, path)
172 with open(abspath, 'r') as f:
Georg Brandla9afb682010-10-21 12:49:28 +0000173 if '\t' not in f.read():
174 continue
Éric Araujoa3e072b2011-07-30 21:34:04 +0200175 untabify.process(abspath, 8, verbose=False)
Georg Brandla9afb682010-10-21 12:49:28 +0000176 fixed.append(path)
177 return fixed
178
179
180ws_re = re.compile(br'\s+(\r?\n)$')
181
182@status("Fixing docs whitespace", info=report_modified_files)
183def normalize_docs_whitespace(file_paths):
184 fixed = []
185 for path in file_paths:
Éric Araujoa3e072b2011-07-30 21:34:04 +0200186 abspath = os.path.join(SRCDIR, path)
Georg Brandla9afb682010-10-21 12:49:28 +0000187 try:
Éric Araujoa3e072b2011-07-30 21:34:04 +0200188 with open(abspath, 'rb') as f:
Georg Brandla9afb682010-10-21 12:49:28 +0000189 lines = f.readlines()
190 new_lines = [ws_re.sub(br'\1', line) for line in lines]
191 if new_lines != lines:
Éric Araujoa3e072b2011-07-30 21:34:04 +0200192 shutil.copyfile(abspath, abspath + '.bak')
193 with open(abspath, 'wb') as f:
Georg Brandla9afb682010-10-21 12:49:28 +0000194 f.writelines(new_lines)
195 fixed.append(path)
196 except Exception as err:
197 print('Cannot fix %s: %s' % (path, err))
198 return fixed
199
200
Christian Heimesada8c3b2008-03-18 18:26:33 +0000201@status("Docs modified", modal=True)
202def docs_modified(file_paths):
Brett Cannon058173e2010-07-04 22:05:34 +0000203 """Report if any file in the Doc directory has been changed."""
204 return bool(file_paths)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000205
Florent Xiclunae4a33802010-08-09 12:24:20 +0000206
Christian Heimesada8c3b2008-03-18 18:26:33 +0000207@status("Misc/ACKS updated", modal=True)
208def credit_given(file_paths):
209 """Check if Misc/ACKS has been changed."""
Terry Jan Reedy6e2711b2013-07-21 20:57:44 -0400210 return os.path.join('Misc', 'ACKS') in file_paths
Christian Heimesada8c3b2008-03-18 18:26:33 +0000211
Florent Xiclunae4a33802010-08-09 12:24:20 +0000212
Antoine Pitrou1ba94692017-06-25 03:21:49 +0200213@status("Misc/NEWS.d updated with `blurb`", modal=True)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000214def reported_news(file_paths):
Antoine Pitrou1ba94692017-06-25 03:21:49 +0200215 """Check if Misc/NEWS.d has been changed."""
216 return any(p.startswith(os.path.join('Misc', 'NEWS.d', 'next'))
217 for p in file_paths)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000218
Ross Lagerwall6c52c572012-03-11 19:21:07 +0200219@status("configure regenerated", modal=True, info=str)
220def regenerated_configure(file_paths):
221 """Check if configure has been regenerated."""
Matthias Klose5ce31cc2012-03-14 23:17:31 +0100222 if 'configure.ac' in file_paths:
Ross Lagerwall6c52c572012-03-11 19:21:07 +0200223 return "yes" if 'configure' in file_paths else "no"
224 else:
225 return "not needed"
226
227@status("pyconfig.h.in regenerated", modal=True, info=str)
228def regenerated_pyconfig_h_in(file_paths):
229 """Check if pyconfig.h.in has been regenerated."""
Matthias Klose5ce31cc2012-03-14 23:17:31 +0100230 if 'configure.ac' in file_paths:
Ross Lagerwall6c52c572012-03-11 19:21:07 +0200231 return "yes" if 'pyconfig.h.in' in file_paths else "no"
232 else:
233 return "not needed"
Christian Heimesada8c3b2008-03-18 18:26:33 +0000234
Brett Cannon70cb1872017-06-24 16:51:23 -0700235def travis(pull_request):
236 if pull_request == 'false':
237 print('Not a pull request; skipping')
238 return
239 base_branch = get_base_branch()
240 file_paths = changed_files(base_branch)
241 python_files = [fn for fn in file_paths if fn.endswith('.py')]
242 c_files = [fn for fn in file_paths if fn.endswith(('.c', '.h'))]
243 doc_files = [fn for fn in file_paths if fn.startswith('Doc') and
244 fn.endswith(('.rst', '.inc'))]
245 fixed = []
246 fixed.extend(normalize_whitespace(python_files))
247 fixed.extend(normalize_c_whitespace(c_files))
248 fixed.extend(normalize_docs_whitespace(doc_files))
249 if not fixed:
250 print('No whitespace issues found')
251 else:
252 print(f'Please fix the {len(fixed)} file(s) with whitespace issues')
253 print('(on UNIX you can run `make patchcheck` to make the fixes)')
254 sys.exit(1)
255
Christian Heimesada8c3b2008-03-18 18:26:33 +0000256def main():
Nick Coghlan482f7a22017-03-12 13:19:08 +1000257 base_branch = get_base_branch()
258 file_paths = changed_files(base_branch)
Brett Cannon058173e2010-07-04 22:05:34 +0000259 python_files = [fn for fn in file_paths if fn.endswith('.py')]
260 c_files = [fn for fn in file_paths if fn.endswith(('.c', '.h'))]
Georg Brandl24f07172014-10-19 11:54:08 +0200261 doc_files = [fn for fn in file_paths if fn.startswith('Doc') and
262 fn.endswith(('.rst', '.inc'))]
Antoine Pitrou1ba94692017-06-25 03:21:49 +0200263 misc_files = {p for p in file_paths if p.startswith('Misc')}
Brett Cannon058173e2010-07-04 22:05:34 +0000264 # PEP 8 whitespace rules enforcement.
265 normalize_whitespace(python_files)
Georg Brandla9afb682010-10-21 12:49:28 +0000266 # C rules enforcement.
267 normalize_c_whitespace(c_files)
268 # Doc whitespace enforcement.
269 normalize_docs_whitespace(doc_files)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000270 # Docs updated.
Georg Brandla9afb682010-10-21 12:49:28 +0000271 docs_modified(doc_files)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000272 # Misc/ACKS changed.
Terry Jan Reedy6e2711b2013-07-21 20:57:44 -0400273 credit_given(misc_files)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000274 # Misc/NEWS changed.
Terry Jan Reedy6e2711b2013-07-21 20:57:44 -0400275 reported_news(misc_files)
Ross Lagerwall6c52c572012-03-11 19:21:07 +0200276 # Regenerated configure, if necessary.
277 regenerated_configure(file_paths)
278 # Regenerated pyconfig.h.in, if necessary.
279 regenerated_pyconfig_h_in(file_paths)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000280
281 # Test suite run and passed.
Éric Araujofbc5ff62011-08-12 17:50:08 +0200282 if python_files or c_files:
Ezio Melotti5e12bb72013-01-11 14:07:47 +0200283 end = " and check for refleaks?" if c_files else "?"
Éric Araujofbc5ff62011-08-12 17:50:08 +0200284 print()
Ezio Melotti5e12bb72013-01-11 14:07:47 +0200285 print("Did you run the test suite" + end)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000286
287
288if __name__ == '__main__':
Brett Cannon70cb1872017-06-24 16:51:23 -0700289 import argparse
290 parser = argparse.ArgumentParser(description=__doc__)
291 parser.add_argument('--travis',
292 help='Perform pass/fail checks')
293 args = parser.parse_args()
294 if args.travis:
295 travis(args.travis)
296 else:
297 main()