3 # Copyright (C) 2010-2011 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/
40 'project': 'calibcant',
44 # Break "copyright" into "copy" and "right" to avoid matching the
47 This file is part of %(project)s.
49 %(project)s is free software: you can redistribute it and/or
50 modify it under the terms of the GNU Lesser General Public
51 License as published by the Free Software Foundation, either
52 version 3 of the License, or (at your option) any later version.
54 %(project)s is distributed in the hope that it will be useful,
55 but WITHOUT ANY WARRANTY; without even the implied warranty of
56 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
57 GNU Lesser General Public License for more details.
59 You should have received a copy of the GNU Lesser General Public
60 License along with %(project)s. If not, see
61 <http://www.gnu.org/licenses/>.
64 COPY_RIGHT_TAG='-xyz-COPY' + '-RIGHT-zyx-' # unlikely to occur in the wild :p
66 # Convert author names to canonical forms.
67 # ALIASES[<canonical name>] = <list of aliases>
70 # 'John Doe <jdoe@a.com>':
71 # ['John Doe', 'jdoe', 'J. Doe <j@doe.net>'],
73 # Git-based projects are encouraged to use .mailmap instead of
74 # ALIASES. See git-shortlog(1) for details.
77 # List of paths that should not be scanned for copyright updates.
78 # IGNORED_PATHS = ['./.git/']
79 IGNORED_PATHS = ['./.git/', './.be/', './build', './dist/',
80 './calibcant.egg-info/']
81 # List of files that should not be scanned for copyright updates.
82 # IGNORED_FILES = ['COPYING']
83 IGNORED_FILES = ['COPYING']
85 # Work around missing author holes in the VCS history.
86 # AUTHOR_HACKS[<path tuple>] = [<missing authors]
87 # for example, if John Doe contributed to module.py but wasn't listed
88 # in the VCS history of that file:
90 # ('path', 'to', 'module.py'):['John Doe'],
94 # Work around missing year holes in the VCS history.
95 # YEAR_HACKS[<path tuple>] = <original year>
96 # for example, if module.py was published in 2008 but the VCS history
97 # only goes back to 2010:
99 # ('path', 'to', 'module.py'):2008,
103 # Helpers for VCS-specific commands
106 """Recursively split a path into elements.
111 >>> splitpath(os.path.join('a', 'b', 'c'))
113 >>> splitpath(os.path.join('.', 'a', 'b', 'c'))
116 path = os.path.normpath(path)
119 dirname,basename = os.path.split(path)
120 elements.insert(0,basename)
121 if dirname in ['', '.']:
124 return tuple(elements)
126 # VCS-specific commands
128 if PROJECT_INFO['vcs'] == 'Git':
132 _MSWINDOWS = sys.platform == 'win32'
133 _POSIX = not _MSWINDOWS
135 def invoke(args, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, expect=(0,)):
137 expect should be a tuple of allowed exit codes.
141 q = subprocess.Popen(args, stdin=subprocess.PIPE,
142 stdout=stdout, stderr=stderr)
144 assert _MSWINDOWS == True, 'invalid platform'
145 # win32 don't have os.execvp() so run the command in a shell
146 q = subprocess.Popen(args, stdin=subprocess.PIPE,
147 stdout=stdout, stderr=stderr, shell=True)
149 raise ValueError([args, e])
150 stdout,stderr = q.communicate(input=stdin)
152 if status not in expect:
153 raise ValueError([args, status, stdout, stderr])
154 return status, stdout, stderr
157 status,stdout,stderr = invoke(['git'] + list(args))
158 return stdout.rstrip('\n')
160 def original_year(filename, year_hacks=YEAR_HACKS):
161 output = git_cmd('log', '--follow',
162 '--format=format:%ad', # Author date
163 '--date=short', # YYYY-MM-DD
165 years = [int(line.split('-', 1)[0]) for line in output.splitlines()]
166 if splitpath(filename) in year_hacks:
167 years.append(year_hacks[splitpath(filename)])
171 def authors(filename, author_hacks=AUTHOR_HACKS):
172 output = git_cmd('log', '--follow', '--format=format:%aN <%aE>',
173 filename) # Author name <author email>
174 ret = list(set(output.splitlines()))
175 if splitpath(filename) in author_hacks:
176 ret.extend(author_hacks[splitpath(filename)])
179 def authors_list(author_hacks=AUTHOR_HACKS):
180 output = git_cmd('log', '--format=format:%aN <%aE>')
181 ret = list(set(output.splitlines()))
182 for path,authors in author_hacks.items():
186 def is_versioned(filename):
187 output = git_cmd('log', '--follow', filename)
192 elif PROJECT_INFO['vcs'] == 'Mercurial':
196 import mercurial.dispatch
198 def mercurial_cmd(*args):
202 tmp_stdout = StringIO.StringIO()
203 tmp_stderr = StringIO.StringIO()
204 sys.stdout = tmp_stdout
205 sys.stderr = tmp_stderr
207 mercurial.dispatch.dispatch(list(args))
212 return (tmp_stdout.getvalue().rstrip('\n'),
213 tmp_stderr.getvalue().rstrip('\n'))
215 def original_year(filename, year_hacks=YEAR_HACKS):
216 # shortdate filter: YEAR-MONTH-DAY
217 output,error = mercurial_cmd('log', '--follow',
218 '--template', '{date|shortdate}\n',
220 years = [int(line.split('-', 1)[0]) for line in output.splitlines()]
221 if splitpath(filename) in year_hacks:
222 years.append(year_hacks[splitpath(filename)])
226 def authors(filename, author_hacks=AUTHOR_HACKS):
227 output,error = mercurial_cmd('log', '--follow',
228 '--template', '{author}\n',
230 ret = list(set(output.splitlines()))
231 if splitpath(filename) in author_hacks:
232 ret.extend(author_hacks[splitpath(filename)])
235 def authors_list(author_hacks=AUTHOR_HACKS):
236 output,error = mercurial_cmd('log', '--template', '{author}\n')
237 ret = list(set(output.splitlines()))
238 for path,authors in author_hacks.items():
242 def is_versioned(filename):
243 output,error = mercurial_cmd('log', '--follow', filename)
248 elif PROJECT_INFO['vcs'] == 'Bazaar':
252 import bzrlib.builtins
256 class LogFormatter (bzrlib.log.LogFormatter):
257 supports_merge_revisions = True
259 supports_deta = False
260 supports_tags = False
261 supports_diff = False
263 def log_revision(self, revision):
264 raise NotImplementedError
266 class YearLogFormatter (LogFormatter):
267 def log_revision(self, revision):
269 time.strftime('%Y', time.gmtime(revision.rev.timestamp))
272 class AuthorLogFormatter (LogFormatter):
273 def log_revision(self, revision):
274 authors = revision.rev.get_apparent_authors()
275 self.to_file.write('\n'.join(authors)+'\n')
277 def original_year(filename, year_hacks=YEAR_HACKS):
278 cmd = bzrlib.builtins.cmd_log()
279 cmd.outf = StringIO.StringIO()
280 cmd.run(file_list=[filename], log_format=YearLogFormatter, levels=0)
281 years = [int(year) for year in set(cmd.outf.getvalue().splitlines())]
282 if splitpath(filename) in year_hacks:
283 years.append(year_hacks[splitpath(filename)])
287 def authors(filename, author_hacks=AUTHOR_HACKS):
288 cmd = bzrlib.builtins.cmd_log()
289 cmd.outf = StringIO.StringIO()
290 cmd.run(file_list=[filename], log_format=AuthorLogFormatter, levels=0)
291 ret = list(set(cmd.outf.getvalue().splitlines()))
292 if splitpath(filename) in author_hacks:
293 ret.extend(author_hacks[splitpath(filename)])
296 def authors_list(author_hacks=AUTHOR_HACKS):
297 cmd = bzrlib.builtins.cmd_log()
298 cmd.outf = StringIO.StringIO()
299 cmd.run(log_format=AuthorLogFormatter, levels=0)
300 output = cmd.outf.getvalue()
301 ret = list(set(cmd.outf.getvalue().splitlines()))
302 for path,authors in author_hacks.items():
306 def is_versioned(filename):
307 cmd = bzrlib.builtins.cmd_log()
308 cmd.outf = StringIO.StringIO()
310 cmd.run(file_list=[filename])
311 except bzrlib.errors.BzrCommandError:
316 raise NotImplementedError('Unrecognized VCS: %(vcs)s' % PROJECT_INFO)
318 # General utility commands
320 def _strip_email(*args):
321 """Remove email addresses from a series of names.
326 >>> _strip_email('J Doe <jdoe@a.com>')
328 >>> _strip_email('J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>')
329 ['J Doe', 'JJJ Smith']
332 for i,arg in enumerate(args):
335 author,addr = email.utils.parseaddr(arg)
339 def _reverse_aliases(aliases):
340 """Reverse an `aliases` dict.
342 Input: key: canonical name, value: list of aliases
343 Output: key: alias, value: canonical name
349 ... 'J Doe <jdoe@a.com>':['Johnny <jdoe@b.edu>', 'J'],
350 ... 'JJJ Smith <jjjs@a.com>':['Jingly <jjjs@b.edu>'],
351 ... None:['Anonymous <a@a.com>'],
353 >>> r = _reverse_aliases(aliases)
354 >>> for item in sorted(r.items()):
356 ('Anonymous <a@a.com>', None)
357 ('J', 'J Doe <jdoe@a.com>')
358 ('Jingly <jjjs@b.edu>', 'JJJ Smith <jjjs@a.com>')
359 ('Johnny <jdoe@b.edu>', 'J Doe <jdoe@a.com>')
362 for canonical_name,_aliases in aliases.items():
363 for alias in _aliases:
364 output[alias] = canonical_name
367 def _replace_aliases(authors, with_email=True, aliases=None):
368 """Consolidate and sort `authors`.
370 Make the replacements listed in the `aliases` dict (key: canonical
371 name, value: list of aliases). If `aliases` is ``None``, default
375 ... 'J Doe <jdoe@a.com>':['Johnny <jdoe@b.edu>'],
376 ... 'JJJ Smith <jjjs@a.com>':['Jingly <jjjs@b.edu>'],
377 ... None:['Anonymous <a@a.com>'],
379 >>> _replace_aliases(['JJJ Smith <jjjs@a.com>', 'Johnny <jdoe@b.edu>',
380 ... 'Jingly <jjjs@b.edu>', 'Anonymous <a@a.com>'],
381 ... with_email=True, aliases=aliases)
382 ['J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>']
383 >>> _replace_aliases(['JJJ Smith', 'Johnny', 'Jingly', 'Anonymous'],
384 ... with_email=False, aliases=aliases)
385 ['J Doe', 'JJJ Smith']
386 >>> _replace_aliases(['JJJ Smith <jjjs@a.com>', 'Johnny <jdoe@b.edu>',
387 ... 'Jingly <jjjs@b.edu>', 'J Doe <jdoe@a.com>'],
388 ... with_email=True, aliases=aliases)
389 ['J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>']
393 if with_email == False:
394 aliases = dict([(_strip_email(author)[0], _strip_email(*_aliases))
395 for author,_aliases in aliases.items()])
396 rev_aliases = _reverse_aliases(aliases)
397 for i,author in enumerate(authors):
398 if author in rev_aliases:
399 authors[i] = rev_aliases[author]
400 authors = sorted(list(set(authors)))
405 def _copyright_string(original_year, final_year, authors, prefix=''):
407 >>> print _copyright_string(original_year=2005,
409 ... authors=['A <a@a.com>', 'B <b@b.edu>'],
411 ... ) # doctest: +ELLIPSIS
412 # Copyright (C) 2005 A <a@a.com>
416 >>> print _copyright_string(original_year=2005,
418 ... authors=['A <a@a.com>', 'B <b@b.edu>']
419 ... ) # doctest: +ELLIPSIS
420 Copyright (C) 2005-2009 A <a@a.com>
425 if original_year == final_year:
426 date_range = '%s' % original_year
428 date_range = '%s-%s' % (original_year, final_year)
429 lines = ['Copyright (C) %s %s' % (date_range, authors[0])]
430 for author in authors[1:]:
431 lines.append(' '*(len('Copyright (C) ')+len(date_range)+1) +
434 lines.extend((COPY_RIGHT_TEXT % PROJECT_INFO).splitlines())
435 for i,line in enumerate(lines):
436 lines[i] = (prefix + line).rstrip()
437 return '\n'.join(lines)
439 def _tag_copyright(contents):
441 >>> contents = '''Some file
443 ... # Copyright (copyright begins)
444 ... # (copyright continues)
449 >>> print _tag_copyright(contents).replace('COPY-RIGHT', 'CR')
459 for line in contents.splitlines():
460 if incopy == False and line.startswith('# Copyright'):
462 lines.append(COPY_RIGHT_TAG)
463 elif incopy == True and not line.startswith('#'):
466 lines.append(line.rstrip('\n'))
467 return '\n'.join(lines)+'\n'
469 def _update_copyright(contents, original_year, authors):
471 >>> contents = '''Some file
473 ... # Copyright (copyright begins)
474 ... # (copyright continues)
479 >>> print _update_copyright(contents, 2008, ['Jack', 'Jill']
480 ... ) # doctest: +ELLIPSIS, +REPORT_UDIFF
483 # Copyright (C) 2008-... Jack
491 current_year = time.gmtime()[0]
492 copyright_string = _copyright_string(
493 original_year, current_year, authors, prefix='# ')
494 contents = _tag_copyright(contents)
495 return contents.replace(COPY_RIGHT_TAG, copyright_string)
497 def ignored_file(filename, ignored_paths=None, ignored_files=None,
498 check_disk=True, check_vcs=True):
500 >>> ignored_paths = ['./a/', './b/']
501 >>> ignored_files = ['x', 'y']
502 >>> ignored_file('./a/z', ignored_paths, ignored_files, False, False)
504 >>> ignored_file('./ab/z', ignored_paths, ignored_files, False, False)
506 >>> ignored_file('./ab/x', ignored_paths, ignored_files, False, False)
508 >>> ignored_file('./ab/xy', ignored_paths, ignored_files, False, False)
510 >>> ignored_file('./z', ignored_paths, ignored_files, False, False)
513 if ignored_paths == None:
514 ignored_paths = IGNORED_PATHS
515 if ignored_files == None:
516 ignored_files = IGNORED_FILES
517 if check_disk == True and os.path.isfile(filename) == False:
519 for path in ignored_paths:
520 if filename.startswith(path):
522 if os.path.basename(filename) in ignored_files:
524 if check_vcs == True and is_versioned(filename) == False:
528 def _set_contents(filename, contents, original_contents=None, dry_run=False,
530 if original_contents == None and os.path.isfile(filename):
531 f = open(filename, 'r')
532 original_contents = f.read()
535 print "checking %s ... " % filename,
536 if contents != original_contents:
538 if original_contents == None:
542 if verbose > 1 and original_contents != None:
544 difflib.unified_diff(
545 original_contents.splitlines(), contents.splitlines(),
546 fromfile=os.path.normpath(os.path.join('a', filename)),
547 tofile=os.path.normpath(os.path.join('b', filename)),
550 f = file(filename, 'w')
558 def update_authors(authors_fn=authors_list, dry_run=False, verbose=0):
559 authors = authors_fn()
560 authors = _replace_aliases(authors, with_email=True, aliases=ALIASES)
561 new_contents = '%s was written by:\n%s\n' % (
562 PROJECT_INFO['project'],
565 _set_contents('AUTHORS', new_contents, dry_run=dry_run, verbose=verbose)
567 def update_file(filename, original_year_fn=original_year, authors_fn=authors,
568 dry_run=False, verbose=0):
569 f = file(filename, 'r')
573 original_year = original_year_fn(filename)
574 authors = authors_fn(filename)
575 authors = _replace_aliases(authors, with_email=True, aliases=ALIASES)
577 new_contents = _update_copyright(contents, original_year, authors)
578 _set_contents(filename, contents=new_contents, original_contents=contents,
579 dry_run=dry_run, verbose=verbose)
581 def update_files(files=None, dry_run=False, verbose=0):
582 if files == None or len(files) == 0:
584 for dirpath,dirnames,filenames in os.walk('.'):
585 for filename in filenames:
586 files.append(os.path.join(dirpath, filename))
588 for filename in files:
589 if ignored_file(filename) == True:
591 update_file(filename, dry_run=dry_run, verbose=verbose)
597 if __name__ == '__main__':
601 usage = """%%prog [options] [file ...]
603 Update copyright information in source code with information from
604 the %(vcs)s repository. Run from the %(project)s repository root.
606 Replaces every line starting with '^# Copyright' and continuing with
607 '^#' with an auto-generated copyright blurb. If you want to add
608 #-commented material after a copyright blurb, please insert a blank
609 line between the blurb and your comment, so the next run of
610 ``update_copyright.py`` doesn't clobber your comment.
612 If no files are given, a list of files to update is generated
615 p = optparse.OptionParser(usage)
616 p.add_option('--test', dest='test', default=False,
617 action='store_true', help='Run internal tests and exit')
618 p.add_option('--dry-run', dest='dry_run', default=False,
619 action='store_true', help="Don't make any changes")
620 p.add_option('-v', '--verbose', dest='verbose', default=0,
621 action='count', help='Increment verbosity')
622 options,args = p.parse_args()
624 if options.test == True:
628 update_authors(dry_run=options.dry_run, verbose=options.verbose)
629 update_files(files=args, dry_run=options.dry_run, verbose=options.verbose)