Debian Codegraph @

util/authors.py

raw symbols SCIP
1 #!/usr/bin/env python
2 # -*- encoding:utf-8 -*-
3 """
4 git-authors [OPTIONS] REV1..REV2
5
6 List the authors who contributed within a given revision interval.
7
8 To change the name mapping, edit .mailmap on the top-level of the
9 repository.
10
11 """
12 # Author: Pauli Virtanen <[email protected]>. This script is in the public domain.
13
14 import optparse
15 import re
16 import sys
17 import os
18 import io
19 import subprocess
20
21 stdout_b = sys.stdout.buffer
22 MAILMAP_FILE = os.path.join(os.path.dirname(__file__), "..", ".mailmap")
23
24
25 def main():
26 p = optparse.OptionParser(__doc__.strip())
27 p.add_option("-d", "--debug", action="store_true",
28 help="print debug output")
29 p.add_option("-n", "--new", action="store_true",
30 help="print debug output")
31 options, args = p.parse_args()
32
33 if len(args) != 1:
34 p.error("invalid number of arguments")
35
36 try:
37 rev1, rev2 = args[0].split('..')
38 except ValueError:
39 p.error("argument is not a revision range")
40
41 NAME_MAP = load_name_map(MAILMAP_FILE)
42
43 # Analyze log data
44 all_authors = set()
45 authors = set()
46
47 def analyze_line(line, names, disp=False):
48 line = line.strip().decode('utf-8')
49
50 # Check the commit author name
51 m = re.match(u'^@@@([^@]*)@@@', line)
52 if m:
53 name = m.group(1)
54 line = line[m.end():]
55 name = NAME_MAP.get(name, name)
56 if disp:
57 if name not in names:
58 stdout_b.write((" - Author: %s\n" % name).encode('utf-8'))
59 names.add(name)
60
61 # Look for "thanks to" messages in the commit log
62 m = re.search(r'([Tt]hanks to|[Cc]ourtesy of) ([A-Z][A-Za-z]*? [A-Z][A-Za-z]*? [A-Z][A-Za-z]*|[A-Z][A-Za-z]*? [A-Z]\. [A-Z][A-Za-z]*|[A-Z][A-Za-z ]*? [A-Z][A-Za-z]*|[a-z0-9]+)($|\.| )', line)
63 if m:
64 name = m.group(2)
65 if name not in (u'this',):
66 if disp:
67 stdout_b.write(" - Log : %s\n" % line.strip().encode('utf-8'))
68 name = NAME_MAP.get(name, name)
69 names.add(name)
70
71 line = line[m.end():].strip()
72 line = re.sub(r'^(and|, and|, ) ', u'Thanks to ', line)
73 analyze_line(line.encode('utf-8'), names)
74
75 # Find all authors before the named range
76 for line in git.pipe('log', '--pretty=@@@%an@@@%n@@@%cn@@@%n%b',
77 '%s' % (rev1,)):
78 analyze_line(line, all_authors)
79
80 # Find authors in the named range
81 for line in git.pipe('log', '--pretty=@@@%an@@@%n@@@%cn@@@%n%b',
82 '%s..%s' % (rev1, rev2)):
83 analyze_line(line, authors, disp=options.debug)
84
85 # Sort
86 def name_key(fullname):
87 m = re.search(u' [a-z ]*[A-Za-z-]+$', fullname)
88 if m:
89 forename = fullname[:m.start()].strip()
90 surname = fullname[m.start():].strip()
91 else:
92 forename = ""
93 surname = fullname.strip()
94 surname = surname.replace('\'', '')
95 if surname.startswith(u'van der '):
96 surname = surname[8:]
97 if surname.startswith(u'de '):
98 surname = surname[3:]
99 if surname.startswith(u'von '):
100 surname = surname[4:]
101 return (surname.lower(), forename.lower())
102
103 # generate set of all new authors
104 if vars(options)['new']:
105 new_authors = authors.difference(all_authors)
106 n_authors = list(new_authors)
107 n_authors.sort(key=name_key)
108 # Print some empty lines to separate
109 stdout_b.write(("\n\n").encode('utf-8'))
110 for author in n_authors:
111 stdout_b.write(("- %s\n" % author).encode('utf-8'))
112 # return for early exit so we only print new authors
113 return
114
115 authors = list(authors)
116 authors.sort(key=name_key)
117
118 # Print
119 stdout_b.write(b"""
120 Authors
121 =======
122
123 """)
124
125 for author in authors:
126 if author in all_authors:
127 stdout_b.write(("* %s\n" % author).encode('utf-8'))
128 else:
129 stdout_b.write(("* %s +\n" % author).encode('utf-8'))
130
131 stdout_b.write(("""
132 A total of %(count)d people contributed to this release.
133 People with a "+" by their names contributed a patch for the first time.
134 This list of names is automatically generated, and may not be fully complete.
135
136 """ % dict(count=len(authors))).encode('utf-8'))
137
138 stdout_b.write(("\nNOTE: Check this list manually! It is automatically generated "
139 "and some names\n may be missing.\n").encode('utf-8'))
140
141
142 def load_name_map(filename):
143 name_map = {}
144
145 with io.open(filename, 'r', encoding='utf-8') as f:
146 for line in f:
147 line = line.strip()
148 if line.startswith(u"#") or not line:
149 continue
150
151 m = re.match(r'^(.*?)\s*<(.*?)>(.*?)\s*<(.*?)>\s*$', line)
152 if not m:
153 print("Invalid line in .mailmap: '{!r}'".format(line), file=sys.stderr)
154 sys.exit(1)
155
156 new_name = m.group(1).strip()
157 old_name = m.group(3).strip()
158
159 if old_name and new_name:
160 name_map[old_name] = new_name
161
162 return name_map
163
164
165 #------------------------------------------------------------------------------
166 # Communicating with Git
167 #------------------------------------------------------------------------------
168
169 class Cmd:
170 executable = None
171
172 def __init__(self, executable):
173 self.executable = executable
174
175 def _call(self, command, args, kw, repository=None, call=False):
176 cmd = [self.executable, command] + list(args)
177 cwd = None
178
179 if repository is not None:
180 cwd = os.getcwd()
181 os.chdir(repository)
182
183 try:
184 if call:
185 return subprocess.call(cmd, **kw)
186 else:
187 return subprocess.Popen(cmd, **kw)
188 finally:
189 if cwd is not None:
190 os.chdir(cwd)
191
192 def __call__(self, command, *a, **kw):
193 ret = self._call(command, a, {}, call=True, **kw)
194 if ret != 0:
195 raise RuntimeError("%s failed" % self.executable)
196
197 def pipe(self, command, *a, **kw):
198 stdin = kw.pop('stdin', None)
199 p = self._call(command, a, dict(stdin=stdin, stdout=subprocess.PIPE),
200 call=False, **kw)
201 return p.stdout
202
203 def read(self, command, *a, **kw):
204 p = self._call(command, a, dict(stdout=subprocess.PIPE),
205 call=False, **kw)
206 out, err = p.communicate()
207 if p.returncode != 0:
208 raise RuntimeError("%s failed" % self.executable)
209 return out
210
211 def readlines(self, command, *a, **kw):
212 out = self.read(command, *a, **kw)
213 return out.rstrip("\n").split("\n")
214
215 def test(self, command, *a, **kw):
216 ret = self._call(command, a, dict(stdout=subprocess.PIPE,
217 stderr=subprocess.PIPE),
218 call=True, **kw)
219 return (ret == 0)
220
221
222 git = Cmd("git")
223
224 #------------------------------------------------------------------------------
225
226 if __name__ == "__main__":
227 main()