blob: be46fe3d083b0371cae1194566b0fa346fe56c07 [file] [log] [blame]
Éric Araujo0fb681e2011-07-29 12:06:13 +02001#!/usr/bin/env python
Georg Brandlef212e02010-11-26 08:04:57 +00002import re
3import sys
4import shutil
Brett Cannona8b09fd2008-03-18 17:25:13 +00005import os.path
6import subprocess
Éric Araujo35a7f552011-07-30 21:34:04 +02007import sysconfig
Brett Cannona8b09fd2008-03-18 17:25:13 +00008
9import reindent
Georg Brandlef212e02010-11-26 08:04:57 +000010import untabify
11
12
Éric Araujo35a7f552011-07-30 21:34:04 +020013SRCDIR = sysconfig.get_config_var('srcdir')
14
Georg Brandlef212e02010-11-26 08:04:57 +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 "")
Brett Cannona8b09fd2008-03-18 17:25:13 +000018
19
20def 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:
Georg Brandlef212e02010-11-26 08:04:57 +000032 print "yes" if result else "NO"
Brett Cannona8b09fd2008-03-18 17:25:13 +000033 return result
34 return call_fxn
35 return decorated_fxn
36
Brett Cannona8b09fd2008-03-18 17:25:13 +000037
Nadeem Vawdaf00011a2012-02-22 11:40:09 +020038def mq_patches_applied():
39 """Check if there are any applied MQ patches."""
40 cmd = 'hg qapplied'
41 st = subprocess.Popen(cmd.split(),
42 stdout=subprocess.PIPE,
43 stderr=subprocess.PIPE)
44 try:
45 bstdout, _ = st.communicate()
46 return st.returncode == 0 and bstdout
47 finally:
48 st.stdout.close()
49 st.stderr.close()
50
51
Nick Coghlanc8869af2017-03-12 19:34:16 +100052def get_git_branch():
53 """Get the symbolic name for the current git branch"""
54 cmd = "git rev-parse --abbrev-ref HEAD".split()
55 try:
56 return subprocess.check_output(cmd, stderr=subprocess.PIPE)
57 except subprocess.CalledProcessError:
58 return None
59
60
61def get_git_upstream_remote():
62 """Get the remote name to use for upstream branches
63
64 Uses "upstream" if it exists, "origin" otherwise
65 """
66 cmd = "git remote get-url upstream".split()
67 try:
68 subprocess.check_output(cmd, stderr=subprocess.PIPE)
69 except subprocess.CalledProcessError:
70 return "origin"
71 return "upstream"
72
73
74@status("Getting base branch for PR",
75 info=lambda x: x if x is not None else "not a PR branch")
76def get_base_branch():
Nick Coghland6d943a2017-04-09 18:32:48 +100077 if not os.path.exists(os.path.join(SRCDIR, '.git')):
Nick Coghlanc8869af2017-03-12 19:34:16 +100078 # Not a git checkout, so there's no base branch
79 return None
80 version = sys.version_info
81 if version.releaselevel == 'alpha':
82 base_branch = "master"
83 else:
84 base_branch = "{0.major}.{0.minor}".format(version)
85 this_branch = get_git_branch()
86 if this_branch is None or this_branch == base_branch:
87 # Not on a git PR branch, so there's no base branch
88 return None
89 upstream_remote = get_git_upstream_remote()
90 return upstream_remote + "/" + base_branch
91
92
Georg Brandlef212e02010-11-26 08:04:57 +000093@status("Getting the list of files that have been added/changed",
94 info=lambda x: n_files_str(len(x)))
Nick Coghlanc8869af2017-03-12 19:34:16 +100095def changed_files(base_branch=None):
96 """Get the list of changed or added files from Mercurial or git."""
Éric Araujo35a7f552011-07-30 21:34:04 +020097 if os.path.isdir(os.path.join(SRCDIR, '.hg')):
Nick Coghlanc8869af2017-03-12 19:34:16 +100098 if base_branch is not None:
99 sys.exit('need a git checkout to check PR status')
Georg Brandlef212e02010-11-26 08:04:57 +0000100 cmd = 'hg status --added --modified --no-status'
Nadeem Vawdaf00011a2012-02-22 11:40:09 +0200101 if mq_patches_applied():
102 cmd += ' --rev qparent'
Nick Coghlanc8869af2017-03-12 19:34:16 +1000103 st = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
104 try:
105 return [x.decode().rstrip() for x in st.stdout]
106 finally:
107 st.stdout.close()
Nick Coghlanee10fb92017-03-12 20:03:45 +1000108 elif os.path.exists(os.path.join(SRCDIR, '.git')):
109 # We just use an existence check here as:
110 # directory = normal git checkout/clone
111 # file = git worktree directory
Nick Coghlanc8869af2017-03-12 19:34:16 +1000112 if base_branch:
113 cmd = 'git diff --name-status ' + base_branch
114 else:
115 cmd = 'git status --porcelain'
116 filenames = []
117 st = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
118 try:
119 for line in st.stdout:
120 line = line.decode().rstrip()
121 status_text, filename = line.split(None, 1)
122 status = set(status_text)
123 # modified, added or unmerged files
124 if not status.intersection('MAU'):
125 continue
126 if ' -> ' in filename:
127 # file is renamed
128 filename = filename.split(' -> ', 2)[1].strip()
129 filenames.append(filename)
130 finally:
131 st.stdout.close()
132 return filenames
Georg Brandlef212e02010-11-26 08:04:57 +0000133 else:
134 sys.exit('need a checkout to get modified files')
135
Georg Brandlef212e02010-11-26 08:04:57 +0000136
137def report_modified_files(file_paths):
138 count = len(file_paths)
139 if count == 0:
140 return n_files_str(count)
141 else:
142 lines = ["{}:".format(n_files_str(count))]
143 for path in file_paths:
144 lines.append(" {}".format(path))
145 return "\n".join(lines)
146
147
148@status("Fixing whitespace", info=report_modified_files)
Brett Cannona8b09fd2008-03-18 17:25:13 +0000149def normalize_whitespace(file_paths):
150 """Make sure that the whitespace for .py files have been normalized."""
151 reindent.makebackup = False # No need to create backups.
Georg Brandlef212e02010-11-26 08:04:57 +0000152 fixed = []
153 for path in (x for x in file_paths if x.endswith('.py')):
Éric Araujo35a7f552011-07-30 21:34:04 +0200154 if reindent.check(os.path.join(SRCDIR, path)):
Georg Brandlef212e02010-11-26 08:04:57 +0000155 fixed.append(path)
156 return fixed
157
158
159@status("Fixing C file whitespace", info=report_modified_files)
160def normalize_c_whitespace(file_paths):
161 """Report if any C files """
162 fixed = []
163 for path in file_paths:
Éric Araujo35a7f552011-07-30 21:34:04 +0200164 abspath = os.path.join(SRCDIR, path)
165 with open(abspath, 'r') as f:
Georg Brandlef212e02010-11-26 08:04:57 +0000166 if '\t' not in f.read():
167 continue
Éric Araujo35a7f552011-07-30 21:34:04 +0200168 untabify.process(abspath, 8, verbose=False)
Georg Brandlef212e02010-11-26 08:04:57 +0000169 fixed.append(path)
170 return fixed
171
172
173ws_re = re.compile(br'\s+(\r?\n)$')
174
175@status("Fixing docs whitespace", info=report_modified_files)
176def normalize_docs_whitespace(file_paths):
177 fixed = []
178 for path in file_paths:
Éric Araujo35a7f552011-07-30 21:34:04 +0200179 abspath = os.path.join(SRCDIR, path)
Georg Brandlef212e02010-11-26 08:04:57 +0000180 try:
Éric Araujo35a7f552011-07-30 21:34:04 +0200181 with open(abspath, 'rb') as f:
Georg Brandlef212e02010-11-26 08:04:57 +0000182 lines = f.readlines()
183 new_lines = [ws_re.sub(br'\1', line) for line in lines]
184 if new_lines != lines:
Éric Araujo35a7f552011-07-30 21:34:04 +0200185 shutil.copyfile(abspath, abspath + '.bak')
186 with open(abspath, 'wb') as f:
Georg Brandlef212e02010-11-26 08:04:57 +0000187 f.writelines(new_lines)
188 fixed.append(path)
189 except Exception as err:
190 print 'Cannot fix %s: %s' % (path, err)
191 return fixed
192
Brett Cannona8b09fd2008-03-18 17:25:13 +0000193
194@status("Docs modified", modal=True)
195def docs_modified(file_paths):
Georg Brandlef212e02010-11-26 08:04:57 +0000196 """Report if any file in the Doc directory has been changed."""
197 return bool(file_paths)
198
Brett Cannona8b09fd2008-03-18 17:25:13 +0000199
200@status("Misc/ACKS updated", modal=True)
201def credit_given(file_paths):
202 """Check if Misc/ACKS has been changed."""
Terry Jan Reedy68ad1d12013-07-21 20:57:44 -0400203 return os.path.join('Misc', 'ACKS') in file_paths
Brett Cannona8b09fd2008-03-18 17:25:13 +0000204
Georg Brandlef212e02010-11-26 08:04:57 +0000205
Brett Cannona8b09fd2008-03-18 17:25:13 +0000206@status("Misc/NEWS updated", modal=True)
207def reported_news(file_paths):
208 """Check if Misc/NEWS has been changed."""
Terry Jan Reedy68ad1d12013-07-21 20:57:44 -0400209 return os.path.join('Misc', 'NEWS') in file_paths
Brett Cannona8b09fd2008-03-18 17:25:13 +0000210
211
212def main():
Nick Coghlanc8869af2017-03-12 19:34:16 +1000213 base_branch = get_base_branch()
214 file_paths = changed_files(base_branch)
Georg Brandlef212e02010-11-26 08:04:57 +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 Brandl6a1184c2014-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 Reedy68ad1d12013-07-21 20:57:44 -0400219 misc_files = {os.path.join('Misc', 'ACKS'), os.path.join('Misc', 'NEWS')}\
220 & set(file_paths)
Georg Brandlef212e02010-11-26 08:04:57 +0000221 # PEP 8 whitespace rules enforcement.
222 normalize_whitespace(python_files)
223 # C rules enforcement.
224 normalize_c_whitespace(c_files)
225 # Doc whitespace enforcement.
226 normalize_docs_whitespace(doc_files)
Brett Cannona8b09fd2008-03-18 17:25:13 +0000227 # Docs updated.
Georg Brandlef212e02010-11-26 08:04:57 +0000228 docs_modified(doc_files)
Brett Cannona8b09fd2008-03-18 17:25:13 +0000229 # Misc/ACKS changed.
Terry Jan Reedy68ad1d12013-07-21 20:57:44 -0400230 credit_given(misc_files)
Brett Cannona8b09fd2008-03-18 17:25:13 +0000231 # Misc/NEWS changed.
Terry Jan Reedy68ad1d12013-07-21 20:57:44 -0400232 reported_news(misc_files)
Brett Cannona8b09fd2008-03-18 17:25:13 +0000233
234 # Test suite run and passed.
Éric Araujoa5afa492011-08-19 08:41:00 +0200235 if python_files or c_files:
Ezio Melotti9e9cb282013-01-11 14:07:47 +0200236 end = " and check for refleaks?" if c_files else "?"
Éric Araujoa5afa492011-08-19 08:41:00 +0200237 print
Ezio Melotti9e9cb282013-01-11 14:07:47 +0200238 print "Did you run the test suite" + end
Brett Cannona8b09fd2008-03-18 17:25:13 +0000239
240
241if __name__ == '__main__':
242 main()