blob: a1253d1de5bb352f357af958d3632cb738dbb3b9 [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:
51 return subprocess.check_output(cmd, stderr=subprocess.DEVNULL)
52 except subprocess.CalledProcessError:
53 return None
54
55
56def get_git_upstream_remote():
57 """Get the remote name to use for upstream branches
58
59 Uses "upstream" if it exists, "origin" otherwise
60 """
61 cmd = "git remote get-url upstream".split()
62 try:
63 subprocess.check_output(cmd, stderr=subprocess.DEVNULL)
64 except subprocess.CalledProcessError:
65 return "origin"
66 return "upstream"
67
68
69@status("Getting base branch for PR",
70 info=lambda x: x if x is not None else "not a PR branch")
71def get_base_branch():
Nick Coghlan2abfdf52017-04-09 18:33:03 +100072 if not os.path.exists(os.path.join(SRCDIR, '.git')):
Nick Coghlan482f7a22017-03-12 13:19:08 +100073 # Not a git checkout, so there's no base branch
74 return None
75 version = sys.version_info
76 if version.releaselevel == 'alpha':
77 base_branch = "master"
78 else:
79 base_branch = "{0.major}.{0.minor}".format(version)
80 this_branch = get_git_branch()
81 if this_branch is None or this_branch == base_branch:
82 # Not on a git PR branch, so there's no base branch
83 return None
84 upstream_remote = get_git_upstream_remote()
85 return upstream_remote + "/" + base_branch
86
87
Christian Heimesada8c3b2008-03-18 18:26:33 +000088@status("Getting the list of files that have been added/changed",
Georg Brandla9afb682010-10-21 12:49:28 +000089 info=lambda x: n_files_str(len(x)))
Nick Coghlan482f7a22017-03-12 13:19:08 +100090def changed_files(base_branch=None):
Benjamin Petersonb8c08452018-06-05 22:40:12 -070091 """Get the list of changed or added files from git."""
92 if os.path.exists(os.path.join(SRCDIR, '.git')):
Nick Coghlan6a6d0902017-03-12 19:37:09 +100093 # We just use an existence check here as:
94 # directory = normal git checkout/clone
95 # file = git worktree directory
Nick Coghlan482f7a22017-03-12 13:19:08 +100096 if base_branch:
97 cmd = 'git diff --name-status ' + base_branch
98 else:
99 cmd = 'git status --porcelain'
Christian Heimesd98c6772015-04-23 11:24:14 +0200100 filenames = []
101 with subprocess.Popen(cmd.split(), stdout=subprocess.PIPE) as st:
102 for line in st.stdout:
103 line = line.decode().rstrip()
Nick Coghlan482f7a22017-03-12 13:19:08 +1000104 status_text, filename = line.split(maxsplit=1)
105 status = set(status_text)
Christian Heimesd98c6772015-04-23 11:24:14 +0200106 # modified, added or unmerged files
107 if not status.intersection('MAU'):
108 continue
Christian Heimesd98c6772015-04-23 11:24:14 +0200109 if ' -> ' in filename:
110 # file is renamed
111 filename = filename.split(' -> ', 2)[1].strip()
112 filenames.append(filename)
Christian Heimesd98c6772015-04-23 11:24:14 +0200113 else:
Benjamin Petersonb8c08452018-06-05 22:40:12 -0700114 sys.exit('need a git checkout to get modified files')
Florent Xiclunae4a33802010-08-09 12:24:20 +0000115
Victor Stinner4a347ce2017-08-17 16:29:15 +0200116 filenames2 = []
117 for filename in filenames:
118 # Normalize the path to be able to match using .startswith()
119 filename = os.path.normpath(filename)
120 if any(filename.startswith(path) for path in EXCLUDE_DIRS):
121 # Exclude the file
122 continue
123 filenames2.append(filename)
124
125 return filenames2
126
Christian Heimesada8c3b2008-03-18 18:26:33 +0000127
Brett Cannon058173e2010-07-04 22:05:34 +0000128def report_modified_files(file_paths):
129 count = len(file_paths)
130 if count == 0:
131 return n_files_str(count)
132 else:
133 lines = ["{}:".format(n_files_str(count))]
134 for path in file_paths:
135 lines.append(" {}".format(path))
136 return "\n".join(lines)
137
Florent Xiclunae4a33802010-08-09 12:24:20 +0000138
Brett Cannon70cb1872017-06-24 16:51:23 -0700139@status("Fixing Python file whitespace", info=report_modified_files)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000140def normalize_whitespace(file_paths):
141 """Make sure that the whitespace for .py files have been normalized."""
142 reindent.makebackup = False # No need to create backups.
Benjamin Peterson4177eff2011-06-27 18:25:06 -0500143 fixed = [path for path in file_paths if path.endswith('.py') and
Éric Araujoad548b82011-07-31 18:33:00 +0200144 reindent.check(os.path.join(SRCDIR, path))]
Brett Cannon058173e2010-07-04 22:05:34 +0000145 return fixed
Christian Heimesada8c3b2008-03-18 18:26:33 +0000146
Florent Xiclunae4a33802010-08-09 12:24:20 +0000147
Georg Brandla9afb682010-10-21 12:49:28 +0000148@status("Fixing C file whitespace", info=report_modified_files)
149def normalize_c_whitespace(file_paths):
150 """Report if any C files """
151 fixed = []
152 for path in file_paths:
Éric Araujoa3e072b2011-07-30 21:34:04 +0200153 abspath = os.path.join(SRCDIR, path)
154 with open(abspath, 'r') as f:
Georg Brandla9afb682010-10-21 12:49:28 +0000155 if '\t' not in f.read():
156 continue
Éric Araujoa3e072b2011-07-30 21:34:04 +0200157 untabify.process(abspath, 8, verbose=False)
Georg Brandla9afb682010-10-21 12:49:28 +0000158 fixed.append(path)
159 return fixed
160
161
162ws_re = re.compile(br'\s+(\r?\n)$')
163
164@status("Fixing docs whitespace", info=report_modified_files)
165def normalize_docs_whitespace(file_paths):
166 fixed = []
167 for path in file_paths:
Éric Araujoa3e072b2011-07-30 21:34:04 +0200168 abspath = os.path.join(SRCDIR, path)
Georg Brandla9afb682010-10-21 12:49:28 +0000169 try:
Éric Araujoa3e072b2011-07-30 21:34:04 +0200170 with open(abspath, 'rb') as f:
Georg Brandla9afb682010-10-21 12:49:28 +0000171 lines = f.readlines()
172 new_lines = [ws_re.sub(br'\1', line) for line in lines]
173 if new_lines != lines:
Éric Araujoa3e072b2011-07-30 21:34:04 +0200174 shutil.copyfile(abspath, abspath + '.bak')
175 with open(abspath, 'wb') as f:
Georg Brandla9afb682010-10-21 12:49:28 +0000176 f.writelines(new_lines)
177 fixed.append(path)
178 except Exception as err:
179 print('Cannot fix %s: %s' % (path, err))
180 return fixed
181
182
Christian Heimesada8c3b2008-03-18 18:26:33 +0000183@status("Docs modified", modal=True)
184def docs_modified(file_paths):
Brett Cannon058173e2010-07-04 22:05:34 +0000185 """Report if any file in the Doc directory has been changed."""
186 return bool(file_paths)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000187
Florent Xiclunae4a33802010-08-09 12:24:20 +0000188
Christian Heimesada8c3b2008-03-18 18:26:33 +0000189@status("Misc/ACKS updated", modal=True)
190def credit_given(file_paths):
191 """Check if Misc/ACKS has been changed."""
Terry Jan Reedy6e2711b2013-07-21 20:57:44 -0400192 return os.path.join('Misc', 'ACKS') in file_paths
Christian Heimesada8c3b2008-03-18 18:26:33 +0000193
Florent Xiclunae4a33802010-08-09 12:24:20 +0000194
Antoine Pitrou1ba94692017-06-25 03:21:49 +0200195@status("Misc/NEWS.d updated with `blurb`", modal=True)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000196def reported_news(file_paths):
Antoine Pitrou1ba94692017-06-25 03:21:49 +0200197 """Check if Misc/NEWS.d has been changed."""
198 return any(p.startswith(os.path.join('Misc', 'NEWS.d', 'next'))
199 for p in file_paths)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000200
Ross Lagerwall6c52c572012-03-11 19:21:07 +0200201@status("configure regenerated", modal=True, info=str)
202def regenerated_configure(file_paths):
203 """Check if configure has been regenerated."""
Matthias Klose5ce31cc2012-03-14 23:17:31 +0100204 if 'configure.ac' in file_paths:
Ross Lagerwall6c52c572012-03-11 19:21:07 +0200205 return "yes" if 'configure' in file_paths else "no"
206 else:
207 return "not needed"
208
209@status("pyconfig.h.in regenerated", modal=True, info=str)
210def regenerated_pyconfig_h_in(file_paths):
211 """Check if pyconfig.h.in has been regenerated."""
Matthias Klose5ce31cc2012-03-14 23:17:31 +0100212 if 'configure.ac' in file_paths:
Ross Lagerwall6c52c572012-03-11 19:21:07 +0200213 return "yes" if 'pyconfig.h.in' in file_paths else "no"
214 else:
215 return "not needed"
Christian Heimesada8c3b2008-03-18 18:26:33 +0000216
Brett Cannon70cb1872017-06-24 16:51:23 -0700217def travis(pull_request):
218 if pull_request == 'false':
219 print('Not a pull request; skipping')
220 return
221 base_branch = get_base_branch()
222 file_paths = changed_files(base_branch)
223 python_files = [fn for fn in file_paths if fn.endswith('.py')]
224 c_files = [fn for fn in file_paths if fn.endswith(('.c', '.h'))]
225 doc_files = [fn for fn in file_paths if fn.startswith('Doc') and
226 fn.endswith(('.rst', '.inc'))]
227 fixed = []
228 fixed.extend(normalize_whitespace(python_files))
229 fixed.extend(normalize_c_whitespace(c_files))
230 fixed.extend(normalize_docs_whitespace(doc_files))
231 if not fixed:
232 print('No whitespace issues found')
233 else:
234 print(f'Please fix the {len(fixed)} file(s) with whitespace issues')
235 print('(on UNIX you can run `make patchcheck` to make the fixes)')
236 sys.exit(1)
237
Christian Heimesada8c3b2008-03-18 18:26:33 +0000238def main():
Nick Coghlan482f7a22017-03-12 13:19:08 +1000239 base_branch = get_base_branch()
240 file_paths = changed_files(base_branch)
Brett Cannon058173e2010-07-04 22:05:34 +0000241 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'))]
Georg Brandl24f07172014-10-19 11:54:08 +0200243 doc_files = [fn for fn in file_paths if fn.startswith('Doc') and
244 fn.endswith(('.rst', '.inc'))]
Antoine Pitrou1ba94692017-06-25 03:21:49 +0200245 misc_files = {p for p in file_paths if p.startswith('Misc')}
Brett Cannon058173e2010-07-04 22:05:34 +0000246 # PEP 8 whitespace rules enforcement.
247 normalize_whitespace(python_files)
Georg Brandla9afb682010-10-21 12:49:28 +0000248 # C rules enforcement.
249 normalize_c_whitespace(c_files)
250 # Doc whitespace enforcement.
251 normalize_docs_whitespace(doc_files)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000252 # Docs updated.
Georg Brandla9afb682010-10-21 12:49:28 +0000253 docs_modified(doc_files)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000254 # Misc/ACKS changed.
Terry Jan Reedy6e2711b2013-07-21 20:57:44 -0400255 credit_given(misc_files)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000256 # Misc/NEWS changed.
Terry Jan Reedy6e2711b2013-07-21 20:57:44 -0400257 reported_news(misc_files)
Ross Lagerwall6c52c572012-03-11 19:21:07 +0200258 # Regenerated configure, if necessary.
259 regenerated_configure(file_paths)
260 # Regenerated pyconfig.h.in, if necessary.
261 regenerated_pyconfig_h_in(file_paths)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000262
263 # Test suite run and passed.
Éric Araujofbc5ff62011-08-12 17:50:08 +0200264 if python_files or c_files:
Ezio Melotti5e12bb72013-01-11 14:07:47 +0200265 end = " and check for refleaks?" if c_files else "?"
Éric Araujofbc5ff62011-08-12 17:50:08 +0200266 print()
Ezio Melotti5e12bb72013-01-11 14:07:47 +0200267 print("Did you run the test suite" + end)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000268
269
270if __name__ == '__main__':
Brett Cannon70cb1872017-06-24 16:51:23 -0700271 import argparse
272 parser = argparse.ArgumentParser(description=__doc__)
273 parser.add_argument('--travis',
274 help='Perform pass/fail checks')
275 args = parser.parse_args()
276 if args.travis:
277 travis(args.travis)
278 else:
279 main()