blob: 7a04aafa82a8a18c95f5772dec54ea66a9215aac [file] [log] [blame]
Éric Araujoa0e92a82011-07-26 18:01:08 +02001#!/usr/bin/env python3
Georg Brandla9afb682010-10-21 12:49:28 +00002import re
3import sys
4import shutil
Christian Heimesada8c3b2008-03-18 18:26:33 +00005import os.path
6import subprocess
Éric Araujoa3e072b2011-07-30 21:34:04 +02007import sysconfig
Christian Heimesada8c3b2008-03-18 18:26:33 +00008
9import reindent
Georg Brandla9afb682010-10-21 12:49:28 +000010import untabify
Christian Heimesada8c3b2008-03-18 18:26:33 +000011
12
Éric Araujoa3e072b2011-07-30 21:34:04 +020013SRCDIR = sysconfig.get_config_var('srcdir')
14
Brett Cannon058173e2010-07-04 22:05:34 +000015def n_files_str(count):
16 """Return 'N file(s)' with the proper plurality on 'file'."""
17 return "{} file{}".format(count, "s" if count != 1 else "")
18
Florent Xiclunae4a33802010-08-09 12:24:20 +000019
Christian Heimesada8c3b2008-03-18 18:26:33 +000020def status(message, modal=False, info=None):
21 """Decorator to output status info to stdout."""
22 def decorated_fxn(fxn):
23 def call_fxn(*args, **kwargs):
24 sys.stdout.write(message + ' ... ')
25 sys.stdout.flush()
26 result = fxn(*args, **kwargs)
27 if not modal and not info:
28 print("done")
29 elif info:
30 print(info(result))
31 else:
Florent Xiclunae4a33802010-08-09 12:24:20 +000032 print("yes" if result else "NO")
Christian Heimesada8c3b2008-03-18 18:26:33 +000033 return result
34 return call_fxn
35 return decorated_fxn
36
Florent Xiclunae4a33802010-08-09 12:24:20 +000037
Nadeem Vawda9f64f732012-02-22 11:46:41 +020038def mq_patches_applied():
39 """Check if there are any applied MQ patches."""
40 cmd = 'hg qapplied'
41 with subprocess.Popen(cmd.split(),
42 stdout=subprocess.PIPE,
43 stderr=subprocess.PIPE) as st:
44 bstdout, _ = st.communicate()
45 return st.returncode == 0 and bstdout
46
47
Nick Coghlan2f386252017-03-12 16:17:46 +100048def get_git_branch():
49 """Get the symbolic name for the current git branch"""
50 cmd = "git rev-parse --abbrev-ref HEAD".split()
51 try:
52 return subprocess.check_output(cmd, stderr=subprocess.DEVNULL)
53 except subprocess.CalledProcessError:
54 return None
55
56
57def get_git_upstream_remote():
58 """Get the remote name to use for upstream branches
59
60 Uses "upstream" if it exists, "origin" otherwise
61 """
62 cmd = "git remote get-url upstream".split()
63 try:
64 subprocess.check_output(cmd, stderr=subprocess.DEVNULL)
65 except subprocess.CalledProcessError:
66 return "origin"
67 return "upstream"
68
69
70@status("Getting base branch for PR",
71 info=lambda x: x if x is not None else "not a PR branch")
72def get_base_branch():
73 if not os.path.isdir(os.path.join(SRCDIR, '.git')):
74 # Not a git checkout, so there's no base branch
75 return None
76 version = sys.version_info
77 if version.releaselevel == 'alpha':
78 base_branch = "master"
79 else:
80 base_branch = "{0.major}.{0.minor}".format(version)
81 this_branch = get_git_branch()
82 if this_branch is None or this_branch == base_branch:
83 # Not on a git PR branch, so there's no base branch
84 return None
85 upstream_remote = get_git_upstream_remote()
86 return upstream_remote + "/" + base_branch
87
88
Christian Heimesada8c3b2008-03-18 18:26:33 +000089@status("Getting the list of files that have been added/changed",
Georg Brandla9afb682010-10-21 12:49:28 +000090 info=lambda x: n_files_str(len(x)))
Nick Coghlan2f386252017-03-12 16:17:46 +100091def changed_files(base_branch=None):
Christian Heimesd98c6772015-04-23 11:24:14 +020092 """Get the list of changed or added files from Mercurial or git."""
93 if os.path.isdir(os.path.join(SRCDIR, '.hg')):
Nick Coghlan2f386252017-03-12 16:17:46 +100094 if base_branch is not None:
95 sys.exit('need a git checkout to check PR status')
Christian Heimesd98c6772015-04-23 11:24:14 +020096 cmd = 'hg status --added --modified --no-status'
97 if mq_patches_applied():
98 cmd += ' --rev qparent'
99 with subprocess.Popen(cmd.split(), stdout=subprocess.PIPE) as st:
100 return [x.decode().rstrip() for x in st.stdout]
101 elif os.path.isdir(os.path.join(SRCDIR, '.git')):
Nick Coghlan2f386252017-03-12 16:17:46 +1000102 if base_branch:
103 cmd = 'git diff --name-status ' + base_branch
104 else:
105 cmd = 'git status --porcelain'
Christian Heimesd98c6772015-04-23 11:24:14 +0200106 filenames = []
107 with subprocess.Popen(cmd.split(), stdout=subprocess.PIPE) as st:
108 for line in st.stdout:
109 line = line.decode().rstrip()
Nick Coghlan2f386252017-03-12 16:17:46 +1000110 status_text, filename = line.split(maxsplit=1)
111 status = set(status_text)
Christian Heimesd98c6772015-04-23 11:24:14 +0200112 # modified, added or unmerged files
113 if not status.intersection('MAU'):
114 continue
Christian Heimesd98c6772015-04-23 11:24:14 +0200115 if ' -> ' in filename:
116 # file is renamed
117 filename = filename.split(' -> ', 2)[1].strip()
118 filenames.append(filename)
119 return filenames
120 else:
121 sys.exit('need a Mercurial or git checkout to get modified files')
Florent Xiclunae4a33802010-08-09 12:24:20 +0000122
Christian Heimesada8c3b2008-03-18 18:26:33 +0000123
Brett Cannon058173e2010-07-04 22:05:34 +0000124def report_modified_files(file_paths):
125 count = len(file_paths)
126 if count == 0:
127 return n_files_str(count)
128 else:
129 lines = ["{}:".format(n_files_str(count))]
130 for path in file_paths:
131 lines.append(" {}".format(path))
132 return "\n".join(lines)
133
Florent Xiclunae4a33802010-08-09 12:24:20 +0000134
Brett Cannon058173e2010-07-04 22:05:34 +0000135@status("Fixing whitespace", info=report_modified_files)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000136def normalize_whitespace(file_paths):
137 """Make sure that the whitespace for .py files have been normalized."""
138 reindent.makebackup = False # No need to create backups.
Benjamin Peterson4177eff2011-06-27 18:25:06 -0500139 fixed = [path for path in file_paths if path.endswith('.py') and
Éric Araujoad548b82011-07-31 18:33:00 +0200140 reindent.check(os.path.join(SRCDIR, path))]
Brett Cannon058173e2010-07-04 22:05:34 +0000141 return fixed
Christian Heimesada8c3b2008-03-18 18:26:33 +0000142
Florent Xiclunae4a33802010-08-09 12:24:20 +0000143
Georg Brandla9afb682010-10-21 12:49:28 +0000144@status("Fixing C file whitespace", info=report_modified_files)
145def normalize_c_whitespace(file_paths):
146 """Report if any C files """
147 fixed = []
148 for path in file_paths:
Éric Araujoa3e072b2011-07-30 21:34:04 +0200149 abspath = os.path.join(SRCDIR, path)
150 with open(abspath, 'r') as f:
Georg Brandla9afb682010-10-21 12:49:28 +0000151 if '\t' not in f.read():
152 continue
Éric Araujoa3e072b2011-07-30 21:34:04 +0200153 untabify.process(abspath, 8, verbose=False)
Georg Brandla9afb682010-10-21 12:49:28 +0000154 fixed.append(path)
155 return fixed
156
157
158ws_re = re.compile(br'\s+(\r?\n)$')
159
160@status("Fixing docs whitespace", info=report_modified_files)
161def normalize_docs_whitespace(file_paths):
162 fixed = []
163 for path in file_paths:
Éric Araujoa3e072b2011-07-30 21:34:04 +0200164 abspath = os.path.join(SRCDIR, path)
Georg Brandla9afb682010-10-21 12:49:28 +0000165 try:
Éric Araujoa3e072b2011-07-30 21:34:04 +0200166 with open(abspath, 'rb') as f:
Georg Brandla9afb682010-10-21 12:49:28 +0000167 lines = f.readlines()
168 new_lines = [ws_re.sub(br'\1', line) for line in lines]
169 if new_lines != lines:
Éric Araujoa3e072b2011-07-30 21:34:04 +0200170 shutil.copyfile(abspath, abspath + '.bak')
171 with open(abspath, 'wb') as f:
Georg Brandla9afb682010-10-21 12:49:28 +0000172 f.writelines(new_lines)
173 fixed.append(path)
174 except Exception as err:
175 print('Cannot fix %s: %s' % (path, err))
176 return fixed
177
178
Christian Heimesada8c3b2008-03-18 18:26:33 +0000179@status("Docs modified", modal=True)
180def docs_modified(file_paths):
Brett Cannon058173e2010-07-04 22:05:34 +0000181 """Report if any file in the Doc directory has been changed."""
182 return bool(file_paths)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000183
Florent Xiclunae4a33802010-08-09 12:24:20 +0000184
Christian Heimesada8c3b2008-03-18 18:26:33 +0000185@status("Misc/ACKS updated", modal=True)
186def credit_given(file_paths):
187 """Check if Misc/ACKS has been changed."""
Terry Jan Reedy6e2711b2013-07-21 20:57:44 -0400188 return os.path.join('Misc', 'ACKS') in file_paths
Christian Heimesada8c3b2008-03-18 18:26:33 +0000189
Florent Xiclunae4a33802010-08-09 12:24:20 +0000190
Christian Heimesada8c3b2008-03-18 18:26:33 +0000191@status("Misc/NEWS updated", modal=True)
192def reported_news(file_paths):
193 """Check if Misc/NEWS has been changed."""
Terry Jan Reedy6e2711b2013-07-21 20:57:44 -0400194 return os.path.join('Misc', 'NEWS') in file_paths
Christian Heimesada8c3b2008-03-18 18:26:33 +0000195
Ross Lagerwall6c52c572012-03-11 19:21:07 +0200196@status("configure regenerated", modal=True, info=str)
197def regenerated_configure(file_paths):
198 """Check if configure has been regenerated."""
Matthias Klose5ce31cc2012-03-14 23:17:31 +0100199 if 'configure.ac' in file_paths:
Ross Lagerwall6c52c572012-03-11 19:21:07 +0200200 return "yes" if 'configure' in file_paths else "no"
201 else:
202 return "not needed"
203
204@status("pyconfig.h.in regenerated", modal=True, info=str)
205def regenerated_pyconfig_h_in(file_paths):
206 """Check if pyconfig.h.in has been regenerated."""
Matthias Klose5ce31cc2012-03-14 23:17:31 +0100207 if 'configure.ac' in file_paths:
Ross Lagerwall6c52c572012-03-11 19:21:07 +0200208 return "yes" if 'pyconfig.h.in' in file_paths else "no"
209 else:
210 return "not needed"
Christian Heimesada8c3b2008-03-18 18:26:33 +0000211
212def main():
Nick Coghlan2f386252017-03-12 16:17:46 +1000213 base_branch = get_base_branch()
214 file_paths = changed_files(base_branch)
Brett Cannon058173e2010-07-04 22:05:34 +0000215 python_files = [fn for fn in file_paths if fn.endswith('.py')]
216 c_files = [fn for fn in file_paths if fn.endswith(('.c', '.h'))]
Georg Brandl24f07172014-10-19 11:54:08 +0200217 doc_files = [fn for fn in file_paths if fn.startswith('Doc') and
218 fn.endswith(('.rst', '.inc'))]
Terry Jan Reedy6e2711b2013-07-21 20:57:44 -0400219 misc_files = {os.path.join('Misc', 'ACKS'), os.path.join('Misc', 'NEWS')}\
220 & set(file_paths)
Brett Cannon058173e2010-07-04 22:05:34 +0000221 # PEP 8 whitespace rules enforcement.
222 normalize_whitespace(python_files)
Georg Brandla9afb682010-10-21 12:49:28 +0000223 # C rules enforcement.
224 normalize_c_whitespace(c_files)
225 # Doc whitespace enforcement.
226 normalize_docs_whitespace(doc_files)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000227 # Docs updated.
Georg Brandla9afb682010-10-21 12:49:28 +0000228 docs_modified(doc_files)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000229 # Misc/ACKS changed.
Terry Jan Reedy6e2711b2013-07-21 20:57:44 -0400230 credit_given(misc_files)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000231 # Misc/NEWS changed.
Terry Jan Reedy6e2711b2013-07-21 20:57:44 -0400232 reported_news(misc_files)
Ross Lagerwall6c52c572012-03-11 19:21:07 +0200233 # Regenerated configure, if necessary.
234 regenerated_configure(file_paths)
235 # Regenerated pyconfig.h.in, if necessary.
236 regenerated_pyconfig_h_in(file_paths)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000237
238 # Test suite run and passed.
Éric Araujofbc5ff62011-08-12 17:50:08 +0200239 if python_files or c_files:
Ezio Melotti5e12bb72013-01-11 14:07:47 +0200240 end = " and check for refleaks?" if c_files else "?"
Éric Araujofbc5ff62011-08-12 17:50:08 +0200241 print()
Ezio Melotti5e12bb72013-01-11 14:07:47 +0200242 print("Did you run the test suite" + end)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000243
244
245if __name__ == '__main__':
246 main()