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.
47 %(project)s is free software: you can redistribute it and/or
48 modify it under the terms of the GNU Lesser General Public
49 License as published by the Free Software Foundation, either
50 version 3 of the License, or (at your option) any later version.
52 %(project)s is distributed in the hope that it will be useful,
53 but WITHOUT ANY WARRANTY; without even the implied warranty of
54 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
55 GNU Lesser General Public License for more details.
57 You should have received a copy of the GNU Lesser General Public
58 License along with %(project)s. If not, see
59 <http://www.gnu.org/licenses/>.
62 SHORT_COPY_RIGHT_TEXT="""
63 %(project)s comes with ABSOLUTELY NO WARRANTY and is licensed
64 under the GNU Lesser General Public License. For details,
68 COPY_RIGHT_TAG='-xyz-COPY' + '-RIGHT-zyx-' # unlikely to occur in the wild :p
70 # Convert author names to canonical forms.
71 # ALIASES[<canonical name>] = <list of aliases>
74 # 'John Doe <jdoe@a.com>':
75 # ['John Doe', 'jdoe', 'J. Doe <j@doe.net>'],
77 # Git-based projects are encouraged to use .mailmap instead of
78 # ALIASES. See git-shortlog(1) for details.
82 'Alberto Gomez-Casado':
84 'Massimo Sandal <devicerandom@gmail.com>':
89 ['fabrizio.benedetti.82'],
90 'Richard Naud <richard.naud@epfl.ch>':
92 'Rolf Schmidt <rschmidt@alcor.concordia.ca>':
101 # List of paths that should not be scanned for copyright updates.
102 # IGNORED_PATHS = ['./.git/']
103 IGNORED_PATHS = ['./.hg/', './doc/img/', './test/data/',
104 './build/', './doc/build/']
105 # List of files that should not be scanned for copyright updates.
106 # IGNORED_FILES = ['COPYING']
107 IGNORED_FILES = ['COPYING', 'COPYING.LESSER']
109 # Work around missing author holes in the VCS history.
110 # AUTHOR_HACKS[<path tuple>] = [<missing authors]
111 # for example, if John Doe contributed to module.py but wasn't listed
112 # in the VCS history of that file:
114 # ('path', 'to', 'module.py'):['John Doe'],
117 ('hooke','driver','hdf5.py'):['Massimo Sandal'],
118 ('hooke','driver','mcs.py'):['Allen Chen'],
119 ('hooke','driver','mfp3d.py'):['A. Seeholzer','Richard Naud','Rolf Schmidt',
120 'Alberto Gomez-Casado'],
121 ('hooke','util','peak.py'):['Fabrizio Benedetti'],
122 ('hooke','plugin','showconvoluted.py'):['Rolf Schmidt'],
123 ('hooke','ui','gui','formatter.py'):['Francesco Musiani','Massimo Sandal'],
124 ('hooke','ui','gui','prettyformat.py'):['Rolf Schmidt'],
127 # Work around missing year holes in the VCS history.
128 # YEAR_HACKS[<path tuple>] = <original year>
129 # for example, if module.py was published in 2008 but the VCS history
130 # only goes back to 2010:
132 # ('path', 'to', 'module.py'):2008,
135 ('hooke','driver','hdf5.py'):2009,
136 ('hooke','driver','mfp3d.py'):2008,
137 ('hooke','driver','picoforce.py'):2006,
138 ('hooke','driver','picoforcealt.py'):2006,
139 ('hooke','util','peak.py'):2007,
140 ('hooke','plugin','showconvoluted.py'):2009,
141 ('hooke','plugin','tutorial.py'):2007,
142 ('hooke','ui','gui','formatter.py'):2006,
143 ('hooke','ui','gui','prettyformat.py'):2009,
146 # Helpers for VCS-specific commands
149 """Recursively split a path into elements.
154 >>> splitpath(os.path.join('a', 'b', 'c'))
156 >>> splitpath(os.path.join('.', 'a', 'b', 'c'))
159 path = os.path.normpath(path)
162 dirname,basename = os.path.split(path)
163 elements.insert(0,basename)
164 if dirname in ['', '.']:
167 return tuple(elements)
169 # VCS-specific commands
171 if PROJECT_INFO['vcs'] == 'Git':
175 _MSWINDOWS = sys.platform == 'win32'
176 _POSIX = not _MSWINDOWS
178 def invoke(args, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, expect=(0,)):
180 expect should be a tuple of allowed exit codes.
184 q = subprocess.Popen(args, stdin=subprocess.PIPE,
185 stdout=stdout, stderr=stderr)
187 assert _MSWINDOWS == True, 'invalid platform'
188 # win32 don't have os.execvp() so run the command in a shell
189 q = subprocess.Popen(args, stdin=subprocess.PIPE,
190 stdout=stdout, stderr=stderr, shell=True)
192 raise ValueError([args, e])
193 stdout,stderr = q.communicate(input=stdin)
195 if status not in expect:
196 raise ValueError([args, status, stdout, stderr])
197 return status, stdout, stderr
200 status,stdout,stderr = invoke(['git'] + list(args))
201 return stdout.rstrip('\n')
203 def original_year(filename=None, year_hacks=YEAR_HACKS):
205 '--format=format:%ad', # Author date
206 '--date=short', # YYYY-MM-DD
209 args.extend(['--follow', filename])
210 output = git_cmd('log', *args)
211 years = [int(line.split('-', 1)[0]) for line in output.splitlines()]
213 years.extend(year_hacks.values())
214 elif splitpath(filename) in year_hacks:
215 years.append(year_hacks[splitpath(filename)])
219 def authors(filename, author_hacks=AUTHOR_HACKS):
220 output = git_cmd('log', '--follow', '--format=format:%aN <%aE>',
221 filename) # Author name <author email>
222 ret = list(set(output.splitlines()))
223 if splitpath(filename) in author_hacks:
224 ret.extend(author_hacks[splitpath(filename)])
227 def authors_list(author_hacks=AUTHOR_HACKS):
228 output = git_cmd('log', '--format=format:%aN <%aE>')
229 ret = list(set(output.splitlines()))
230 for path,authors in author_hacks.items():
234 def is_versioned(filename):
235 output = git_cmd('log', '--follow', filename)
240 elif PROJECT_INFO['vcs'] == 'Mercurial':
244 import mercurial.dispatch
246 def mercurial_cmd(*args):
250 tmp_stdout = StringIO.StringIO()
251 tmp_stderr = StringIO.StringIO()
252 sys.stdout = tmp_stdout
253 sys.stderr = tmp_stderr
255 mercurial.dispatch.dispatch(list(args))
260 return (tmp_stdout.getvalue().rstrip('\n'),
261 tmp_stderr.getvalue().rstrip('\n'))
263 def original_year(filename=None, year_hacks=YEAR_HACKS):
265 '--template', '{date|shortdate}\n',
266 # shortdate filter: YEAR-MONTH-DAY
269 args.extend(['--follow', filename])
270 output,error = mercurial_cmd('log', *args)
271 years = [int(line.split('-', 1)[0]) for line in output.splitlines()]
273 years.extend(year_hacks.values())
274 elif splitpath(filename) in year_hacks:
275 years.append(year_hacks[splitpath(filename)])
279 def authors(filename, author_hacks=AUTHOR_HACKS):
280 output,error = mercurial_cmd('log', '--follow',
281 '--template', '{author}\n',
283 ret = list(set(output.splitlines()))
284 if splitpath(filename) in author_hacks:
285 ret.extend(author_hacks[splitpath(filename)])
288 def authors_list(author_hacks=AUTHOR_HACKS):
289 output,error = mercurial_cmd('log', '--template', '{author}\n')
290 ret = list(set(output.splitlines()))
291 for path,authors in author_hacks.items():
295 def is_versioned(filename):
296 output,error = mercurial_cmd('log', '--follow', filename)
301 elif PROJECT_INFO['vcs'] == 'Bazaar':
305 import bzrlib.builtins
308 class LogFormatter (bzrlib.log.LogFormatter):
309 supports_merge_revisions = True
311 supports_deta = False
312 supports_tags = False
313 supports_diff = False
315 def log_revision(self, revision):
316 raise NotImplementedError
318 class YearLogFormatter (LogFormatter):
319 def log_revision(self, revision):
321 time.strftime('%Y', time.gmtime(revision.rev.timestamp))
324 class AuthorLogFormatter (LogFormatter):
325 def log_revision(self, revision):
326 authors = revision.rev.get_apparent_authors()
327 self.to_file.write('\n'.join(authors)+'\n')
329 def original_year(filename=None, year_hacks=YEAR_HACKS):
330 cmd = bzrlib.builtins.cmd_log()
331 cmd.outf = StringIO.StringIO()
332 kwargs = {'log_format':YearLogFormatter, 'levels':0}
334 kwargs['file_list'] = [filenme]
336 years = [int(year) for year in set(cmd.outf.getvalue().splitlines())]
338 years.append(year_hacks.values())
339 elif splitpath(filename) in year_hacks:
340 years.append(year_hacks[splitpath(filename)])
344 def authors(filename, author_hacks=AUTHOR_HACKS):
345 cmd = bzrlib.builtins.cmd_log()
346 cmd.outf = StringIO.StringIO()
347 cmd.run(file_list=[filename], log_format=AuthorLogFormatter, levels=0)
348 ret = list(set(cmd.outf.getvalue().splitlines()))
349 if splitpath(filename) in author_hacks:
350 ret.extend(author_hacks[splitpath(filename)])
353 def authors_list(author_hacks=AUTHOR_HACKS):
354 cmd = bzrlib.builtins.cmd_log()
355 cmd.outf = StringIO.StringIO()
356 cmd.run(log_format=AuthorLogFormatter, levels=0)
357 output = cmd.outf.getvalue()
358 ret = list(set(cmd.outf.getvalue().splitlines()))
359 for path,authors in author_hacks.items():
363 def is_versioned(filename):
364 cmd = bzrlib.builtins.cmd_log()
365 cmd.outf = StringIO.StringIO()
366 cmd.run(file_list=[filename])
370 raise NotImplementedError('Unrecognized VCS: %(vcs)s' % PROJECT_INFO)
372 # General utility commands
374 def _strip_email(*args):
375 """Remove email addresses from a series of names.
380 >>> _strip_email('J Doe')
382 >>> _strip_email('J Doe <jdoe@a.com>')
384 >>> _strip_email('J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>')
385 ['J Doe', 'JJJ Smith']
388 for i,arg in enumerate(args):
391 author,addr = email.utils.parseaddr(arg)
397 def _reverse_aliases(aliases):
398 """Reverse an `aliases` dict.
400 Input: key: canonical name, value: list of aliases
401 Output: key: alias, value: canonical name
407 ... 'J Doe <jdoe@a.com>':['Johnny <jdoe@b.edu>', 'J'],
408 ... 'JJJ Smith <jjjs@a.com>':['Jingly <jjjs@b.edu>'],
409 ... None:['Anonymous <a@a.com>'],
411 >>> r = _reverse_aliases(aliases)
412 >>> for item in sorted(r.items()):
414 ('Anonymous <a@a.com>', None)
415 ('J', 'J Doe <jdoe@a.com>')
416 ('Jingly <jjjs@b.edu>', 'JJJ Smith <jjjs@a.com>')
417 ('Johnny <jdoe@b.edu>', 'J Doe <jdoe@a.com>')
420 for canonical_name,_aliases in aliases.items():
421 for alias in _aliases:
422 output[alias] = canonical_name
425 def _replace_aliases(authors, with_email=True, aliases=None):
426 """Consolidate and sort `authors`.
428 Make the replacements listed in the `aliases` dict (key: canonical
429 name, value: list of aliases). If `aliases` is ``None``, default
433 ... 'J Doe <jdoe@a.com>':['Johnny <jdoe@b.edu>'],
434 ... 'JJJ Smith <jjjs@a.com>':['Jingly <jjjs@b.edu>'],
435 ... None:['Anonymous <a@a.com>'],
438 ... 'JJJ Smith <jjjs@a.com>', 'Johnny <jdoe@b.edu>',
439 ... 'Jingly <jjjs@b.edu>', 'J Doe <jdoe@a.com>', 'Anonymous <a@a.com>']
440 >>> _replace_aliases(authors, with_email=True, aliases=aliases)
441 ['J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>']
442 >>> _replace_aliases(authors, with_email=False, aliases=aliases)
443 ['J Doe', 'JJJ Smith']
447 rev_aliases = _reverse_aliases(aliases)
448 for i,author in enumerate(authors):
449 if author in rev_aliases:
450 authors[i] = rev_aliases[author]
451 authors = sorted(list(set(authors)))
454 if with_email == False:
455 authors = _strip_email(*authors)
458 def _long_author_formatter(copyright_year_string, authors):
460 >>> print '\\n'.join(_long_author_formatter(
461 ... copyright_year_string='Copyright (C) 1990-2010',
462 ... authors=['Jack', 'Jill', 'John']))
463 Copyright (C) 1990-2010 Jack
467 lines = ['%s %s' % (copyright_year_string, authors[0])]
468 for author in authors[1:]:
469 lines.append(' '*(len(copyright_year_string)+1) + author)
472 def _short_author_formatter(copyright_year_string, authors, **kwargs):
474 >>> print '\\n'.join(_short_author_formatter(
475 ... copyright_year_string='Copyright (C) 1990-2010',
476 ... authors=['Jack', 'Jill', 'John']*5,
478 Copyright (C) 1990-2010 Jack, Jill, John, Jack,
479 Jill, John, Jack, Jill, John, Jack, Jill, John,
482 blurb = '%s %s' % (copyright_year_string, ', '.join(authors))
483 return textwrap.wrap(blurb, **kwargs)
485 def _copyright_string(original_year, final_year, authors, prefix='',
486 text=COPY_RIGHT_TEXT, extra_info={},
487 author_format_fn=_long_author_formatter,
488 formatter_kwargs={}):
490 >>> print _copyright_string(original_year=2005,
492 ... authors=['A <a@a.com>', 'B <b@b.edu>'],
494 ... ) # doctest: +ELLIPSIS
495 # Copyright (C) 2005 A <a@a.com>
499 >>> print _copyright_string(original_year=2005,
501 ... authors=['A <a@a.com>', 'B <b@b.edu>']
502 ... ) # doctest: +ELLIPSIS
503 Copyright (C) 2005-2009 A <a@a.com>
507 >>> print _copyright_string(original_year=2005,
509 ... authors=['A <a@a.com>', 'B <b@b.edu>'],
511 ... text=SHORT_COPY_RIGHT_TEXT,
512 ... author_format_fn=_short_author_formatter,
513 ... extra_info={'get-details':'%(get-details)s'},
514 ... formatter_kwargs={'width': 50},
515 ... ) # doctest: +ELLIPSIS
516 Copyright (C) 2005 A <a@a.com>, B <b@b.edu>
518 Hooke comes with ABSOLUTELY NO WARRANTY and is licensed
519 under the GNU Lesser General Public License. For details,
522 if original_year == final_year:
523 date_range = '%s' % original_year
525 date_range = '%s-%s' % (original_year, final_year)
526 copyright_year_string = 'Copyright (C) %s' % date_range
527 lines = author_format_fn(copyright_year_string, authors,
530 info = dict(PROJECT_INFO)
531 for key,value in extra_info.items():
533 lines.extend((text % info).splitlines())
534 for i,line in enumerate(lines):
535 lines[i] = (prefix + line).rstrip()
536 return '\n'.join(lines)
538 def _tag_copyright(contents):
540 >>> contents = '''Some file
542 ... # Copyright (copyright begins)
543 ... # (copyright continues)
548 >>> print _tag_copyright(contents).replace('COPY-RIGHT', 'CR')
558 for line in contents.splitlines():
559 if incopy == False and line.startswith('# Copyright'):
561 lines.append(COPY_RIGHT_TAG)
562 elif incopy == True and not line.startswith('#'):
565 lines.append(line.rstrip('\n'))
566 return '\n'.join(lines)+'\n'
568 def _update_copyright(contents, original_year, authors):
570 >>> contents = '''Some file
572 ... # Copyright (copyright begins)
573 ... # (copyright continues)
578 >>> print _update_copyright(contents, 2008, ['Jack', 'Jill']
579 ... ) # doctest: +ELLIPSIS, +REPORT_UDIFF
582 # Copyright (C) 2008-... Jack
590 current_year = time.gmtime()[0]
591 copyright_string = _copyright_string(
592 original_year, current_year, authors, prefix='# ')
593 contents = _tag_copyright(contents)
594 return contents.replace(COPY_RIGHT_TAG, copyright_string)
596 def ignored_file(filename, ignored_paths=None, ignored_files=None,
597 check_disk=True, check_vcs=True):
599 >>> ignored_paths = ['./a/', './b/']
600 >>> ignored_files = ['x', 'y']
601 >>> ignored_file('./a/z', ignored_paths, ignored_files, False, False)
603 >>> ignored_file('./ab/z', ignored_paths, ignored_files, False, False)
605 >>> ignored_file('./ab/x', ignored_paths, ignored_files, False, False)
607 >>> ignored_file('./ab/xy', ignored_paths, ignored_files, False, False)
609 >>> ignored_file('./z', ignored_paths, ignored_files, False, False)
612 if ignored_paths == None:
613 ignored_paths = IGNORED_PATHS
614 if ignored_files == None:
615 ignored_files = IGNORED_FILES
616 if check_disk == True and os.path.isfile(filename) == False:
618 for path in ignored_paths:
619 if filename.startswith(path):
621 if os.path.basename(filename) in ignored_files:
623 if check_vcs == True and is_versioned(filename) == False:
627 def _set_contents(filename, contents, original_contents=None, dry_run=False,
629 if original_contents == None and os.path.isfile(filename):
630 f = open(filename, 'r')
631 original_contents = f.read()
634 print "checking %s ... " % filename,
635 if contents != original_contents:
637 if original_contents == None:
641 if verbose > 1 and original_contents != None:
643 difflib.unified_diff(
644 original_contents.splitlines(), contents.splitlines(),
645 fromfile=os.path.normpath(os.path.join('a', filename)),
646 tofile=os.path.normpath(os.path.join('b', filename)),
649 f = file(filename, 'w')
657 def update_authors(authors_fn=authors_list, dry_run=False, verbose=0):
658 authors = authors_fn()
659 authors = _replace_aliases(authors, with_email=True, aliases=ALIASES)
660 new_contents = '%s was written by:\n%s\n' % (
661 PROJECT_INFO['project'],
664 _set_contents('AUTHORS', new_contents, dry_run=dry_run, verbose=verbose)
666 def update_file(filename, original_year_fn=original_year, authors_fn=authors,
667 dry_run=False, verbose=0):
668 f = file(filename, 'r')
672 original_year = original_year_fn(filename)
673 authors = authors_fn(filename)
674 authors = _replace_aliases(authors, with_email=True, aliases=ALIASES)
676 new_contents = _update_copyright(contents, original_year, authors)
677 _set_contents(filename, contents=new_contents, original_contents=contents,
678 dry_run=dry_run, verbose=verbose)
680 def update_files(files=None, dry_run=False, verbose=0):
681 if files == None or len(files) == 0:
683 for dirpath,dirnames,filenames in os.walk('.'):
684 for filename in filenames:
685 files.append(os.path.join(dirpath, filename))
687 for filename in files:
688 if ignored_file(filename) == True:
690 update_file(filename, dry_run=dry_run, verbose=verbose)
692 def update_pyfile(path, original_year_fn=original_year,
693 authors_fn=authors_list, dry_run=False, verbose=0):
694 original_year = original_year_fn()
695 current_year = time.gmtime()[0]
696 authors = authors_fn()
697 authors = _replace_aliases(authors, with_email=False, aliases=ALIASES)
699 _copyright_string(original_year, current_year, authors, prefix='# '),
702 _copyright_string(original_year, current_year, authors, prefix=''),
705 'def short_license(extra_info):',
707 _copyright_string(original_year, current_year, authors, prefix='',
708 text=SHORT_COPY_RIGHT_TEXT,
709 author_format_fn=_short_author_formatter,
710 extra_info={'get-details':'%(get-details)s'}),
711 '""".strip() % extra_info',
713 new_contents = '\n'.join(lines)+'\n'
714 _set_contents(path, new_contents, dry_run=dry_run, verbose=verbose)
721 if __name__ == '__main__':
725 usage = """%%prog [options] [file ...]
727 Update copyright information in source code with information from
728 the %(vcs)s repository. Run from the %(project)s repository root.
730 Replaces every line starting with '^# Copyright' and continuing with
731 '^#' with an auto-generated copyright blurb. If you want to add
732 #-commented material after a copyright blurb, please insert a blank
733 line between the blurb and your comment, so the next run of
734 ``update_copyright.py`` doesn't clobber your comment.
736 If no files are given, a list of files to update is generated
739 p = optparse.OptionParser(usage)
740 p.add_option('--pyfile', dest='pyfile', default='hooke/license.py',
742 help='Write project license info to a Python module at PATH')
743 p.add_option('--test', dest='test', default=False,
744 action='store_true', help='Run internal tests and exit')
745 p.add_option('--dry-run', dest='dry_run', default=False,
746 action='store_true', help="Don't make any changes")
747 p.add_option('-v', '--verbose', dest='verbose', default=0,
748 action='count', help='Increment verbosity')
749 options,args = p.parse_args()
751 if options.test == True:
755 update_authors(dry_run=options.dry_run, verbose=options.verbose)
756 update_files(files=args, dry_run=options.dry_run, verbose=options.verbose)
757 if options.pyfile != None:
758 update_pyfile(path=options.pyfile,
759 dry_run=options.dry_run, verbose=options.verbose)