3 # Copyright (C) 2010-2012 W. Trevor King <wking@drexel.edu>
5 # This file is part of Hooke.
7 # Hooke is free software: you can redistribute it and/or modify it
8 # under the terms of the GNU Lesser General Public License as
9 # published by the Free Software Foundation, either version 3 of the
10 # License, or (at your option) any later version.
12 # Hooke is distributed in the hope that it will be useful, but WITHOUT
13 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
15 # 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.
68 # List of paths that should not be scanned for copyright updates.
69 # IGNORED_PATHS = ['./.git/']
70 IGNORED_PATHS = ['./.hg/', './doc/img/', './test/data/',
71 './build/', './doc/build/']
72 # List of files that should not be scanned for copyright updates.
73 # IGNORED_FILES = ['COPYING']
74 IGNORED_FILES = ['COPYING', 'COPYING.LESSER']
76 # Work around missing author holes in the VCS history.
77 # AUTHOR_HACKS[<path tuple>] = [<missing authors]
78 # for example, if John Doe contributed to module.py but wasn't listed
79 # in the VCS history of that file:
81 # ('path', 'to', 'module.py'):['John Doe'],
84 ('hooke','driver','hdf5.py'):['Massimo Sandal <devicerandom@gmail.com>'],
85 ('hooke','driver','mcs.py'):['Allen Chen'],
86 ('hooke','driver','mfp3d.py'):[
89 'Rolf Schmidt <rschmidt@alcor.concordia.ca>',
90 'Alberto Gomez-Casado <a.gomezcasado@tnw.utwente.nl>'],
91 ('hooke','util','peak.py'):[
92 'Fabrizio Benedetti <fabrizio.benedetti.82@gmail.com>'],
93 ('hooke','plugin','showconvoluted.py'):[
94 'Rolf Schmidt <rschmidt@alcor.concordia.ca>'],
95 ('hooke','ui','gui','formatter.py'):[
97 'Massimo Sandal <devicerandom@gmail.com>'],
98 ('hooke','ui','gui','prettyformat.py'):[
99 'Rolf Schmidt <rschmidt@alcor.concordia.ca>'],
102 # Work around missing year holes in the VCS history.
103 # YEAR_HACKS[<path tuple>] = <original year>
104 # for example, if module.py was published in 2008 but the VCS history
105 # only goes back to 2010:
107 # ('path', 'to', 'module.py'):2008,
110 ('hooke','driver','hdf5.py'):2009,
111 ('hooke','driver','mfp3d.py'):2008,
112 ('hooke','driver','picoforce.py'):2006,
113 ('hooke','driver','picoforcealt.py'):2006,
114 ('hooke','util','peak.py'):2007,
115 ('hooke','plugin','showconvoluted.py'):2009,
116 ('hooke','plugin','tutorial.py'):2007,
117 ('hooke','ui','gui','formatter.py'):2006,
118 ('hooke','ui','gui','prettyformat.py'):2009,
121 # Helpers for VCS-specific commands
124 """Recursively split a path into elements.
129 >>> splitpath(os.path.join('a', 'b', 'c'))
131 >>> splitpath(os.path.join('.', 'a', 'b', 'c'))
134 path = os.path.normpath(path)
137 dirname,basename = os.path.split(path)
138 elements.insert(0,basename)
139 if dirname in ['', '.']:
142 return tuple(elements)
144 # VCS-specific commands
146 if PROJECT_INFO['vcs'] == 'Git':
150 _MSWINDOWS = sys.platform == 'win32'
151 _POSIX = not _MSWINDOWS
153 def invoke(args, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, expect=(0,)):
155 expect should be a tuple of allowed exit codes.
159 q = subprocess.Popen(args, stdin=subprocess.PIPE,
160 stdout=stdout, stderr=stderr)
162 assert _MSWINDOWS == True, 'invalid platform'
163 # win32 don't have os.execvp() so run the command in a shell
164 q = subprocess.Popen(args, stdin=subprocess.PIPE,
165 stdout=stdout, stderr=stderr, shell=True)
167 raise ValueError([args, e])
168 stdout,stderr = q.communicate(input=stdin)
170 if status not in expect:
171 raise ValueError([args, status, stdout, stderr])
172 return status, stdout, stderr
175 status,stdout,stderr = invoke(['git'] + list(args))
176 return stdout.rstrip('\n')
178 def original_year(filename=None, year_hacks=YEAR_HACKS):
180 '--format=format:%ad', # Author date
181 '--date=short', # YYYY-MM-DD
184 args.extend(['--follow', filename])
185 output = git_cmd('log', *args)
186 years = [int(line.split('-', 1)[0]) for line in output.splitlines()]
188 years.extend(year_hacks.values())
189 elif splitpath(filename) in year_hacks:
190 years.append(year_hacks[splitpath(filename)])
194 def authors(filename, author_hacks=AUTHOR_HACKS):
195 output = git_cmd('log', '--follow', '--format=format:%aN <%aE>',
196 filename) # Author name <author email>
197 ret = list(set(output.splitlines()))
198 if splitpath(filename) in author_hacks:
199 ret.extend(author_hacks[splitpath(filename)])
202 def authors_list(author_hacks=AUTHOR_HACKS):
203 output = git_cmd('log', '--format=format:%aN <%aE>')
204 ret = list(set(output.splitlines()))
205 for path,authors in author_hacks.items():
209 def is_versioned(filename):
210 output = git_cmd('log', '--follow', filename)
215 elif PROJECT_INFO['vcs'] == 'Mercurial':
219 import mercurial.dispatch
221 def mercurial_cmd(*args):
225 tmp_stdout = StringIO.StringIO()
226 tmp_stderr = StringIO.StringIO()
227 sys.stdout = tmp_stdout
228 sys.stderr = tmp_stderr
230 mercurial.dispatch.dispatch(list(args))
235 return (tmp_stdout.getvalue().rstrip('\n'),
236 tmp_stderr.getvalue().rstrip('\n'))
238 def original_year(filename=None, year_hacks=YEAR_HACKS):
240 '--template', '{date|shortdate}\n',
241 # shortdate filter: YEAR-MONTH-DAY
244 args.extend(['--follow', filename])
245 output,error = mercurial_cmd('log', *args)
246 years = [int(line.split('-', 1)[0]) for line in output.splitlines()]
248 years.extend(year_hacks.values())
249 elif splitpath(filename) in year_hacks:
250 years.append(year_hacks[splitpath(filename)])
254 def authors(filename, author_hacks=AUTHOR_HACKS):
255 output,error = mercurial_cmd('log', '--follow',
256 '--template', '{author}\n',
258 ret = list(set(output.splitlines()))
259 if splitpath(filename) in author_hacks:
260 ret.extend(author_hacks[splitpath(filename)])
263 def authors_list(author_hacks=AUTHOR_HACKS):
264 output,error = mercurial_cmd('log', '--template', '{author}\n')
265 ret = list(set(output.splitlines()))
266 for path,authors in author_hacks.items():
270 def is_versioned(filename):
271 output,error = mercurial_cmd('log', '--follow', filename)
276 elif PROJECT_INFO['vcs'] == 'Bazaar':
280 import bzrlib.builtins
283 class LogFormatter (bzrlib.log.LogFormatter):
284 supports_merge_revisions = True
286 supports_deta = False
287 supports_tags = False
288 supports_diff = False
290 def log_revision(self, revision):
291 raise NotImplementedError
293 class YearLogFormatter (LogFormatter):
294 def log_revision(self, revision):
296 time.strftime('%Y', time.gmtime(revision.rev.timestamp))
299 class AuthorLogFormatter (LogFormatter):
300 def log_revision(self, revision):
301 authors = revision.rev.get_apparent_authors()
302 self.to_file.write('\n'.join(authors)+'\n')
304 def original_year(filename=None, year_hacks=YEAR_HACKS):
305 cmd = bzrlib.builtins.cmd_log()
306 cmd.outf = StringIO.StringIO()
307 kwargs = {'log_format':YearLogFormatter, 'levels':0}
309 kwargs['file_list'] = [filenme]
311 years = [int(year) for year in set(cmd.outf.getvalue().splitlines())]
313 years.append(year_hacks.values())
314 elif splitpath(filename) in year_hacks:
315 years.append(year_hacks[splitpath(filename)])
319 def authors(filename, author_hacks=AUTHOR_HACKS):
320 cmd = bzrlib.builtins.cmd_log()
321 cmd.outf = StringIO.StringIO()
322 cmd.run(file_list=[filename], log_format=AuthorLogFormatter, levels=0)
323 ret = list(set(cmd.outf.getvalue().splitlines()))
324 if splitpath(filename) in author_hacks:
325 ret.extend(author_hacks[splitpath(filename)])
328 def authors_list(author_hacks=AUTHOR_HACKS):
329 cmd = bzrlib.builtins.cmd_log()
330 cmd.outf = StringIO.StringIO()
331 cmd.run(log_format=AuthorLogFormatter, levels=0)
332 output = cmd.outf.getvalue()
333 ret = list(set(cmd.outf.getvalue().splitlines()))
334 for path,authors in author_hacks.items():
338 def is_versioned(filename):
339 cmd = bzrlib.builtins.cmd_log()
340 cmd.outf = StringIO.StringIO()
341 cmd.run(file_list=[filename])
345 raise NotImplementedError('Unrecognized VCS: %(vcs)s' % PROJECT_INFO)
347 # General utility commands
349 def _strip_email(*args):
350 """Remove email addresses from a series of names.
355 >>> _strip_email('J Doe')
357 >>> _strip_email('J Doe <jdoe@a.com>')
359 >>> _strip_email('J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>')
360 ['J Doe', 'JJJ Smith']
363 for i,arg in enumerate(args):
366 author,addr = email.utils.parseaddr(arg)
372 def _reverse_aliases(aliases):
373 """Reverse an `aliases` dict.
375 Input: key: canonical name, value: list of aliases
376 Output: key: alias, value: canonical name
382 ... 'J Doe <jdoe@a.com>':['Johnny <jdoe@b.edu>', 'J'],
383 ... 'JJJ Smith <jjjs@a.com>':['Jingly <jjjs@b.edu>'],
384 ... None:['Anonymous <a@a.com>'],
386 >>> r = _reverse_aliases(aliases)
387 >>> for item in sorted(r.items()):
389 ('Anonymous <a@a.com>', None)
390 ('J', 'J Doe <jdoe@a.com>')
391 ('Jingly <jjjs@b.edu>', 'JJJ Smith <jjjs@a.com>')
392 ('Johnny <jdoe@b.edu>', 'J Doe <jdoe@a.com>')
395 for canonical_name,_aliases in aliases.items():
396 for alias in _aliases:
397 output[alias] = canonical_name
400 def _replace_aliases(authors, with_email=True, aliases=None):
401 """Consolidate and sort `authors`.
403 Make the replacements listed in the `aliases` dict (key: canonical
404 name, value: list of aliases). If `aliases` is ``None``, default
408 ... 'J Doe <jdoe@a.com>':['Johnny <jdoe@b.edu>'],
409 ... 'JJJ Smith <jjjs@a.com>':['Jingly <jjjs@b.edu>'],
410 ... None:['Anonymous <a@a.com>'],
413 ... 'JJJ Smith <jjjs@a.com>', 'Johnny <jdoe@b.edu>',
414 ... 'Jingly <jjjs@b.edu>', 'J Doe <jdoe@a.com>', 'Anonymous <a@a.com>']
415 >>> _replace_aliases(authors, with_email=True, aliases=aliases)
416 ['J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>']
417 >>> _replace_aliases(authors, with_email=False, aliases=aliases)
418 ['J Doe', 'JJJ Smith']
422 rev_aliases = _reverse_aliases(aliases)
423 for i,author in enumerate(authors):
424 if author in rev_aliases:
425 authors[i] = rev_aliases[author]
426 authors = sorted(list(set(authors)))
429 if with_email == False:
430 authors = _strip_email(*authors)
433 def _long_author_formatter(copyright_year_string, authors):
435 >>> print '\\n'.join(_long_author_formatter(
436 ... copyright_year_string='Copyright (C) 1990-2010',
437 ... authors=['Jack', 'Jill', 'John']))
438 Copyright (C) 1990-2010 Jack
442 lines = ['%s %s' % (copyright_year_string, authors[0])]
443 for author in authors[1:]:
444 lines.append(' '*(len(copyright_year_string)+1) + author)
447 def _short_author_formatter(copyright_year_string, authors):
449 >>> print '\\n'.join(_short_author_formatter(
450 ... copyright_year_string='Copyright (C) 1990-2010',
451 ... authors=['Jack', 'Jill', 'John']*5))
452 Copyright (C) 1990-2010 Jack, Jill, John, Jack, Jill, John, Jack, Jill, John, Jack, Jill, John, Jack, Jill, John
454 blurb = '%s %s' % (copyright_year_string, ', '.join(authors))
457 def _copyright_string(original_year, final_year, authors,
458 text=COPY_RIGHT_TEXT, extra_info={},
459 author_format_fn=_long_author_formatter,
460 formatter_kwargs={}, prefix='', wrap=True,
463 >>> print _copyright_string(original_year=2005,
465 ... authors=['A <a@a.com>', 'B <b@b.edu>'],
467 ... ) # doctest: +ELLIPSIS
468 # Copyright (C) 2005 A <a@a.com>
472 >>> print _copyright_string(original_year=2005,
474 ... authors=['A <a@a.com>', 'B <b@b.edu>']
475 ... ) # doctest: +ELLIPSIS
476 Copyright (C) 2005-2009 A <a@a.com>
480 >>> print _copyright_string(original_year=2005,
482 ... authors=['A <a@a.com>', 'B <b@b.edu>'],
483 ... text=SHORT_COPY_RIGHT_TEXT,
484 ... author_format_fn=_short_author_formatter,
485 ... extra_info={'get-details':'%(get-details)s'},
489 Copyright (C) 2005 A <a@a.com>, B <b@b.edu>
491 Hooke comes with ABSOLUTELY NO WARRANTY and is
492 licensed under the GNU Lesser General Public
493 License. For details, %(get-details)s.
494 >>> print _copyright_string(original_year=2005,
496 ... authors=['A <a@a.com>', 'B <b@b.edu>'],
497 ... text=SHORT_COPY_RIGHT_TEXT,
498 ... extra_info={'get-details':'%(get-details)s'},
499 ... author_format_fn=_short_author_formatter,
503 Copyright (C) 2005 A <a@a.com>, B <b@b.edu>
505 Hooke comes with ABSOLUTELY NO WARRANTY and is licensed under the GNU Lesser General Public License. For details, %(get-details)s.
507 for key in ['initial_indent', 'subsequent_indent']:
508 if key not in wrap_kwargs:
509 wrap_kwargs[key] = prefix
511 if original_year == final_year:
512 date_range = '%s' % original_year
514 date_range = '%s-%s' % (original_year, final_year)
515 copyright_year_string = 'Copyright (C) %s' % date_range
517 lines = author_format_fn(copyright_year_string, authors,
519 for i,line in enumerate(lines):
520 lines[i] = prefix + line
522 info = dict(PROJECT_INFO)
523 for key,value in extra_info.items():
525 text = [paragraph % info for paragraph in text]
528 text = [textwrap.fill(p, **wrap_kwargs) for p in text]
530 assert wrap_kwargs['subsequent_indent'] == '', \
531 wrap_kwargs['subsequent_indent']
532 sep = '\n%s\n' % prefix.rstrip()
533 return sep.join(['\n'.join(lines)] + text)
535 def _tag_copyright(contents):
537 >>> contents = '''Some file
539 ... # Copyright (copyright begins)
540 ... # (copyright continues)
545 >>> print _tag_copyright(contents).replace('COPY-RIGHT', 'CR')
555 for line in contents.splitlines():
556 if incopy == False and line.startswith('# Copyright'):
558 lines.append(COPY_RIGHT_TAG)
559 elif incopy == True and not line.startswith('#'):
562 lines.append(line.rstrip('\n'))
563 return '\n'.join(lines)+'\n'
565 def _update_copyright(contents, original_year, authors):
567 >>> contents = '''Some file
569 ... # Copyright (copyright begins)
570 ... # (copyright continues)
575 >>> print _update_copyright(contents, 2008, ['Jack', 'Jill']
576 ... ) # doctest: +ELLIPSIS, +REPORT_UDIFF
579 # Copyright (C) 2008-... Jack
587 current_year = time.gmtime()[0]
588 copyright_string = _copyright_string(
589 original_year, current_year, authors, prefix='# ')
590 contents = _tag_copyright(contents)
591 return contents.replace(COPY_RIGHT_TAG, copyright_string)
593 def ignored_file(filename, ignored_paths=None, ignored_files=None,
594 check_disk=True, check_vcs=True):
596 >>> ignored_paths = ['./a/', './b/']
597 >>> ignored_files = ['x', 'y']
598 >>> ignored_file('./a/z', ignored_paths, ignored_files, False, False)
600 >>> ignored_file('./ab/z', ignored_paths, ignored_files, False, False)
602 >>> ignored_file('./ab/x', ignored_paths, ignored_files, False, False)
604 >>> ignored_file('./ab/xy', ignored_paths, ignored_files, False, False)
606 >>> ignored_file('./z', ignored_paths, ignored_files, False, False)
609 if ignored_paths == None:
610 ignored_paths = IGNORED_PATHS
611 if ignored_files == None:
612 ignored_files = IGNORED_FILES
613 if check_disk == True and os.path.isfile(filename) == False:
615 for path in ignored_paths:
616 if filename.startswith(path):
618 if os.path.basename(filename) in ignored_files:
620 if check_vcs == True and is_versioned(filename) == False:
624 def _set_contents(filename, contents, original_contents=None, dry_run=False,
626 if original_contents == None and os.path.isfile(filename):
627 f = open(filename, 'r')
628 original_contents = f.read()
631 print "checking %s ... " % filename,
632 if contents != original_contents:
634 if original_contents == None:
638 if verbose > 1 and original_contents != None:
640 difflib.unified_diff(
641 original_contents.splitlines(), contents.splitlines(),
642 fromfile=os.path.normpath(os.path.join('a', filename)),
643 tofile=os.path.normpath(os.path.join('b', filename)),
646 f = file(filename, 'w')
654 def update_authors(authors_fn=authors_list, dry_run=False, verbose=0):
655 authors = authors_fn()
656 authors = _replace_aliases(authors, with_email=True, aliases=ALIASES)
657 new_contents = '%s was written by:\n%s\n' % (
658 PROJECT_INFO['project'],
661 _set_contents('AUTHORS', new_contents, dry_run=dry_run, verbose=verbose)
663 def update_file(filename, original_year_fn=original_year, authors_fn=authors,
664 dry_run=False, verbose=0):
665 f = file(filename, 'r')
669 original_year = original_year_fn(filename)
670 authors = authors_fn(filename)
671 authors = _replace_aliases(authors, with_email=True, aliases=ALIASES)
673 new_contents = _update_copyright(contents, original_year, authors)
674 _set_contents(filename, contents=new_contents, original_contents=contents,
675 dry_run=dry_run, verbose=verbose)
677 def update_files(files=None, dry_run=False, verbose=0):
678 if files == None or len(files) == 0:
680 for dirpath,dirnames,filenames in os.walk('.'):
681 for filename in filenames:
682 files.append(os.path.join(dirpath, filename))
684 for filename in files:
685 if ignored_file(filename) == True:
687 update_file(filename, dry_run=dry_run, verbose=verbose)
689 def update_pyfile(path, original_year_fn=original_year,
690 authors_fn=authors_list, dry_run=False, verbose=0):
691 original_year = original_year_fn()
692 current_year = time.gmtime()[0]
693 authors = authors_fn()
694 authors = _replace_aliases(authors, with_email=False, aliases=ALIASES)
695 paragraphs = _copyright_string(
696 original_year, current_year, authors,
697 text=SHORT_COPY_RIGHT_TEXT,
698 extra_info={'get-details':'%(get-details)s'},
699 author_format_fn=_short_author_formatter, wrap=False,
702 _copyright_string(original_year, current_year, authors, prefix='# '),
703 '', 'import textwrap', '', '',
705 _copyright_string(original_year, current_year, authors, prefix=''),
708 'def short_license(extra_info, wrap=True, **kwargs):',
712 lines.append(" '%s' %% extra_info," % p.replace("'", r"\'"))
716 ' for i,p in enumerate(paragraphs):',
717 ' paragraphs[i] = textwrap.fill(p, **kwargs)',
718 r" return '\n\n'.join(paragraphs)",
720 new_contents = '\n'.join(lines)+'\n'
721 _set_contents(path, new_contents, dry_run=dry_run, verbose=verbose)
728 if __name__ == '__main__':
732 usage = """%%prog [options] [file ...]
734 Update copyright information in source code with information from
735 the %(vcs)s repository. Run from the %(project)s repository root.
737 Replaces every line starting with '^# Copyright' and continuing with
738 '^#' with an auto-generated copyright blurb. If you want to add
739 #-commented material after a copyright blurb, please insert a blank
740 line between the blurb and your comment, so the next run of
741 ``update_copyright.py`` doesn't clobber your comment.
743 If no files are given, a list of files to update is generated
746 p = optparse.OptionParser(usage)
747 p.add_option('--pyfile', dest='pyfile', default='hooke/license.py',
749 help='Write project license info to a Python module at PATH')
750 p.add_option('--test', dest='test', default=False,
751 action='store_true', help='Run internal tests and exit')
752 p.add_option('--dry-run', dest='dry_run', default=False,
753 action='store_true', help="Don't make any changes")
754 p.add_option('-v', '--verbose', dest='verbose', default=0,
755 action='count', help='Increment verbosity')
756 options,args = p.parse_args()
758 if options.test == True:
762 update_authors(dry_run=options.dry_run, verbose=options.verbose)
763 update_files(files=args, dry_run=options.dry_run, verbose=options.verbose)
764 if options.pyfile != None:
765 update_pyfile(path=options.pyfile,
766 dry_run=options.dry_run, verbose=options.verbose)