3 # Copyright (C) 2010 W. Trevor King <wking@drexel.edu>
5 # This file is part of CalibCant.
7 # CalibCant is free software: you can redistribute it and/or
8 # modify it under the terms of the GNU Lesser General Public
9 # License as published by the Free Software Foundation, either
10 # version 3 of the License, or (at your option) any later version.
12 # CalibCant is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Lesser General Public License for more details.
17 # You should have received a copy of the GNU Lesser General Public
18 # License along with CalibCant. If not, see
19 # <http://www.gnu.org/licenses/>.
21 """Automatically update copyright boilerplate.
23 This script is adapted from one written for `Bugs Everywhere`_
26 .. _Bugs Everywhere: http://bugseverywhere.org/
27 .. _Hooke: http://code.google.com/p/hooke/
41 'project': 'CalibCant',
45 # Break "copyright" into "copy" and "right" to avoid matching the
48 This file is part of %(project)s.
50 %(project)s is free software: you can redistribute it and/or
51 modify it under the terms of the GNU Lesser General Public
52 License as published by the Free Software Foundation, either
53 version 3 of the License, or (at your option) any later version.
55 %(project)s is distributed in the hope that it will be useful,
56 but WITHOUT ANY WARRANTY; without even the implied warranty of
57 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
58 GNU Lesser General Public License for more details.
60 You should have received a copy of the GNU Lesser General Public
61 License along with %(project)s. If not, see
62 <http://www.gnu.org/licenses/>.
65 COPY_RIGHT_TAG='-xyz-COPY' + '-RIGHT-zyx-' # unlikely to occur in the wild :p
67 # Convert author names to canonical forms.
68 # ALIASES[<canonical name>] = <list of aliases>
71 # 'John Doe <jdoe@a.com>':
72 # ['John Doe', 'jdoe', 'J. Doe <j@doe.net>'],
74 # Git-based projects are encouraged to use .mailmap instead of
75 # ALIASES. See git-shortlog(1) for details.
78 # List of paths that should not be scanned for copyright updates.
79 # IGNORED_PATHS = ['./.git/']
80 IGNORED_PATHS = ['./.git/', './.be/', './build', './dist/',
81 './calibcant.egg-info/']
82 # List of files that should not be scanned for copyright updates.
83 # IGNORED_FILES = ['COPYING']
84 IGNORED_FILES = ['COPYING']
86 # Work around missing author holes in the VCS history.
87 # AUTHOR_HACKS[<path tuple>] = [<missing authors]
88 # for example, if John Doe contributed to module.py but wasn't listed
89 # in the VCS history of that file:
91 # ('path', 'to', 'module.py'):['John Doe'],
95 # Work around missing year holes in the VCS history.
96 # YEAR_HACKS[<path tuple>] = <original year>
97 # for example, if module.py was published in 2008 but the VCS history
98 # only goes back to 2010:
100 # ('path', 'to', 'module.py'):2008,
104 # Helpers for VCS-specific commands
107 """Recursively split a path into elements.
112 >>> splitpath(os.path.join('a', 'b', 'c'))
114 >>> splitpath(os.path.join('.', 'a', 'b', 'c'))
117 path = os.path.normpath(path)
120 dirname,basename = os.path.split(path)
121 elements.insert(0,basename)
122 if dirname in ['', '.']:
125 return tuple(elements)
127 # VCS-specific commands
129 if PROJECT_INFO['vcs'] == 'Git':
133 _MSWINDOWS = sys.platform == 'win32'
134 _POSIX = not _MSWINDOWS
136 def invoke(args, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, expect=(0,)):
138 expect should be a tuple of allowed exit codes.
142 q = subprocess.Popen(args, stdin=subprocess.PIPE,
143 stdout=stdout, stderr=stderr)
145 assert _MSWINDOWS == True, 'invalid platform'
146 # win32 don't have os.execvp() so run the command in a shell
147 q = subprocess.Popen(args, stdin=subprocess.PIPE,
148 stdout=stdout, stderr=stderr, shell=True)
150 raise ValueError([args, e])
151 stdout,stderr = q.communicate(input=stdin)
153 if status not in expect:
154 raise ValueError([args, status, stdout, stderr])
155 return status, stdout, stderr
158 status,stdout,stderr = invoke(['git'] + list(args))
159 return stdout.rstrip('\n')
161 def original_year(filename, year_hacks=YEAR_HACKS):
162 # shortdate filter: YEAR-MONTH-DAY
163 output = git_cmd('log', '--follow',
164 '--format=format:%ad', # Author date
165 '--date=short', # YYYY-MM-DD
167 years = [int(line.split('-', 1)[0]) for line in output.splitlines()]
168 if splitpath(filename) in year_hacks:
169 years.append(year_hacks[splitpath(filename)])
173 def authors(filename, author_hacks=AUTHOR_HACKS):
174 output = git_cmd('log', '--follow', '--format=format:%aN <%aE>',
175 filename) # Author name <author email>
176 ret = list(set(output.splitlines()))
177 if splitpath(filename) in author_hacks:
178 ret.extend(author_hacks[splitpath(filename)])
181 def authors_list(author_hacks=AUTHOR_HACKS):
182 output = git_cmd('log', '--format=format:%aN <%aE>')
183 ret = list(set(output.splitlines()))
184 for path,authors in author_hacks.items():
188 def is_versioned(filename):
189 output = git_cmd('log', '--follow', filename)
194 elif PROJECT_INFO['vcs'] == 'Mercurial':
196 def mercurial_cmd(*args):
200 tmp_stdout = StringIO.StringIO()
201 tmp_stderr = StringIO.StringIO()
202 sys.stdout = tmp_stdout
203 sys.stderr = tmp_stderr
205 mercurial.dispatch.dispatch(list(args))
210 return (tmp_stdout.getvalue().rstrip('\n'),
211 tmp_stderr.getvalue().rstrip('\n'))
213 def original_year(filename, year_hacks=YEAR_HACKS):
214 # shortdate filter: YEAR-MONTH-DAY
215 output,error = mercurial_cmd('log', '--follow',
216 '--template', '{date|shortdate}\n',
218 years = [int(line.split('-', 1)[0]) for line in output.splitlines()]
219 if splitpath(filename) in year_hacks:
220 years.append(year_hacks[splitpath(filename)])
224 def authors(filename, author_hacks=AUTHOR_HACKS):
225 output,error = mercurial_cmd('log', '-template', '{author}\n',
227 ret = list(set(output.splitlines()))
228 if splitpath(filename) in author_hacks:
229 ret.extend(author_hacks[splitpath(filename)])
232 def authors_list(author_hacks=AUTHOR_HACKS):
233 output,error = mercurial_cmd('log', '--follow',
234 '--template', '{author}\n')
235 ret = list(set(output.splitlines()))
236 for path,authors in author_hacks.items():
240 def is_versioned(filename):
241 output,error = mercurial_cmd('log', '--follow', filename)
246 elif PROJECT_INFO['vcs'] == 'Bazaar':
250 raise NotImplementedError('Unrecognized VCS: %(vcs)s' % PROJECT_INFO)
252 # General utility commands
254 def _strip_email(*args):
255 """Remove email addresses from a series of names.
260 >>> _strip_email('J Doe <jdoe@a.com>')
262 >>> _strip_email('J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>')
263 ['J Doe', 'JJJ Smith']
266 for i,arg in enumerate(args):
269 author,addr = email.utils.parseaddr(arg)
273 def _reverse_aliases(aliases):
274 """Reverse an `aliases` dict.
276 Input: key: canonical name, value: list of aliases
277 Output: key: alias, value: canonical name
283 ... 'J Doe <jdoe@a.com>':['Johnny <jdoe@b.edu>', 'J'],
284 ... 'JJJ Smith <jjjs@a.com>':['Jingly <jjjs@b.edu>'],
285 ... None:['Anonymous <a@a.com>'],
287 >>> r = _reverse_aliases(aliases)
288 >>> for item in sorted(r.items()):
290 ('Anonymous <a@a.com>', None)
291 ('J', 'J Doe <jdoe@a.com>')
292 ('Jingly <jjjs@b.edu>', 'JJJ Smith <jjjs@a.com>')
293 ('Johnny <jdoe@b.edu>', 'J Doe <jdoe@a.com>')
296 for canonical_name,_aliases in aliases.items():
297 for alias in _aliases:
298 output[alias] = canonical_name
301 def _replace_aliases(authors, with_email=True, aliases=None):
302 """Consolidate and sort `authors`.
304 Make the replacements listed in the `aliases` dict (key: canonical
305 name, value: list of aliases). If `aliases` is ``None``, default
309 ... 'J Doe <jdoe@a.com>':['Johnny <jdoe@b.edu>'],
310 ... 'JJJ Smith <jjjs@a.com>':['Jingly <jjjs@b.edu>'],
311 ... None:['Anonymous <a@a.com>'],
313 >>> _replace_aliases(['JJJ Smith <jjjs@a.com>', 'Johnny <jdoe@b.edu>',
314 ... 'Jingly <jjjs@b.edu>', 'Anonymous <a@a.com>'],
315 ... with_email=True, aliases=aliases)
316 ['J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>']
317 >>> _replace_aliases(['JJJ Smith', 'Johnny', 'Jingly', 'Anonymous'],
318 ... with_email=False, aliases=aliases)
319 ['J Doe', 'JJJ Smith']
320 >>> _replace_aliases(['JJJ Smith <jjjs@a.com>', 'Johnny <jdoe@b.edu>',
321 ... 'Jingly <jjjs@b.edu>', 'J Doe <jdoe@a.com>'],
322 ... with_email=True, aliases=aliases)
323 ['J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>']
327 if with_email == False:
328 aliases = dict([(_strip_email(author)[0], _strip_email(*_aliases))
329 for author,_aliases in aliases.items()])
330 rev_aliases = _reverse_aliases(aliases)
331 for i,author in enumerate(authors):
332 if author in rev_aliases:
333 authors[i] = rev_aliases[author]
334 authors = sorted(list(set(authors)))
339 def _copyright_string(original_year, final_year, authors, prefix=''):
341 >>> print _copyright_string(original_year=2005,
343 ... authors=['A <a@a.com>', 'B <b@b.edu>'],
345 ... ) # doctest: +ELLIPSIS
346 # Copyright (C) 2005 A <a@a.com>
350 >>> print _copyright_string(original_year=2005,
352 ... authors=['A <a@a.com>', 'B <b@b.edu>']
353 ... ) # doctest: +ELLIPSIS
354 Copyright (C) 2005-2009 A <a@a.com>
359 if original_year == final_year:
360 date_range = '%s' % original_year
362 date_range = '%s-%s' % (original_year, final_year)
363 lines = ['Copyright (C) %s %s' % (date_range, authors[0])]
364 for author in authors[1:]:
365 lines.append(' '*(len('Copyright (C) ')+len(date_range)+1) +
368 lines.extend((COPY_RIGHT_TEXT % PROJECT_INFO).splitlines())
369 for i,line in enumerate(lines):
370 lines[i] = (prefix + line).rstrip()
371 return '\n'.join(lines)
373 def _tag_copyright(contents):
375 >>> contents = '''Some file
377 ... # Copyright (copyright begins)
378 ... # (copyright continues)
383 >>> print _tag_copyright(contents).replace('COPY-RIGHT', 'CR')
393 for line in contents.splitlines():
394 if incopy == False and line.startswith('# Copyright'):
396 lines.append(COPY_RIGHT_TAG)
397 elif incopy == True and not line.startswith('#'):
400 lines.append(line.rstrip('\n'))
401 return '\n'.join(lines)+'\n'
403 def _update_copyright(contents, original_year, authors):
405 >>> contents = '''Some file
407 ... # Copyright (copyright begins)
408 ... # (copyright continues)
413 >>> print _update_copyright(contents, 2008, ['Jack', 'Jill']
414 ... ) # doctest: +ELLIPSIS, +REPORT_UDIFF
417 # Copyright (C) 2008-... Jack
425 current_year = time.gmtime()[0]
426 copyright_string = _copyright_string(
427 original_year, current_year, authors, prefix='# ')
428 contents = _tag_copyright(contents)
429 return contents.replace(COPY_RIGHT_TAG, copyright_string)
431 def ignored_file(filename, ignored_paths=None, ignored_files=None,
432 check_disk=True, check_vcs=True):
434 >>> ignored_paths = ['./a/', './b/']
435 >>> ignored_files = ['x', 'y']
436 >>> ignored_file('./a/z', ignored_paths, ignored_files, False, False)
438 >>> ignored_file('./ab/z', ignored_paths, ignored_files, False, False)
440 >>> ignored_file('./ab/x', ignored_paths, ignored_files, False, False)
442 >>> ignored_file('./ab/xy', ignored_paths, ignored_files, False, False)
444 >>> ignored_file('./z', ignored_paths, ignored_files, False, False)
447 if ignored_paths == None:
448 ignored_paths = IGNORED_PATHS
449 if ignored_files == None:
450 ignored_files = IGNORED_FILES
451 if check_disk == True and os.path.isfile(filename) == False:
453 for path in ignored_paths:
454 if filename.startswith(path):
456 if os.path.basename(filename) in ignored_files:
458 if check_vcs == True and is_versioned(filename) == False:
462 def _set_contents(filename, contents, original_contents=None, dry_run=False,
464 if original_contents == None and os.path.isfile(filename):
465 f = open(filename, 'r')
466 original_contents = f.read()
469 print "checking %s ... " % filename,
470 if contents != original_contents:
472 if original_contents == None:
476 if verbose > 1 and original_contents != None:
478 difflib.unified_diff(
479 original_contents.splitlines(), contents.splitlines(),
480 fromfile=os.path.normpath(os.path.join('a', filename)),
481 tofile=os.path.normpath(os.path.join('b', filename)),
484 f = file(filename, 'w')
492 def update_authors(authors_fn=authors_list, dry_run=False, verbose=0):
493 authors = authors_fn()
494 authors = _replace_aliases(authors, with_email=True, aliases=ALIASES)
495 new_contents = '%s was written by:\n%s\n' % (
496 PROJECT_INFO['project'],
499 _set_contents('AUTHORS', new_contents, dry_run=dry_run, verbose=verbose)
501 def update_file(filename, original_year_fn=original_year, authors_fn=authors,
502 dry_run=False, verbose=0):
503 f = file(filename, 'r')
507 original_year = original_year_fn(filename)
508 authors = authors_fn(filename)
509 authors = _replace_aliases(authors, with_email=True, aliases=ALIASES)
511 new_contents = _update_copyright(contents, original_year, authors)
512 _set_contents(filename, contents=new_contents, original_contents=contents,
513 dry_run=dry_run, verbose=verbose)
515 def update_files(files=None, dry_run=False, verbose=0):
516 if files == None or len(files) == 0:
518 for dirpath,dirnames,filenames in os.walk('.'):
519 for filename in filenames:
520 files.append(os.path.join(dirpath, filename))
522 for filename in files:
523 if ignored_file(filename) == True:
525 update_file(filename, dry_run=dry_run, verbose=verbose)
531 if __name__ == '__main__':
535 usage = """%%prog [options] [file ...]
537 Update copyright information in source code with information from
538 the %(vcs)s repository. Run from the %(project)s repository root.
540 Replaces every line starting with '^# Copyright' and continuing with
541 '^#' with an auto-generated copyright blurb. If you want to add
542 #-commented material after a copyright blurb, please insert a blank
543 line between the blurb and your comment, so the next run of
544 ``update_copyright.py`` doesn't clobber your comment.
546 If no files are given, a list of files to update is generated
549 p = optparse.OptionParser(usage)
550 p.add_option('--test', dest='test', default=False,
551 action='store_true', help='Run internal tests and exit')
552 p.add_option('--dry-run', dest='dry_run', default=False,
553 action='store_true', help="Don't make any changes")
554 p.add_option('-v', '--verbose', dest='verbose', default=0,
555 action='count', help='Increment verbosity')
556 options,args = p.parse_args()
558 if options.test == True:
562 update_authors(dry_run=options.dry_run, verbose=options.verbose)
563 update_files(files=args, dry_run=options.dry_run, verbose=options.verbose)
565 # LocalWords: difflib