blob: 33a9fead879325c41d6a8f7f605b13604b9e2c85 [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 Coghlan482f7a22017-03-12 13:19:08 +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():
Nick Coghlan2abfdf52017-04-09 18:33:03 +100073 if not os.path.exists(os.path.join(SRCDIR, '.git')):
Nick Coghlan482f7a22017-03-12 13:19:08 +100074 # 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 Coghlan482f7a22017-03-12 13:19:08 +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 Coghlan482f7a22017-03-12 13:19:08 +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]
Nick Coghlan6a6d0902017-03-12 19:37:09 +1000101 elif os.path.exists(os.path.join(SRCDIR, '.git')):
102 # We just use an existence check here as:
103 # directory = normal git checkout/clone
104 # file = git worktree directory
Nick Coghlan482f7a22017-03-12 13:19:08 +1000105 if base_branch:
106 cmd = 'git diff --name-status ' + base_branch
107 else:
108 cmd = 'git status --porcelain'
Christian Heimesd98c6772015-04-23 11:24:14 +0200109 filenames = []
110 with subprocess.Popen(cmd.split(), stdout=subprocess.PIPE) as st:
111 for line in st.stdout:
112 line = line.decode().rstrip()
Nick Coghlan482f7a22017-03-12 13:19:08 +1000113 status_text, filename = line.split(maxsplit=1)
114 status = set(status_text)
Christian Heimesd98c6772015-04-23 11:24:14 +0200115 # modified, added or unmerged files
116 if not status.intersection('MAU'):
117 continue
Christian Heimesd98c6772015-04-23 11:24:14 +0200118 if ' -> ' in filename:
119 # file is renamed
120 filename = filename.split(' -> ', 2)[1].strip()
121 filenames.append(filename)
122 return filenames
123 else:
124 sys.exit('need a Mercurial or git checkout to get modified files')
Florent Xiclunae4a33802010-08-09 12:24:20 +0000125
Christian Heimesada8c3b2008-03-18 18:26:33 +0000126
Brett Cannon058173e2010-07-04 22:05:34 +0000127def report_modified_files(file_paths):
128 count = len(file_paths)
129 if count == 0:
130 return n_files_str(count)
131 else:
132 lines = ["{}:".format(n_files_str(count))]
133 for path in file_paths:
134 lines.append(" {}".format(path))
135 return "\n".join(lines)
136
Florent Xiclunae4a33802010-08-09 12:24:20 +0000137
Brett Cannon058173e2010-07-04 22:05:34 +0000138@status("Fixing whitespace", info=report_modified_files)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000139def normalize_whitespace(file_paths):
140 """Make sure that the whitespace for .py files have been normalized."""
141 reindent.makebackup = False # No need to create backups.
Benjamin Peterson4177eff2011-06-27 18:25:06 -0500142 fixed = [path for path in file_paths if path.endswith('.py') and
Éric Araujoad548b82011-07-31 18:33:00 +0200143 reindent.check(os.path.join(SRCDIR, path))]
Brett Cannon058173e2010-07-04 22:05:34 +0000144 return fixed
Christian Heimesada8c3b2008-03-18 18:26:33 +0000145
Florent Xiclunae4a33802010-08-09 12:24:20 +0000146
Georg Brandla9afb682010-10-21 12:49:28 +0000147@status("Fixing C file whitespace", info=report_modified_files)
148def normalize_c_whitespace(file_paths):
149 """Report if any C files """
150 fixed = []
151 for path in file_paths:
Éric Araujoa3e072b2011-07-30 21:34:04 +0200152 abspath = os.path.join(SRCDIR, path)
153 with open(abspath, 'r') as f:
Georg Brandla9afb682010-10-21 12:49:28 +0000154 if '\t' not in f.read():
155 continue
Éric Araujoa3e072b2011-07-30 21:34:04 +0200156 untabify.process(abspath, 8, verbose=False)
Georg Brandla9afb682010-10-21 12:49:28 +0000157 fixed.append(path)
158 return fixed
159
160
161ws_re = re.compile(br'\s+(\r?\n)$')
162
163@status("Fixing docs whitespace", info=report_modified_files)
164def normalize_docs_whitespace(file_paths):
165 fixed = []
166 for path in file_paths:
Éric Araujoa3e072b2011-07-30 21:34:04 +0200167 abspath = os.path.join(SRCDIR, path)
Georg Brandla9afb682010-10-21 12:49:28 +0000168 try:
Éric Araujoa3e072b2011-07-30 21:34:04 +0200169 with open(abspath, 'rb') as f:
Georg Brandla9afb682010-10-21 12:49:28 +0000170 lines = f.readlines()
171 new_lines = [ws_re.sub(br'\1', line) for line in lines]
172 if new_lines != lines:
Éric Araujoa3e072b2011-07-30 21:34:04 +0200173 shutil.copyfile(abspath, abspath + '.bak')
174 with open(abspath, 'wb') as f:
Georg Brandla9afb682010-10-21 12:49:28 +0000175 f.writelines(new_lines)
176 fixed.append(path)
177 except Exception as err:
178 print('Cannot fix %s: %s' % (path, err))
179 return fixed
180
181
Christian Heimesada8c3b2008-03-18 18:26:33 +0000182@status("Docs modified", modal=True)
183def docs_modified(file_paths):
Brett Cannon058173e2010-07-04 22:05:34 +0000184 """Report if any file in the Doc directory has been changed."""
185 return bool(file_paths)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000186
Florent Xiclunae4a33802010-08-09 12:24:20 +0000187
Christian Heimesada8c3b2008-03-18 18:26:33 +0000188@status("Misc/ACKS updated", modal=True)
189def credit_given(file_paths):
190 """Check if Misc/ACKS has been changed."""
Terry Jan Reedy6e2711b2013-07-21 20:57:44 -0400191 return os.path.join('Misc', 'ACKS') in file_paths
Christian Heimesada8c3b2008-03-18 18:26:33 +0000192
Florent Xiclunae4a33802010-08-09 12:24:20 +0000193
Christian Heimesada8c3b2008-03-18 18:26:33 +0000194@status("Misc/NEWS updated", modal=True)
195def reported_news(file_paths):
196 """Check if Misc/NEWS has been changed."""
Terry Jan Reedy6e2711b2013-07-21 20:57:44 -0400197 return os.path.join('Misc', 'NEWS') in file_paths
Christian Heimesada8c3b2008-03-18 18:26:33 +0000198
Ross Lagerwall6c52c572012-03-11 19:21:07 +0200199@status("configure regenerated", modal=True, info=str)
200def regenerated_configure(file_paths):
201 """Check if configure has been regenerated."""
Matthias Klose5ce31cc2012-03-14 23:17:31 +0100202 if 'configure.ac' in file_paths:
Ross Lagerwall6c52c572012-03-11 19:21:07 +0200203 return "yes" if 'configure' in file_paths else "no"
204 else:
205 return "not needed"
206
207@status("pyconfig.h.in regenerated", modal=True, info=str)
208def regenerated_pyconfig_h_in(file_paths):
209 """Check if pyconfig.h.in has been regenerated."""
Matthias Klose5ce31cc2012-03-14 23:17:31 +0100210 if 'configure.ac' in file_paths:
Ross Lagerwall6c52c572012-03-11 19:21:07 +0200211 return "yes" if 'pyconfig.h.in' in file_paths else "no"
212 else:
213 return "not needed"
Christian Heimesada8c3b2008-03-18 18:26:33 +0000214
215def main():
Nick Coghlan482f7a22017-03-12 13:19:08 +1000216 base_branch = get_base_branch()
217 file_paths = changed_files(base_branch)
Brett Cannon058173e2010-07-04 22:05:34 +0000218 python_files = [fn for fn in file_paths if fn.endswith('.py')]
219 c_files = [fn for fn in file_paths if fn.endswith(('.c', '.h'))]
Georg Brandl24f07172014-10-19 11:54:08 +0200220 doc_files = [fn for fn in file_paths if fn.startswith('Doc') and
221 fn.endswith(('.rst', '.inc'))]
Terry Jan Reedy6e2711b2013-07-21 20:57:44 -0400222 misc_files = {os.path.join('Misc', 'ACKS'), os.path.join('Misc', 'NEWS')}\
223 & set(file_paths)
Brett Cannon058173e2010-07-04 22:05:34 +0000224 # PEP 8 whitespace rules enforcement.
225 normalize_whitespace(python_files)
Georg Brandla9afb682010-10-21 12:49:28 +0000226 # C rules enforcement.
227 normalize_c_whitespace(c_files)
228 # Doc whitespace enforcement.
229 normalize_docs_whitespace(doc_files)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000230 # Docs updated.
Georg Brandla9afb682010-10-21 12:49:28 +0000231 docs_modified(doc_files)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000232 # Misc/ACKS changed.
Terry Jan Reedy6e2711b2013-07-21 20:57:44 -0400233 credit_given(misc_files)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000234 # Misc/NEWS changed.
Terry Jan Reedy6e2711b2013-07-21 20:57:44 -0400235 reported_news(misc_files)
Ross Lagerwall6c52c572012-03-11 19:21:07 +0200236 # Regenerated configure, if necessary.
237 regenerated_configure(file_paths)
238 # Regenerated pyconfig.h.in, if necessary.
239 regenerated_pyconfig_h_in(file_paths)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000240
241 # Test suite run and passed.
Éric Araujofbc5ff62011-08-12 17:50:08 +0200242 if python_files or c_files:
Ezio Melotti5e12bb72013-01-11 14:07:47 +0200243 end = " and check for refleaks?" if c_files else "?"
Éric Araujofbc5ff62011-08-12 17:50:08 +0200244 print()
Ezio Melotti5e12bb72013-01-11 14:07:47 +0200245 print("Did you run the test suite" + end)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000246
247
248if __name__ == '__main__':
249 main()