3 # Copyright (C) 2009-2011 W. Trevor King <wking@drexel.edu>
5 # This file is part of Bugs Everywhere.
7 # Bugs Everywhere 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 # Bugs Everywhere is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 # General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with Bugs Everywhere. If not, see <http://www.gnu.org/licenses/>.
20 """Automatically update copyright boilerplate.
22 This script is adapted from one written for `Bugs Everywhere`_. and
23 later modified for `Hooke`_ before returning to `Bugs Everywhere`_.
25 .. _Bugs Everywhere: http://bugseverywhere.org/
26 .. _Hooke: http://code.google.com/p/hooke/
43 # Break "copyright" into "copy" and "right" to avoid matching the
46 This file is part of %(project)s.
48 %(project)s is free software; you can redistribute it and/or modify it
49 under the terms of the GNU General Public License as published by the
50 Free Software Foundation, either version 3 of the License, or (at your
51 option) any later version.
53 %(project)s is distributed in the hope that it will be useful, but
54 WITHOUT ANY WARRANTY; without even the implied warranty of
55 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
56 General Public License for more details.
58 You should have received a copy of the GNU General Public License
59 along with %(project)s. If not, see <http://www.gnu.org/licenses/>.
62 COPY_RIGHT_TAG='-xyz-COPY' + '-RIGHT-zyx-' # unlikely to occur in the wild :p
64 # Convert author names to canonical forms.
65 # ALIASES[<canonical name>] = <list of aliases>
68 # 'John Doe <jdoe@a.com>':
69 # ['John Doe', 'jdoe', 'J. Doe <j@doe.net>'],
71 # Git-based projects are encouraged to use .mailmap instead of
72 # ALIASES. See git-shortlog(1) for details.
75 # List of paths that should not be scanned for copyright updates.
76 # IGNORED_PATHS = ['./.git/']
77 IGNORED_PATHS = ['./.git/', './build/']
78 # List of files that should not be scanned for copyright updates.
79 # IGNORED_FILES = ['COPYING']
80 IGNORED_FILES = ['COPYING', 'MANIFEST.in', 'README', 'veeco_header']
82 # Work around missing author holes in the VCS history.
83 # AUTHOR_HACKS[<path tuple>] = [<missing authors]
84 # for example, if John Doe contributed to module.py but wasn't listed
85 # in the VCS history of that file:
87 # ('path', 'to', 'module.py'):['John Doe'],
91 # Work around missing year holes in the VCS history.
92 # YEAR_HACKS[<path tuple>] = <original year>
93 # for example, if module.py was published in 2008 but the VCS history
94 # only goes back to 2010:
96 # ('path', 'to', 'module.py'):2008,
100 # Helpers for VCS-specific commands
103 """Recursively split a path into elements.
108 >>> splitpath(os.path.join('a', 'b', 'c'))
110 >>> splitpath(os.path.join('.', 'a', 'b', 'c'))
113 path = os.path.normpath(path)
116 dirname,basename = os.path.split(path)
117 elements.insert(0,basename)
118 if dirname in ['', '.']:
121 return tuple(elements)
123 # VCS-specific commands
125 if PROJECT_INFO['vcs'] == 'Git':
129 _MSWINDOWS = sys.platform == 'win32'
130 _POSIX = not _MSWINDOWS
132 def invoke(args, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, expect=(0,)):
134 expect should be a tuple of allowed exit codes.
138 q = subprocess.Popen(args, stdin=subprocess.PIPE,
139 stdout=stdout, stderr=stderr)
141 assert _MSWINDOWS == True, 'invalid platform'
142 # win32 don't have os.execvp() so run the command in a shell
143 q = subprocess.Popen(args, stdin=subprocess.PIPE,
144 stdout=stdout, stderr=stderr, shell=True)
146 raise ValueError([args, e])
147 stdout,stderr = q.communicate(input=stdin)
149 if status not in expect:
150 raise ValueError([args, status, stdout, stderr])
151 return status, stdout, stderr
154 status,stdout,stderr = invoke(['git'] + list(args))
155 return stdout.rstrip('\n')
157 version = git_cmd('--version').split(' ')[-1]
158 if version.startswith('1.5.'):
159 # Author name <author email>
160 author_format = '--pretty=format:%an <%ae>'
161 year_format = ['--pretty=format:%ai'] # Author date
162 # YYYY-MM-DD HH:MM:SS Z
163 # Earlier versions of Git don't seem to recognize --date=short
165 author_format = '--pretty=format:%aN <%aE>'
166 year_format = ['--pretty=format:%ad', # Author date
167 '--date=short'] # YYYY-MM-DD
169 def original_year(filename, year_hacks=YEAR_HACKS):
170 output = git_cmd(*(['log', '--follow']
173 if version.startswith('1.5.'):
174 output = '\n'.join([x.split()[0] for x in output.splitlines()])
175 years = [int(line.split('-', 1)[0]) for line in output.splitlines()]
176 if splitpath(filename) in year_hacks:
177 years.append(year_hacks[splitpath(filename)])
181 def authors(filename, author_hacks=AUTHOR_HACKS):
182 output = git_cmd('log', '--follow', author_format,
184 ret = list(set(output.splitlines()))
185 if splitpath(filename) in author_hacks:
186 ret.extend(author_hacks[splitpath(filename)])
189 def authors_list(author_hacks=AUTHOR_HACKS):
190 output = git_cmd('log', author_format)
191 ret = list(set(output.splitlines()))
192 for path,authors in author_hacks.items():
196 def is_versioned(filename):
197 output = git_cmd('log', '--follow', filename)
202 elif PROJECT_INFO['vcs'] == 'Mercurial':
206 import mercurial.dispatch
208 def mercurial_cmd(*args):
212 tmp_stdout = StringIO.StringIO()
213 tmp_stderr = StringIO.StringIO()
214 sys.stdout = tmp_stdout
215 sys.stderr = tmp_stderr
217 mercurial.dispatch.dispatch(list(args))
222 return (tmp_stdout.getvalue().rstrip('\n'),
223 tmp_stderr.getvalue().rstrip('\n'))
225 def original_year(filename, year_hacks=YEAR_HACKS):
226 # shortdate filter: YEAR-MONTH-DAY
227 output,error = mercurial_cmd('log', '--follow',
228 '--template', '{date|shortdate}\n',
230 years = [int(line.split('-', 1)[0]) for line in output.splitlines()]
231 if splitpath(filename) in year_hacks:
232 years.append(year_hacks[splitpath(filename)])
236 def authors(filename, author_hacks=AUTHOR_HACKS):
237 output,error = mercurial_cmd('log', '--follow',
238 '--template', '{author}\n',
240 ret = list(set(output.splitlines()))
241 if splitpath(filename) in author_hacks:
242 ret.extend(author_hacks[splitpath(filename)])
245 def authors_list(author_hacks=AUTHOR_HACKS):
246 output,error = mercurial_cmd('log', '--template', '{author}\n')
247 ret = list(set(output.splitlines()))
248 for path,authors in author_hacks.items():
252 def is_versioned(filename):
253 output,error = mercurial_cmd('log', '--follow', filename)
258 elif PROJECT_INFO['vcs'] == 'Bazaar':
262 import bzrlib.builtins
265 class LogFormatter (bzrlib.log.LogFormatter):
266 supports_merge_revisions = True
268 supports_deta = False
269 supports_tags = False
270 supports_diff = False
272 def log_revision(self, revision):
273 raise NotImplementedError
275 class YearLogFormatter (LogFormatter):
276 def log_revision(self, revision):
278 time.strftime('%Y', time.gmtime(revision.rev.timestamp))
281 class AuthorLogFormatter (LogFormatter):
282 def log_revision(self, revision):
283 authors = revision.rev.get_apparent_authors()
284 self.to_file.write('\n'.join(authors)+'\n')
286 def original_year(filename, year_hacks=YEAR_HACKS):
287 cmd = bzrlib.builtins.cmd_log()
288 cmd.outf = StringIO.StringIO()
289 cmd.run(file_list=[filename], log_format=YearLogFormatter, levels=0)
290 years = [int(year) for year in set(cmd.outf.getvalue().splitlines())]
291 if splitpath(filename) in year_hacks:
292 years.append(year_hacks[splitpath(filename)])
296 def authors(filename, author_hacks=AUTHOR_HACKS):
297 cmd = bzrlib.builtins.cmd_log()
298 cmd.outf = StringIO.StringIO()
299 cmd.run(file_list=[filename], log_format=AuthorLogFormatter, levels=0)
300 ret = list(set(cmd.outf.getvalue().splitlines()))
301 if splitpath(filename) in author_hacks:
302 ret.extend(author_hacks[splitpath(filename)])
305 def authors_list(author_hacks=AUTHOR_HACKS):
306 cmd = bzrlib.builtins.cmd_log()
307 cmd.outf = StringIO.StringIO()
308 cmd.run(log_format=AuthorLogFormatter, levels=0)
309 output = cmd.outf.getvalue()
310 ret = list(set(cmd.outf.getvalue().splitlines()))
311 for path,authors in author_hacks.items():
315 def is_versioned(filename):
316 cmd = bzrlib.builtins.cmd_log()
317 cmd.outf = StringIO.StringIO()
318 cmd.run(file_list=[filename])
322 raise NotImplementedError('Unrecognized VCS: %(vcs)s' % PROJECT_INFO)
324 # General utility commands
326 def _strip_email(*args):
327 """Remove email addresses from a series of names.
332 >>> _strip_email('J Doe <jdoe@a.com>')
334 >>> _strip_email('J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>')
335 ['J Doe', 'JJJ Smith']
338 for i,arg in enumerate(args):
341 author,addr = email.utils.parseaddr(arg)
345 def _reverse_aliases(aliases):
346 """Reverse an `aliases` dict.
348 Input: key: canonical name, value: list of aliases
349 Output: key: alias, value: canonical name
355 ... 'J Doe <jdoe@a.com>':['Johnny <jdoe@b.edu>', 'J'],
356 ... 'JJJ Smith <jjjs@a.com>':['Jingly <jjjs@b.edu>'],
357 ... None:['Anonymous <a@a.com>'],
359 >>> r = _reverse_aliases(aliases)
360 >>> for item in sorted(r.items()):
362 ('Anonymous <a@a.com>', None)
363 ('J', 'J Doe <jdoe@a.com>')
364 ('Jingly <jjjs@b.edu>', 'JJJ Smith <jjjs@a.com>')
365 ('Johnny <jdoe@b.edu>', 'J Doe <jdoe@a.com>')
368 for canonical_name,_aliases in aliases.items():
369 for alias in _aliases:
370 output[alias] = canonical_name
373 def _replace_aliases(authors, with_email=True, aliases=None):
374 """Consolidate and sort `authors`.
376 Make the replacements listed in the `aliases` dict (key: canonical
377 name, value: list of aliases). If `aliases` is ``None``, default
381 ... 'J Doe <jdoe@a.com>':['Johnny <jdoe@b.edu>'],
382 ... 'JJJ Smith <jjjs@a.com>':['Jingly <jjjs@b.edu>'],
383 ... None:['Anonymous <a@a.com>'],
385 >>> _replace_aliases(['JJJ Smith <jjjs@a.com>', 'Johnny <jdoe@b.edu>',
386 ... 'Jingly <jjjs@b.edu>', 'Anonymous <a@a.com>'],
387 ... with_email=True, aliases=aliases)
388 ['J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>']
389 >>> _replace_aliases(['JJJ Smith', 'Johnny', 'Jingly', 'Anonymous'],
390 ... with_email=False, aliases=aliases)
391 ['J Doe', 'JJJ Smith']
392 >>> _replace_aliases(['JJJ Smith <jjjs@a.com>', 'Johnny <jdoe@b.edu>',
393 ... 'Jingly <jjjs@b.edu>', 'J Doe <jdoe@a.com>'],
394 ... with_email=True, aliases=aliases)
395 ['J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>']
399 if with_email == False:
400 aliases = dict([(_strip_email(author)[0], _strip_email(*_aliases))
401 for author,_aliases in aliases.items()])
402 rev_aliases = _reverse_aliases(aliases)
403 for i,author in enumerate(authors):
404 if author in rev_aliases:
405 authors[i] = rev_aliases[author]
406 authors = sorted(list(set(authors)))
411 def _copyright_string(original_year, final_year, authors, prefix=''):
413 >>> print _copyright_string(original_year=2005,
415 ... authors=['A <a@a.com>', 'B <b@b.edu>'],
417 ... ) # doctest: +ELLIPSIS
418 # Copyright (C) 2005 A <a@a.com>
422 >>> print _copyright_string(original_year=2005,
424 ... authors=['A <a@a.com>', 'B <b@b.edu>']
425 ... ) # doctest: +ELLIPSIS
426 Copyright (C) 2005-2009 A <a@a.com>
431 if original_year == final_year:
432 date_range = '%s' % original_year
434 date_range = '%s-%s' % (original_year, final_year)
435 lines = ['Copyright (C) %s %s' % (date_range, authors[0])]
436 for author in authors[1:]:
437 lines.append(' '*(len('Copyright (C) ')+len(date_range)+1) +
440 lines.extend((COPY_RIGHT_TEXT % PROJECT_INFO).splitlines())
441 for i,line in enumerate(lines):
442 lines[i] = (prefix + line).rstrip()
443 return '\n'.join(lines)
445 def _tag_copyright(contents):
447 >>> contents = '''Some file
449 ... # Copyright (copyright begins)
450 ... # (copyright continues)
455 >>> print _tag_copyright(contents).replace('COPY-RIGHT', 'CR')
465 for line in contents.splitlines():
466 if incopy == False and line.startswith('# Copyright'):
468 lines.append(COPY_RIGHT_TAG)
469 elif incopy == True and not line.startswith('#'):
472 lines.append(line.rstrip('\n'))
473 return '\n'.join(lines)+'\n'
475 def _update_copyright(contents, original_year, authors):
477 >>> contents = '''Some file
479 ... # Copyright (copyright begins)
480 ... # (copyright continues)
485 >>> print _update_copyright(contents, 2008, ['Jack', 'Jill']
486 ... ) # doctest: +ELLIPSIS, +REPORT_UDIFF
489 # Copyright (C) 2008-... Jack
497 current_year = time.gmtime()[0]
498 copyright_string = _copyright_string(
499 original_year, current_year, authors, prefix='# ')
500 contents = _tag_copyright(contents)
501 return contents.replace(COPY_RIGHT_TAG, copyright_string)
503 def ignored_file(filename, ignored_paths=None, ignored_files=None,
504 check_disk=True, check_vcs=True):
506 >>> ignored_paths = ['./a/', './b/']
507 >>> ignored_files = ['x', 'y']
508 >>> ignored_file('./a/z', ignored_paths, ignored_files, False, False)
510 >>> ignored_file('./ab/z', ignored_paths, ignored_files, False, False)
512 >>> ignored_file('./ab/x', ignored_paths, ignored_files, False, False)
514 >>> ignored_file('./ab/xy', ignored_paths, ignored_files, False, False)
516 >>> ignored_file('./z', ignored_paths, ignored_files, False, False)
519 if ignored_paths == None:
520 ignored_paths = IGNORED_PATHS
521 if ignored_files == None:
522 ignored_files = IGNORED_FILES
523 if check_disk == True and os.path.isfile(filename) == False:
525 for path in ignored_paths:
526 if filename.startswith(path):
528 if os.path.basename(filename) in ignored_files:
530 if check_vcs == True and is_versioned(filename) == False:
534 def _set_contents(filename, contents, original_contents=None, dry_run=False,
536 if original_contents == None and os.path.isfile(filename):
537 f = open(filename, 'r')
538 original_contents = f.read()
541 print "checking %s ... " % filename,
542 if contents != original_contents:
544 if original_contents == None:
548 if verbose > 1 and original_contents != None:
550 difflib.unified_diff(
551 original_contents.splitlines(), contents.splitlines(),
552 fromfile=os.path.normpath(os.path.join('a', filename)),
553 tofile=os.path.normpath(os.path.join('b', filename)),
556 f = file(filename, 'w')
564 def update_authors(authors_fn=authors_list, dry_run=False, verbose=0):
565 authors = authors_fn()
566 authors = _replace_aliases(authors, with_email=True, aliases=ALIASES)
567 new_contents = '%s was written by:\n%s\n' % (
568 PROJECT_INFO['project'],
571 _set_contents('AUTHORS', new_contents, dry_run=dry_run, verbose=verbose)
573 def update_file(filename, original_year_fn=original_year, authors_fn=authors,
574 dry_run=False, verbose=0):
575 f = file(filename, 'r')
579 original_year = original_year_fn(filename)
580 authors = authors_fn(filename)
581 authors = _replace_aliases(authors, with_email=True, aliases=ALIASES)
583 new_contents = _update_copyright(contents, original_year, authors)
584 _set_contents(filename, contents=new_contents, original_contents=contents,
585 dry_run=dry_run, verbose=verbose)
587 def update_files(files=None, dry_run=False, verbose=0):
588 if files == None or len(files) == 0:
590 for dirpath,dirnames,filenames in os.walk('.'):
591 for filename in filenames:
592 files.append(os.path.join(dirpath, filename))
594 for filename in files:
595 if ignored_file(filename) == True:
597 update_file(filename, dry_run=dry_run, verbose=verbose)
603 if __name__ == '__main__':
607 usage = """%%prog [options] [file ...]
609 Update copyright information in source code with information from
610 the %(vcs)s repository. Run from the %(project)s repository root.
612 Replaces every line starting with '^# Copyright' and continuing with
613 '^#' with an auto-generated copyright blurb. If you want to add
614 #-commented material after a copyright blurb, please insert a blank
615 line between the blurb and your comment, so the next run of
616 ``update_copyright.py`` doesn't clobber your comment.
618 If no files are given, a list of files to update is generated
621 p = optparse.OptionParser(usage)
622 p.add_option('--test', dest='test', default=False,
623 action='store_true', help='Run internal tests and exit')
624 p.add_option('--dry-run', dest='dry_run', default=False,
625 action='store_true', help="Don't make any changes")
626 p.add_option('-v', '--verbose', dest='verbose', default=0,
627 action='count', help='Increment verbosity')
628 options,args = p.parse_args()
630 if options.test == True:
634 update_authors(dry_run=options.dry_run, verbose=options.verbose)
635 update_files(files=args, dry_run=options.dry_run, verbose=options.verbose)