3 # Copyright (C) 2010 W. Trevor King <wking@drexel.edu>
5 # This file is part of ChemDB.
7 # ChemDB is free software: you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by the
9 # Free Software Foundation, either version 3 of the License, or (at your
10 # option) any later version.
12 # ChemDB 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 General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with ChemDB. If not, see <http://www.gnu.org/licenses/>.
20 """Automatically update copyright boilerplate.
22 This script is adapted from one written for `Bugs Everywhere`_.
24 .. _Bugs Everywhere: http://bugseverywhere.org/
41 # Break "copyright" into "copy" and "right" to avoid matching the
44 This file is part of %(project)s.
46 %(project)s is free software: you can redistribute it and/or modify it
47 under the terms of the GNU General Public License as published by the
48 Free Software Foundation, either version 3 of the License, or (at your
49 option) any later version.
51 %(project)s is distributed in the hope that it will be useful,
52 but WITHOUT ANY WARRANTY; without even the implied warranty of
53 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
54 GNU General Public License for more details.
56 You should have received a copy of the GNU General Public License
57 along with %(project)s. If not, see <http://www.gnu.org/licenses/>.
60 COPY_RIGHT_TAG='-xyz-COPY' + '-RIGHT-zyx-' # unlikely to occur in the wild :p
61 COMMENT_CHARS=['#', '%'] # allowed comment characters
63 # Convert author names to canonical forms.
64 # ALIASES[<canonical name>] = <list of aliases>
67 # 'John Doe <jdoe@a.com>':
68 # ['John Doe', 'jdoe', 'J. Doe <j@doe.net>'],
70 # Git-based projects are encouraged to use .mailmap instead of
71 # ALIASES. See git-shortlog(1) for details.
73 'W. Trevor King <wking@drexel.edu>':
74 ['William Trevor King <wking@thor.yang.physics.drexel.edu>',
75 'wking <wking@loki.(none)>'],
78 # List of paths that should not be scanned for copyright updates.
79 # IGNORED_PATHS = ['./.git/']
80 IGNORED_PATHS = ['./.git/', './template/web/']
81 # List of files that should not be scanned for copyright updates.
82 # IGNORED_FILES = ['COPYING']
83 IGNORED_FILES = ['COPYING', 'certgen.py', 'mk_simple_certs.py',
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 output = git_cmd('log', '--follow',
163 '--format=format:%ad', # Author date
164 '--date=short', # YYYY-MM-DD
166 years = [int(line.split('-', 1)[0]) for line in output.splitlines()]
167 if splitpath(filename) in year_hacks:
168 years.append(year_hacks[splitpath(filename)])
172 def authors(filename, author_hacks=AUTHOR_HACKS):
173 output = git_cmd('log', '--follow', '--format=format:%aN <%aE>',
174 filename) # Author name <author email>
175 ret = list(set(output.splitlines()))
176 if splitpath(filename) in author_hacks:
177 ret.extend(author_hacks[splitpath(filename)])
180 def authors_list(author_hacks=AUTHOR_HACKS):
181 output = git_cmd('log', '--format=format:%aN <%aE>')
182 ret = list(set(output.splitlines()))
183 for path,authors in author_hacks.items():
187 def is_versioned(filename):
188 output = git_cmd('log', '--follow', filename)
193 elif PROJECT_INFO['vcs'] == 'Mercurial':
197 import mercurial.dispatch
199 def mercurial_cmd(*args):
203 tmp_stdout = StringIO.StringIO()
204 tmp_stderr = StringIO.StringIO()
205 sys.stdout = tmp_stdout
206 sys.stderr = tmp_stderr
208 mercurial.dispatch.dispatch(list(args))
213 return (tmp_stdout.getvalue().rstrip('\n'),
214 tmp_stderr.getvalue().rstrip('\n'))
216 def original_year(filename, year_hacks=YEAR_HACKS):
217 # shortdate filter: YEAR-MONTH-DAY
218 output,error = mercurial_cmd('log', '--follow',
219 '--template', '{date|shortdate}\n',
221 years = [int(line.split('-', 1)[0]) for line in output.splitlines()]
222 if splitpath(filename) in year_hacks:
223 years.append(year_hacks[splitpath(filename)])
227 def authors(filename, author_hacks=AUTHOR_HACKS):
228 output,error = mercurial_cmd('log', '--follow',
229 '--template', '{author}\n',
231 ret = list(set(output.splitlines()))
232 if splitpath(filename) in author_hacks:
233 ret.extend(author_hacks[splitpath(filename)])
236 def authors_list(author_hacks=AUTHOR_HACKS):
237 output,error = mercurial_cmd('log', '--template', '{author}\n')
238 ret = list(set(output.splitlines()))
239 for path,authors in author_hacks.items():
243 def is_versioned(filename):
244 output,error = mercurial_cmd('log', '--follow', filename)
249 elif PROJECT_INFO['vcs'] == 'Bazaar':
253 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()
309 cmd.run(file_list=[filename])
313 raise NotImplementedError('Unrecognized VCS: %(vcs)s' % PROJECT_INFO)
315 # General utility commands
317 def _strip_email(*args):
318 """Remove email addresses from a series of names.
323 >>> _strip_email('J Doe <jdoe@a.com>')
325 >>> _strip_email('J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>')
326 ['J Doe', 'JJJ Smith']
329 for i,arg in enumerate(args):
332 author,addr = email.utils.parseaddr(arg)
336 def _reverse_aliases(aliases):
337 """Reverse an `aliases` dict.
339 Input: key: canonical name, value: list of aliases
340 Output: key: alias, value: canonical name
346 ... 'J Doe <jdoe@a.com>':['Johnny <jdoe@b.edu>', 'J'],
347 ... 'JJJ Smith <jjjs@a.com>':['Jingly <jjjs@b.edu>'],
348 ... None:['Anonymous <a@a.com>'],
350 >>> r = _reverse_aliases(aliases)
351 >>> for item in sorted(r.items()):
353 ('Anonymous <a@a.com>', None)
354 ('J', 'J Doe <jdoe@a.com>')
355 ('Jingly <jjjs@b.edu>', 'JJJ Smith <jjjs@a.com>')
356 ('Johnny <jdoe@b.edu>', 'J Doe <jdoe@a.com>')
359 for canonical_name,_aliases in aliases.items():
360 for alias in _aliases:
361 output[alias] = canonical_name
364 def _replace_aliases(authors, with_email=True, aliases=None):
365 """Consolidate and sort `authors`.
367 Make the replacements listed in the `aliases` dict (key: canonical
368 name, value: list of aliases). If `aliases` is ``None``, default
372 ... 'J Doe <jdoe@a.com>':['Johnny <jdoe@b.edu>'],
373 ... 'JJJ Smith <jjjs@a.com>':['Jingly <jjjs@b.edu>'],
374 ... None:['Anonymous <a@a.com>'],
376 >>> _replace_aliases(['JJJ Smith <jjjs@a.com>', 'Johnny <jdoe@b.edu>',
377 ... 'Jingly <jjjs@b.edu>', 'Anonymous <a@a.com>'],
378 ... with_email=True, aliases=aliases)
379 ['J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>']
380 >>> _replace_aliases(['JJJ Smith', 'Johnny', 'Jingly', 'Anonymous'],
381 ... with_email=False, aliases=aliases)
382 ['J Doe', 'JJJ Smith']
383 >>> _replace_aliases(['JJJ Smith <jjjs@a.com>', 'Johnny <jdoe@b.edu>',
384 ... 'Jingly <jjjs@b.edu>', 'J Doe <jdoe@a.com>'],
385 ... with_email=True, aliases=aliases)
386 ['J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>']
390 if with_email == False:
391 aliases = dict([(_strip_email(author)[0], _strip_email(*_aliases))
392 for author,_aliases in aliases.items()])
393 rev_aliases = _reverse_aliases(aliases)
394 for i,author in enumerate(authors):
395 if author in rev_aliases:
396 authors[i] = rev_aliases[author]
397 authors = sorted(list(set(authors)))
402 def _copyright_string(original_year, final_year, authors, prefix=''):
404 >>> print _copyright_string(original_year=2005,
406 ... authors=['A <a@a.com>', 'B <b@b.edu>'],
408 ... ) # doctest: +ELLIPSIS
409 # Copyright (C) 2005 A <a@a.com>
413 >>> print _copyright_string(original_year=2005,
415 ... authors=['A <a@a.com>', 'B <b@b.edu>']
416 ... ) # doctest: +ELLIPSIS
417 Copyright (C) 2005-2009 A <a@a.com>
422 if original_year == final_year:
423 date_range = '%s' % original_year
425 date_range = '%s-%s' % (original_year, final_year)
426 lines = ['Copyright (C) %s %s' % (date_range, authors[0])]
427 for author in authors[1:]:
428 lines.append(' '*(len('Copyright (C) ')+len(date_range)+1) +
431 lines.extend((COPY_RIGHT_TEXT % PROJECT_INFO).splitlines())
432 for i,line in enumerate(lines):
433 lines[i] = (prefix + line).rstrip()
434 return '\n'.join(lines)
436 def _tag_copyright(contents):
438 >>> contents = '''Some file
440 ... # Copyright (copyright begins)
441 ... # (copyright continues)
446 >>> print _tag_copyright(contents).replace('COPY-RIGHT', 'CR')
453 >>> contents = contents.replace('#', '%')
454 >>> print _tag_copyright(contents).replace('COPY-RIGHT', 'CR')
465 for line in contents.splitlines():
467 for c in COMMENT_CHARS:
468 if line.startswith('%s Copyright' % c):
471 lines.append(COPY_RIGHT_TAG + c)
473 elif incopy == True and not line.startswith(comment_char):
477 lines.append(line.rstrip('\n'))
478 return '\n'.join(lines)+'\n'
480 def _update_copyright(contents, original_year, authors):
482 >>> contents = '''Some file
484 ... # Copyright (copyright begins)
485 ... # (copyright continues)
490 >>> print _update_copyright(contents, 2008, ['Jack', 'Jill']
491 ... ) # doctest: +ELLIPSIS, +REPORT_UDIFF
494 # Copyright (C) 2008-... Jack
501 >>> contents = contents.replace('#', '%')
502 >>> print _update_copyright(contents, 2008, ['Jack', 'Jill']
503 ... ) # doctest: +ELLIPSIS, +REPORT_UDIFF
506 % Copyright (C) 2008-... Jack
514 current_year = time.gmtime()[0]
515 contents = _tag_copyright(contents)
517 for line in contents.splitlines():
518 if line.startswith(COPY_RIGHT_TAG):
519 comment_char = line[len(COPY_RIGHT_TAG):]
520 copyright_string = _copyright_string(
521 original_year, current_year, authors,
522 prefix='%s ' % comment_char)
523 lines.append(copyright_string.rstrip('\n'))
525 lines.append(line.rstrip('\n'))
526 return '\n'.join(lines)+'\n'
529 def ignored_file(filename, ignored_paths=None, ignored_files=None,
530 check_disk=True, check_vcs=True):
532 >>> ignored_paths = ['./a/', './b/']
533 >>> ignored_files = ['x', 'y']
534 >>> ignored_file('./a/z', ignored_paths, ignored_files, False, False)
536 >>> ignored_file('./ab/z', ignored_paths, ignored_files, False, False)
538 >>> ignored_file('./ab/x', ignored_paths, ignored_files, False, False)
540 >>> ignored_file('./ab/xy', ignored_paths, ignored_files, False, False)
542 >>> ignored_file('./z', ignored_paths, ignored_files, False, False)
545 if ignored_paths == None:
546 ignored_paths = IGNORED_PATHS
547 if ignored_files == None:
548 ignored_files = IGNORED_FILES
549 if check_disk == True and os.path.isfile(filename) == False:
551 for path in ignored_paths:
552 if filename.startswith(path):
554 if os.path.basename(filename) in ignored_files:
556 if check_vcs == True and is_versioned(filename) == False:
560 def _set_contents(filename, contents, original_contents=None, dry_run=False,
562 if original_contents == None and os.path.isfile(filename):
563 f = open(filename, 'r')
564 original_contents = f.read()
567 print "checking %s ... " % filename,
568 if contents != original_contents:
570 if original_contents == None:
574 if verbose > 1 and original_contents != None:
576 difflib.unified_diff(
577 original_contents.splitlines(), contents.splitlines(),
578 fromfile=os.path.normpath(os.path.join('a', filename)),
579 tofile=os.path.normpath(os.path.join('b', filename)),
582 f = file(filename, 'w')
590 def update_authors(authors_fn=authors_list, dry_run=False, verbose=0):
591 authors = authors_fn()
592 authors = _replace_aliases(authors, with_email=True, aliases=ALIASES)
593 new_contents = '%s was written by:\n%s\n' % (
594 PROJECT_INFO['project'],
597 _set_contents('AUTHORS', new_contents, dry_run=dry_run, verbose=verbose)
599 def update_file(filename, original_year_fn=original_year, authors_fn=authors,
600 dry_run=False, verbose=0):
601 f = file(filename, 'r')
605 original_year = original_year_fn(filename)
606 authors = authors_fn(filename)
607 authors = _replace_aliases(authors, with_email=True, aliases=ALIASES)
609 new_contents = _update_copyright(contents, original_year, authors)
610 _set_contents(filename, contents=new_contents, original_contents=contents,
611 dry_run=dry_run, verbose=verbose)
613 def update_files(files=None, dry_run=False, verbose=0):
614 if files == None or len(files) == 0:
616 for dirpath,dirnames,filenames in os.walk('.'):
617 for filename in filenames:
618 files.append(os.path.join(dirpath, filename))
620 for filename in files:
621 if ignored_file(filename) == True:
623 update_file(filename, dry_run=dry_run, verbose=verbose)
629 if __name__ == '__main__':
633 PROJECT_INFO['comment_chars'] = COMMENT_CHARS
634 usage = """%%prog [options] [file ...]
636 Update copyright information in source code with information from
637 the %(vcs)s repository. Run from the %(project)s repository root.
639 Replaces every line starting with '^# Copyright' and continuing with
640 '^#' with an auto-generated copyright blurb. If you want to add
641 #-commented material after a copyright blurb, please insert a blank
642 line between the blurb and your comment, so the next run of
643 ``update_copyright.py`` doesn't clobber your comment. The comment
644 character ('#' above) can be any of %(comment_chars)s.'
646 If no files are given, a list of files to update is generated
649 p = optparse.OptionParser(usage)
650 p.add_option('--test', dest='test', default=False,
651 action='store_true', help='Run internal tests and exit')
652 p.add_option('--dry-run', dest='dry_run', default=False,
653 action='store_true', help="Don't make any changes")
654 p.add_option('-v', '--verbose', dest='verbose', default=0,
655 action='count', help='Increment verbosity')
656 options,args = p.parse_args()
658 if options.test == True:
662 update_authors(dry_run=options.dry_run, verbose=options.verbose)
663 update_files(files=args, dry_run=options.dry_run, verbose=options.verbose)