3 # Copyright (C) 2010 W. Trevor King <wking@drexel.edu>
5 # This file is part of Hooke.
7 # Hooke 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 # Hooke 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 Hooke. 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`_.
25 .. _Bugs Everywhere: http://bugseverywhere.org/
42 # Break "copyright" into "copy" and "right" to avoid matching the
43 # REGEXP if we decide to go back to regexps.
45 'This file is part of %(project)s.',
46 '%(project)s is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.',
47 '%(project)s is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.',
48 'You should have received a copy of the GNU Lesser General Public License along with %(project)s. If not, see <http://www.gnu.org/licenses/>.'
51 SHORT_COPY_RIGHT_TEXT = [
52 '%(project)s comes with ABSOLUTELY NO WARRANTY and is licensed under the GNU Lesser General Public License. For details, %(get-details)s.'
55 COPY_RIGHT_TAG='-xyz-COPY' + '-RIGHT-zyx-' # unlikely to occur in the wild :p
57 # Convert author names to canonical forms.
58 # ALIASES[<canonical name>] = <list of aliases>
61 # 'John Doe <jdoe@a.com>':
62 # ['John Doe', 'jdoe', 'J. Doe <j@doe.net>'],
64 # Git-based projects are encouraged to use .mailmap instead of
65 # ALIASES. See git-shortlog(1) for details.
69 'Alberto Gomez-Casado':
71 'Massimo Sandal <devicerandom@gmail.com>':
76 ['fabrizio.benedetti.82'],
77 'Richard Naud <richard.naud@epfl.ch>':
79 'Rolf Schmidt <rschmidt@alcor.concordia.ca>':
88 # List of paths that should not be scanned for copyright updates.
89 # IGNORED_PATHS = ['./.git/']
90 IGNORED_PATHS = ['./.hg/', './doc/img/', './test/data/',
91 './build/', './doc/build/']
92 # List of files that should not be scanned for copyright updates.
93 # IGNORED_FILES = ['COPYING']
94 IGNORED_FILES = ['COPYING', 'COPYING.LESSER']
96 # Work around missing author holes in the VCS history.
97 # AUTHOR_HACKS[<path tuple>] = [<missing authors]
98 # for example, if John Doe contributed to module.py but wasn't listed
99 # in the VCS history of that file:
101 # ('path', 'to', 'module.py'):['John Doe'],
104 ('hooke','driver','hdf5.py'):['Massimo Sandal'],
105 ('hooke','driver','mcs.py'):['Allen Chen'],
106 ('hooke','driver','mfp3d.py'):['A. Seeholzer','Richard Naud','Rolf Schmidt',
107 'Alberto Gomez-Casado'],
108 ('hooke','util','peak.py'):['Fabrizio Benedetti'],
109 ('hooke','plugin','showconvoluted.py'):['Rolf Schmidt'],
110 ('hooke','ui','gui','formatter.py'):['Francesco Musiani','Massimo Sandal'],
111 ('hooke','ui','gui','prettyformat.py'):['Rolf Schmidt'],
114 # Work around missing year holes in the VCS history.
115 # YEAR_HACKS[<path tuple>] = <original year>
116 # for example, if module.py was published in 2008 but the VCS history
117 # only goes back to 2010:
119 # ('path', 'to', 'module.py'):2008,
122 ('hooke','driver','hdf5.py'):2009,
123 ('hooke','driver','mfp3d.py'):2008,
124 ('hooke','driver','picoforce.py'):2006,
125 ('hooke','driver','picoforcealt.py'):2006,
126 ('hooke','util','peak.py'):2007,
127 ('hooke','plugin','showconvoluted.py'):2009,
128 ('hooke','plugin','tutorial.py'):2007,
129 ('hooke','ui','gui','formatter.py'):2006,
130 ('hooke','ui','gui','prettyformat.py'):2009,
133 # Helpers for VCS-specific commands
136 """Recursively split a path into elements.
141 >>> splitpath(os.path.join('a', 'b', 'c'))
143 >>> splitpath(os.path.join('.', 'a', 'b', 'c'))
146 path = os.path.normpath(path)
149 dirname,basename = os.path.split(path)
150 elements.insert(0,basename)
151 if dirname in ['', '.']:
154 return tuple(elements)
156 # VCS-specific commands
158 if PROJECT_INFO['vcs'] == 'Git':
162 _MSWINDOWS = sys.platform == 'win32'
163 _POSIX = not _MSWINDOWS
165 def invoke(args, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, expect=(0,)):
167 expect should be a tuple of allowed exit codes.
171 q = subprocess.Popen(args, stdin=subprocess.PIPE,
172 stdout=stdout, stderr=stderr)
174 assert _MSWINDOWS == True, 'invalid platform'
175 # win32 don't have os.execvp() so run the command in a shell
176 q = subprocess.Popen(args, stdin=subprocess.PIPE,
177 stdout=stdout, stderr=stderr, shell=True)
179 raise ValueError([args, e])
180 stdout,stderr = q.communicate(input=stdin)
182 if status not in expect:
183 raise ValueError([args, status, stdout, stderr])
184 return status, stdout, stderr
187 status,stdout,stderr = invoke(['git'] + list(args))
188 return stdout.rstrip('\n')
190 def original_year(filename=None, year_hacks=YEAR_HACKS):
192 '--format=format:%ad', # Author date
193 '--date=short', # YYYY-MM-DD
196 args.extend(['--follow', filename])
197 output = git_cmd('log', *args)
198 years = [int(line.split('-', 1)[0]) for line in output.splitlines()]
200 years.extend(year_hacks.values())
201 elif splitpath(filename) in year_hacks:
202 years.append(year_hacks[splitpath(filename)])
206 def authors(filename, author_hacks=AUTHOR_HACKS):
207 output = git_cmd('log', '--follow', '--format=format:%aN <%aE>',
208 filename) # Author name <author email>
209 ret = list(set(output.splitlines()))
210 if splitpath(filename) in author_hacks:
211 ret.extend(author_hacks[splitpath(filename)])
214 def authors_list(author_hacks=AUTHOR_HACKS):
215 output = git_cmd('log', '--format=format:%aN <%aE>')
216 ret = list(set(output.splitlines()))
217 for path,authors in author_hacks.items():
221 def is_versioned(filename):
222 output = git_cmd('log', '--follow', filename)
227 elif PROJECT_INFO['vcs'] == 'Mercurial':
231 import mercurial.dispatch
233 def mercurial_cmd(*args):
237 tmp_stdout = StringIO.StringIO()
238 tmp_stderr = StringIO.StringIO()
239 sys.stdout = tmp_stdout
240 sys.stderr = tmp_stderr
242 mercurial.dispatch.dispatch(list(args))
247 return (tmp_stdout.getvalue().rstrip('\n'),
248 tmp_stderr.getvalue().rstrip('\n'))
250 def original_year(filename=None, year_hacks=YEAR_HACKS):
252 '--template', '{date|shortdate}\n',
253 # shortdate filter: YEAR-MONTH-DAY
256 args.extend(['--follow', filename])
257 output,error = mercurial_cmd('log', *args)
258 years = [int(line.split('-', 1)[0]) for line in output.splitlines()]
260 years.extend(year_hacks.values())
261 elif splitpath(filename) in year_hacks:
262 years.append(year_hacks[splitpath(filename)])
266 def authors(filename, author_hacks=AUTHOR_HACKS):
267 output,error = mercurial_cmd('log', '--follow',
268 '--template', '{author}\n',
270 ret = list(set(output.splitlines()))
271 if splitpath(filename) in author_hacks:
272 ret.extend(author_hacks[splitpath(filename)])
275 def authors_list(author_hacks=AUTHOR_HACKS):
276 output,error = mercurial_cmd('log', '--template', '{author}\n')
277 ret = list(set(output.splitlines()))
278 for path,authors in author_hacks.items():
282 def is_versioned(filename):
283 output,error = mercurial_cmd('log', '--follow', filename)
288 elif PROJECT_INFO['vcs'] == 'Bazaar':
292 import bzrlib.builtins
295 class LogFormatter (bzrlib.log.LogFormatter):
296 supports_merge_revisions = True
298 supports_deta = False
299 supports_tags = False
300 supports_diff = False
302 def log_revision(self, revision):
303 raise NotImplementedError
305 class YearLogFormatter (LogFormatter):
306 def log_revision(self, revision):
308 time.strftime('%Y', time.gmtime(revision.rev.timestamp))
311 class AuthorLogFormatter (LogFormatter):
312 def log_revision(self, revision):
313 authors = revision.rev.get_apparent_authors()
314 self.to_file.write('\n'.join(authors)+'\n')
316 def original_year(filename=None, year_hacks=YEAR_HACKS):
317 cmd = bzrlib.builtins.cmd_log()
318 cmd.outf = StringIO.StringIO()
319 kwargs = {'log_format':YearLogFormatter, 'levels':0}
321 kwargs['file_list'] = [filenme]
323 years = [int(year) for year in set(cmd.outf.getvalue().splitlines())]
325 years.append(year_hacks.values())
326 elif splitpath(filename) in year_hacks:
327 years.append(year_hacks[splitpath(filename)])
331 def authors(filename, author_hacks=AUTHOR_HACKS):
332 cmd = bzrlib.builtins.cmd_log()
333 cmd.outf = StringIO.StringIO()
334 cmd.run(file_list=[filename], log_format=AuthorLogFormatter, levels=0)
335 ret = list(set(cmd.outf.getvalue().splitlines()))
336 if splitpath(filename) in author_hacks:
337 ret.extend(author_hacks[splitpath(filename)])
340 def authors_list(author_hacks=AUTHOR_HACKS):
341 cmd = bzrlib.builtins.cmd_log()
342 cmd.outf = StringIO.StringIO()
343 cmd.run(log_format=AuthorLogFormatter, levels=0)
344 output = cmd.outf.getvalue()
345 ret = list(set(cmd.outf.getvalue().splitlines()))
346 for path,authors in author_hacks.items():
350 def is_versioned(filename):
351 cmd = bzrlib.builtins.cmd_log()
352 cmd.outf = StringIO.StringIO()
353 cmd.run(file_list=[filename])
357 raise NotImplementedError('Unrecognized VCS: %(vcs)s' % PROJECT_INFO)
359 # General utility commands
361 def _strip_email(*args):
362 """Remove email addresses from a series of names.
367 >>> _strip_email('J Doe')
369 >>> _strip_email('J Doe <jdoe@a.com>')
371 >>> _strip_email('J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>')
372 ['J Doe', 'JJJ Smith']
375 for i,arg in enumerate(args):
378 author,addr = email.utils.parseaddr(arg)
384 def _reverse_aliases(aliases):
385 """Reverse an `aliases` dict.
387 Input: key: canonical name, value: list of aliases
388 Output: key: alias, value: canonical name
394 ... 'J Doe <jdoe@a.com>':['Johnny <jdoe@b.edu>', 'J'],
395 ... 'JJJ Smith <jjjs@a.com>':['Jingly <jjjs@b.edu>'],
396 ... None:['Anonymous <a@a.com>'],
398 >>> r = _reverse_aliases(aliases)
399 >>> for item in sorted(r.items()):
401 ('Anonymous <a@a.com>', None)
402 ('J', 'J Doe <jdoe@a.com>')
403 ('Jingly <jjjs@b.edu>', 'JJJ Smith <jjjs@a.com>')
404 ('Johnny <jdoe@b.edu>', 'J Doe <jdoe@a.com>')
407 for canonical_name,_aliases in aliases.items():
408 for alias in _aliases:
409 output[alias] = canonical_name
412 def _replace_aliases(authors, with_email=True, aliases=None):
413 """Consolidate and sort `authors`.
415 Make the replacements listed in the `aliases` dict (key: canonical
416 name, value: list of aliases). If `aliases` is ``None``, default
420 ... 'J Doe <jdoe@a.com>':['Johnny <jdoe@b.edu>'],
421 ... 'JJJ Smith <jjjs@a.com>':['Jingly <jjjs@b.edu>'],
422 ... None:['Anonymous <a@a.com>'],
425 ... 'JJJ Smith <jjjs@a.com>', 'Johnny <jdoe@b.edu>',
426 ... 'Jingly <jjjs@b.edu>', 'J Doe <jdoe@a.com>', 'Anonymous <a@a.com>']
427 >>> _replace_aliases(authors, with_email=True, aliases=aliases)
428 ['J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>']
429 >>> _replace_aliases(authors, with_email=False, aliases=aliases)
430 ['J Doe', 'JJJ Smith']
434 rev_aliases = _reverse_aliases(aliases)
435 for i,author in enumerate(authors):
436 if author in rev_aliases:
437 authors[i] = rev_aliases[author]
438 authors = sorted(list(set(authors)))
441 if with_email == False:
442 authors = _strip_email(*authors)
445 def _long_author_formatter(copyright_year_string, authors):
447 >>> print '\\n'.join(_long_author_formatter(
448 ... copyright_year_string='Copyright (C) 1990-2010',
449 ... authors=['Jack', 'Jill', 'John']))
450 Copyright (C) 1990-2010 Jack
454 lines = ['%s %s' % (copyright_year_string, authors[0])]
455 for author in authors[1:]:
456 lines.append(' '*(len(copyright_year_string)+1) + author)
459 def _short_author_formatter(copyright_year_string, authors):
461 >>> print '\\n'.join(_short_author_formatter(
462 ... copyright_year_string='Copyright (C) 1990-2010',
463 ... authors=['Jack', 'Jill', 'John']*5))
464 Copyright (C) 1990-2010 Jack, Jill, John, Jack, Jill, John, Jack, Jill, John, Jack, Jill, John, Jack, Jill, John
466 blurb = '%s %s' % (copyright_year_string, ', '.join(authors))
469 def _copyright_string(original_year, final_year, authors,
470 text=COPY_RIGHT_TEXT, extra_info={},
471 author_format_fn=_long_author_formatter,
472 formatter_kwargs={}, prefix='', wrap=True,
475 >>> print _copyright_string(original_year=2005,
477 ... authors=['A <a@a.com>', 'B <b@b.edu>'],
479 ... ) # doctest: +ELLIPSIS
480 # Copyright (C) 2005 A <a@a.com>
484 >>> print _copyright_string(original_year=2005,
486 ... authors=['A <a@a.com>', 'B <b@b.edu>']
487 ... ) # doctest: +ELLIPSIS
488 Copyright (C) 2005-2009 A <a@a.com>
492 >>> print _copyright_string(original_year=2005,
494 ... authors=['A <a@a.com>', 'B <b@b.edu>'],
495 ... text=SHORT_COPY_RIGHT_TEXT,
496 ... author_format_fn=_short_author_formatter,
497 ... extra_info={'get-details':'%(get-details)s'},
501 Copyright (C) 2005 A <a@a.com>, B <b@b.edu>
503 Hooke comes with ABSOLUTELY NO WARRANTY and is
504 licensed under the GNU Lesser General Public
505 License. For details, %(get-details)s.
506 >>> print _copyright_string(original_year=2005,
508 ... authors=['A <a@a.com>', 'B <b@b.edu>'],
509 ... text=SHORT_COPY_RIGHT_TEXT,
510 ... extra_info={'get-details':'%(get-details)s'},
511 ... author_format_fn=_short_author_formatter,
515 Copyright (C) 2005 A <a@a.com>, B <b@b.edu>
517 Hooke comes with ABSOLUTELY NO WARRANTY and is licensed under the GNU Lesser General Public License. For details, %(get-details)s.
519 for key in ['initial_indent', 'subsequent_indent']:
520 if key not in wrap_kwargs:
521 wrap_kwargs[key] = prefix
523 if original_year == final_year:
524 date_range = '%s' % original_year
526 date_range = '%s-%s' % (original_year, final_year)
527 copyright_year_string = 'Copyright (C) %s' % date_range
529 lines = author_format_fn(copyright_year_string, authors,
531 for i,line in enumerate(lines):
532 lines[i] = prefix + line
534 info = dict(PROJECT_INFO)
535 for key,value in extra_info.items():
537 text = [paragraph % info for paragraph in text]
540 text = [textwrap.fill(p, **wrap_kwargs) for p in text]
542 assert wrap_kwargs['subsequent_indent'] == '', \
543 wrap_kwargs['subsequent_indent']
544 sep = '\n%s\n' % prefix.rstrip()
545 return sep.join(['\n'.join(lines)] + text)
547 def _tag_copyright(contents):
549 >>> contents = '''Some file
551 ... # Copyright (copyright begins)
552 ... # (copyright continues)
557 >>> print _tag_copyright(contents).replace('COPY-RIGHT', 'CR')
567 for line in contents.splitlines():
568 if incopy == False and line.startswith('# Copyright'):
570 lines.append(COPY_RIGHT_TAG)
571 elif incopy == True and not line.startswith('#'):
574 lines.append(line.rstrip('\n'))
575 return '\n'.join(lines)+'\n'
577 def _update_copyright(contents, original_year, authors):
579 >>> contents = '''Some file
581 ... # Copyright (copyright begins)
582 ... # (copyright continues)
587 >>> print _update_copyright(contents, 2008, ['Jack', 'Jill']
588 ... ) # doctest: +ELLIPSIS, +REPORT_UDIFF
591 # Copyright (C) 2008-... Jack
599 current_year = time.gmtime()[0]
600 copyright_string = _copyright_string(
601 original_year, current_year, authors, prefix='# ')
602 contents = _tag_copyright(contents)
603 return contents.replace(COPY_RIGHT_TAG, copyright_string)
605 def ignored_file(filename, ignored_paths=None, ignored_files=None,
606 check_disk=True, check_vcs=True):
608 >>> ignored_paths = ['./a/', './b/']
609 >>> ignored_files = ['x', 'y']
610 >>> ignored_file('./a/z', ignored_paths, ignored_files, False, False)
612 >>> ignored_file('./ab/z', ignored_paths, ignored_files, False, False)
614 >>> ignored_file('./ab/x', ignored_paths, ignored_files, False, False)
616 >>> ignored_file('./ab/xy', ignored_paths, ignored_files, False, False)
618 >>> ignored_file('./z', ignored_paths, ignored_files, False, False)
621 if ignored_paths == None:
622 ignored_paths = IGNORED_PATHS
623 if ignored_files == None:
624 ignored_files = IGNORED_FILES
625 if check_disk == True and os.path.isfile(filename) == False:
627 for path in ignored_paths:
628 if filename.startswith(path):
630 if os.path.basename(filename) in ignored_files:
632 if check_vcs == True and is_versioned(filename) == False:
636 def _set_contents(filename, contents, original_contents=None, dry_run=False,
638 if original_contents == None and os.path.isfile(filename):
639 f = open(filename, 'r')
640 original_contents = f.read()
643 print "checking %s ... " % filename,
644 if contents != original_contents:
646 if original_contents == None:
650 if verbose > 1 and original_contents != None:
652 difflib.unified_diff(
653 original_contents.splitlines(), contents.splitlines(),
654 fromfile=os.path.normpath(os.path.join('a', filename)),
655 tofile=os.path.normpath(os.path.join('b', filename)),
658 f = file(filename, 'w')
666 def update_authors(authors_fn=authors_list, dry_run=False, verbose=0):
667 authors = authors_fn()
668 authors = _replace_aliases(authors, with_email=True, aliases=ALIASES)
669 new_contents = '%s was written by:\n%s\n' % (
670 PROJECT_INFO['project'],
673 _set_contents('AUTHORS', new_contents, dry_run=dry_run, verbose=verbose)
675 def update_file(filename, original_year_fn=original_year, authors_fn=authors,
676 dry_run=False, verbose=0):
677 f = file(filename, 'r')
681 original_year = original_year_fn(filename)
682 authors = authors_fn(filename)
683 authors = _replace_aliases(authors, with_email=True, aliases=ALIASES)
685 new_contents = _update_copyright(contents, original_year, authors)
686 _set_contents(filename, contents=new_contents, original_contents=contents,
687 dry_run=dry_run, verbose=verbose)
689 def update_files(files=None, dry_run=False, verbose=0):
690 if files == None or len(files) == 0:
692 for dirpath,dirnames,filenames in os.walk('.'):
693 for filename in filenames:
694 files.append(os.path.join(dirpath, filename))
696 for filename in files:
697 if ignored_file(filename) == True:
699 update_file(filename, dry_run=dry_run, verbose=verbose)
701 def update_pyfile(path, original_year_fn=original_year,
702 authors_fn=authors_list, dry_run=False, verbose=0):
703 original_year = original_year_fn()
704 current_year = time.gmtime()[0]
705 authors = authors_fn()
706 authors = _replace_aliases(authors, with_email=False, aliases=ALIASES)
707 paragraphs = _copyright_string(
708 original_year, current_year, authors,
709 text=SHORT_COPY_RIGHT_TEXT,
710 extra_info={'get-details':'%(get-details)s'},
711 author_format_fn=_short_author_formatter, wrap=False,
714 _copyright_string(original_year, current_year, authors, prefix='# '),
715 '', 'import textwrap', '', '',
717 _copyright_string(original_year, current_year, authors, prefix=''),
720 'def short_license(extra_info, wrap=True, **kwargs):',
724 lines.append(" '%s' %% extra_info," % p.replace("'", r"\'"))
728 ' for i,p in enumerate(paragraphs):',
729 ' paragraphs[i] = textwrap.fill(p, **kwargs)',
730 r" return '\n\n'.join(paragraphs)",
732 new_contents = '\n'.join(lines)+'\n'
733 _set_contents(path, new_contents, dry_run=dry_run, verbose=verbose)
740 if __name__ == '__main__':
744 usage = """%%prog [options] [file ...]
746 Update copyright information in source code with information from
747 the %(vcs)s repository. Run from the %(project)s repository root.
749 Replaces every line starting with '^# Copyright' and continuing with
750 '^#' with an auto-generated copyright blurb. If you want to add
751 #-commented material after a copyright blurb, please insert a blank
752 line between the blurb and your comment, so the next run of
753 ``update_copyright.py`` doesn't clobber your comment.
755 If no files are given, a list of files to update is generated
758 p = optparse.OptionParser(usage)
759 p.add_option('--pyfile', dest='pyfile', default='hooke/license.py',
761 help='Write project license info to a Python module at PATH')
762 p.add_option('--test', dest='test', default=False,
763 action='store_true', help='Run internal tests and exit')
764 p.add_option('--dry-run', dest='dry_run', default=False,
765 action='store_true', help="Don't make any changes")
766 p.add_option('-v', '--verbose', dest='verbose', default=0,
767 action='count', help='Increment verbosity')
768 options,args = p.parse_args()
770 if options.test == True:
774 #update_authors(dry_run=options.dry_run, verbose=options.verbose)
775 #update_files(files=args, dry_run=options.dry_run, verbose=options.verbose)
776 if options.pyfile != None:
777 update_pyfile(path=options.pyfile,
778 dry_run=options.dry_run, verbose=options.verbose)