blob: 8a2d90639d4c206c1c4698087c9902adbd5a6184 [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():
77 if not os.path.isdir(os.path.join(SRCDIR, '.git')):
78 # 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()
108 elif os.path.isdir(os.path.join(SRCDIR, '.git')):
109 if base_branch:
110 cmd = 'git diff --name-status ' + base_branch
111 else:
112 cmd = 'git status --porcelain'
113 filenames = []
114 st = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
115 try:
116 for line in st.stdout:
117 line = line.decode().rstrip()
118 status_text, filename = line.split(None, 1)
119 status = set(status_text)
120 # modified, added or unmerged files
121 if not status.intersection('MAU'):
122 continue
123 if ' -> ' in filename:
124 # file is renamed
125 filename = filename.split(' -> ', 2)[1].strip()
126 filenames.append(filename)
127 finally:
128 st.stdout.close()
129 return filenames
Georg Brandlef212e02010-11-26 08:04:57 +0000130 else:
131 sys.exit('need a checkout to get modified files')
132
Georg Brandlef212e02010-11-26 08:04:57 +0000133
134def report_modified_files(file_paths):
135 count = len(file_paths)
136 if count == 0:
137 return n_files_str(count)
138 else:
139 lines = ["{}:".format(n_files_str(count))]
140 for path in file_paths:
141 lines.append(" {}".format(path))
142 return "\n".join(lines)
143
144
145@status("Fixing whitespace", info=report_modified_files)
Brett Cannona8b09fd2008-03-18 17:25:13 +0000146def normalize_whitespace(file_paths):
147 """Make sure that the whitespace for .py files have been normalized."""
148 reindent.makebackup = False # No need to create backups.
Georg Brandlef212e02010-11-26 08:04:57 +0000149 fixed = []
150 for path in (x for x in file_paths if x.endswith('.py')):
Éric Araujo35a7f552011-07-30 21:34:04 +0200151 if reindent.check(os.path.join(SRCDIR, path)):
Georg Brandlef212e02010-11-26 08:04:57 +0000152 fixed.append(path)
153 return fixed
154
155
156@status("Fixing C file whitespace", info=report_modified_files)
157def normalize_c_whitespace(file_paths):
158 """Report if any C files """
159 fixed = []
160 for path in file_paths:
Éric Araujo35a7f552011-07-30 21:34:04 +0200161 abspath = os.path.join(SRCDIR, path)
162 with open(abspath, 'r') as f:
Georg Brandlef212e02010-11-26 08:04:57 +0000163 if '\t' not in f.read():
164 continue
Éric Araujo35a7f552011-07-30 21:34:04 +0200165 untabify.process(abspath, 8, verbose=False)
Georg Brandlef212e02010-11-26 08:04:57 +0000166 fixed.append(path)
167 return fixed
168
169
170ws_re = re.compile(br'\s+(\r?\n)$')
171
172@status("Fixing docs whitespace", info=report_modified_files)
173def normalize_docs_whitespace(file_paths):
174 fixed = []
175 for path in file_paths:
Éric Araujo35a7f552011-07-30 21:34:04 +0200176 abspath = os.path.join(SRCDIR, path)
Georg Brandlef212e02010-11-26 08:04:57 +0000177 try:
Éric Araujo35a7f552011-07-30 21:34:04 +0200178 with open(abspath, 'rb') as f:
Georg Brandlef212e02010-11-26 08:04:57 +0000179 lines = f.readlines()
180 new_lines = [ws_re.sub(br'\1', line) for line in lines]
181 if new_lines != lines:
Éric Araujo35a7f552011-07-30 21:34:04 +0200182 shutil.copyfile(abspath, abspath + '.bak')
183 with open(abspath, 'wb') as f:
Georg Brandlef212e02010-11-26 08:04:57 +0000184 f.writelines(new_lines)
185 fixed.append(path)
186 except Exception as err:
187 print 'Cannot fix %s: %s' % (path, err)
188 return fixed
189
Brett Cannona8b09fd2008-03-18 17:25:13 +0000190
191@status("Docs modified", modal=True)
192def docs_modified(file_paths):
Georg Brandlef212e02010-11-26 08:04:57 +0000193 """Report if any file in the Doc directory has been changed."""
194 return bool(file_paths)
195
Brett Cannona8b09fd2008-03-18 17:25:13 +0000196
197@status("Misc/ACKS updated", modal=True)
198def credit_given(file_paths):
199 """Check if Misc/ACKS has been changed."""
Terry Jan Reedy68ad1d12013-07-21 20:57:44 -0400200 return os.path.join('Misc', 'ACKS') in file_paths
Brett Cannona8b09fd2008-03-18 17:25:13 +0000201
Georg Brandlef212e02010-11-26 08:04:57 +0000202
Brett Cannona8b09fd2008-03-18 17:25:13 +0000203@status("Misc/NEWS updated", modal=True)
204def reported_news(file_paths):
205 """Check if Misc/NEWS has been changed."""
Terry Jan Reedy68ad1d12013-07-21 20:57:44 -0400206 return os.path.join('Misc', 'NEWS') in file_paths
Brett Cannona8b09fd2008-03-18 17:25:13 +0000207
208
209def main():
Nick Coghlanc8869af2017-03-12 19:34:16 +1000210 base_branch = get_base_branch()
211 file_paths = changed_files(base_branch)
Georg Brandlef212e02010-11-26 08:04:57 +0000212 python_files = [fn for fn in file_paths if fn.endswith('.py')]
213 c_files = [fn for fn in file_paths if fn.endswith(('.c', '.h'))]
Georg Brandl6a1184c2014-10-19 11:54:08 +0200214 doc_files = [fn for fn in file_paths if fn.startswith('Doc') and
215 fn.endswith(('.rst', '.inc'))]
Terry Jan Reedy68ad1d12013-07-21 20:57:44 -0400216 misc_files = {os.path.join('Misc', 'ACKS'), os.path.join('Misc', 'NEWS')}\
217 & set(file_paths)
Georg Brandlef212e02010-11-26 08:04:57 +0000218 # PEP 8 whitespace rules enforcement.
219 normalize_whitespace(python_files)
220 # C rules enforcement.
221 normalize_c_whitespace(c_files)
222 # Doc whitespace enforcement.
223 normalize_docs_whitespace(doc_files)
Brett Cannona8b09fd2008-03-18 17:25:13 +0000224 # Docs updated.
Georg Brandlef212e02010-11-26 08:04:57 +0000225 docs_modified(doc_files)
Brett Cannona8b09fd2008-03-18 17:25:13 +0000226 # Misc/ACKS changed.
Terry Jan Reedy68ad1d12013-07-21 20:57:44 -0400227 credit_given(misc_files)
Brett Cannona8b09fd2008-03-18 17:25:13 +0000228 # Misc/NEWS changed.
Terry Jan Reedy68ad1d12013-07-21 20:57:44 -0400229 reported_news(misc_files)
Brett Cannona8b09fd2008-03-18 17:25:13 +0000230
231 # Test suite run and passed.
Éric Araujoa5afa492011-08-19 08:41:00 +0200232 if python_files or c_files:
Ezio Melotti9e9cb282013-01-11 14:07:47 +0200233 end = " and check for refleaks?" if c_files else "?"
Éric Araujoa5afa492011-08-19 08:41:00 +0200234 print
Ezio Melotti9e9cb282013-01-11 14:07:47 +0200235 print "Did you run the test suite" + end
Brett Cannona8b09fd2008-03-18 17:25:13 +0000236
237
238if __name__ == '__main__':
239 main()