3 # Copyright (C) 2010 W. Trevor King <wking@drexel.edu>
5 # This file is part of Cookbook.
7 # Cookbook 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 # Cookbook 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 Cookbook. 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/
37 'project': 'Cookbook',
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
62 # Convert author names to canonical forms.
63 # ALIASES[<canonical name>] = <list of aliases>
66 # 'John Doe <jdoe@a.com>':
67 # ['John Doe', 'jdoe', 'J. Doe <j@doe.net>'],
69 # Git-based projects are encouraged to use .mailmap instead of
70 # ALIASES. See git-shortlog(1) for details.
73 # List of paths that should not be scanned for copyright updates.
74 # IGNORED_PATHS = ['./.git/']
75 IGNORED_PATHS = ['./.git/', './recipe/', './cookbook/static/',
76 './cookbook/template/']
77 # List of files that should not be scanned for copyright updates.
78 # IGNORED_FILES = ['COPYING']
79 IGNORED_FILES = ['COPYING']
81 # Work around missing author holes in the VCS history.
82 # AUTHOR_HACKS[<path tuple>] = [<missing authors]
83 # for example, if John Doe contributed to module.py but wasn't listed
84 # in the VCS history of that file:
86 # ('path', 'to', 'module.py'):['John Doe'],
90 # Work around missing year holes in the VCS history.
91 # YEAR_HACKS[<path tuple>] = <original year>
92 # for example, if module.py was published in 2008 but the VCS history
93 # only goes back to 2010:
95 # ('path', 'to', 'module.py'):2008,
99 # Helpers for VCS-specific commands
102 """Recursively split a path into elements.
107 >>> splitpath(os.path.join('a', 'b', 'c'))
109 >>> splitpath(os.path.join('.', 'a', 'b', 'c'))
112 path = os.path.normpath(path)
115 dirname,basename = os.path.split(path)
116 elements.insert(0,basename)
117 if dirname in ['', '.']:
120 return tuple(elements)
122 # VCS-specific commands
124 if PROJECT_INFO['vcs'] == 'Git':
128 _MSWINDOWS = sys.platform == 'win32'
129 _POSIX = not _MSWINDOWS
131 def invoke(args, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, expect=(0,)):
133 expect should be a tuple of allowed exit codes.
137 q = subprocess.Popen(args, stdin=subprocess.PIPE,
138 stdout=stdout, stderr=stderr)
140 assert _MSWINDOWS == True, 'invalid platform'
141 # win32 don't have os.execvp() so run the command in a shell
142 q = subprocess.Popen(args, stdin=subprocess.PIPE,
143 stdout=stdout, stderr=stderr, shell=True)
145 raise ValueError([args, e])
146 stdout,stderr = q.communicate(input=stdin)
148 if status not in expect:
149 raise ValueError([args, status, stdout, stderr])
150 return status, stdout, stderr
153 status,stdout,stderr = invoke(['git'] + list(args))
154 return stdout.rstrip('\n')
156 def original_year(filename, year_hacks=YEAR_HACKS):
157 output = git_cmd('log', '--follow',
158 '--format=format:%ad', # Author date
159 '--date=short', # YYYY-MM-DD
161 years = [int(line.split('-', 1)[0]) for line in output.splitlines()]
162 if splitpath(filename) in year_hacks:
163 years.append(year_hacks[splitpath(filename)])
167 def authors(filename, author_hacks=AUTHOR_HACKS):
168 output = git_cmd('log', '--follow', '--format=format:%aN <%aE>',
169 filename) # Author name <author email>
170 ret = list(set(output.splitlines()))
171 if splitpath(filename) in author_hacks:
172 ret.extend(author_hacks[splitpath(filename)])
175 def authors_list(author_hacks=AUTHOR_HACKS):
176 output = git_cmd('log', '--format=format:%aN <%aE>')
177 ret = list(set(output.splitlines()))
178 for path,authors in author_hacks.items():
182 def is_versioned(filename):
183 output = git_cmd('log', '--follow', filename)
188 elif PROJECT_INFO['vcs'] == 'Mercurial':
192 import mercurial.dispatch
194 def mercurial_cmd(*args):
198 tmp_stdout = StringIO.StringIO()
199 tmp_stderr = StringIO.StringIO()
200 sys.stdout = tmp_stdout
201 sys.stderr = tmp_stderr
203 mercurial.dispatch.dispatch(list(args))
208 return (tmp_stdout.getvalue().rstrip('\n'),
209 tmp_stderr.getvalue().rstrip('\n'))
211 def original_year(filename, year_hacks=YEAR_HACKS):
212 # shortdate filter: YEAR-MONTH-DAY
213 output,error = mercurial_cmd('log', '--follow',
214 '--template', '{date|shortdate}\n',
216 years = [int(line.split('-', 1)[0]) for line in output.splitlines()]
217 if splitpath(filename) in year_hacks:
218 years.append(year_hacks[splitpath(filename)])
222 def authors(filename, author_hacks=AUTHOR_HACKS):
223 output,error = mercurial_cmd('log', '--follow',
224 '--template', '{author}\n',
226 ret = list(set(output.splitlines()))
227 if splitpath(filename) in author_hacks:
228 ret.extend(author_hacks[splitpath(filename)])
231 def authors_list(author_hacks=AUTHOR_HACKS):
232 output,error = mercurial_cmd('log', '--template', '{author}\n')
233 ret = list(set(output.splitlines()))
234 for path,authors in author_hacks.items():
238 def is_versioned(filename):
239 output,error = mercurial_cmd('log', '--follow', filename)
244 elif PROJECT_INFO['vcs'] == 'Bazaar':
248 import bzrlib.builtins
251 class LogFormatter (bzrlib.log.LogFormatter):
252 supports_merge_revisions = True
254 supports_deta = False
255 supports_tags = False
256 supports_diff = False
258 def log_revision(self, revision):
259 raise NotImplementedError
261 class YearLogFormatter (LogFormatter):
262 def log_revision(self, revision):
264 time.strftime('%Y', time.gmtime(revision.rev.timestamp))
267 class AuthorLogFormatter (LogFormatter):
268 def log_revision(self, revision):
269 authors = revision.rev.get_apparent_authors()
270 self.to_file.write('\n'.join(authors)+'\n')
272 def original_year(filename, year_hacks=YEAR_HACKS):
273 cmd = bzrlib.builtins.cmd_log()
274 cmd.outf = StringIO.StringIO()
275 cmd.run(file_list=[filename], log_format=YearLogFormatter, levels=0)
276 years = [int(year) for year in set(cmd.outf.getvalue().splitlines())]
277 if splitpath(filename) in year_hacks:
278 years.append(year_hacks[splitpath(filename)])
282 def authors(filename, author_hacks=AUTHOR_HACKS):
283 cmd = bzrlib.builtins.cmd_log()
284 cmd.outf = StringIO.StringIO()
285 cmd.run(file_list=[filename], log_format=AuthorLogFormatter, levels=0)
286 ret = list(set(cmd.outf.getvalue().splitlines()))
287 if splitpath(filename) in author_hacks:
288 ret.extend(author_hacks[splitpath(filename)])
291 def authors_list(author_hacks=AUTHOR_HACKS):
292 cmd = bzrlib.builtins.cmd_log()
293 cmd.outf = StringIO.StringIO()
294 cmd.run(log_format=AuthorLogFormatter, levels=0)
295 output = cmd.outf.getvalue()
296 ret = list(set(cmd.outf.getvalue().splitlines()))
297 for path,authors in author_hacks.items():
301 def is_versioned(filename):
302 cmd = bzrlib.builtins.cmd_log()
303 cmd.outf = StringIO.StringIO()
304 cmd.run(file_list=[filename])
308 raise NotImplementedError('Unrecognized VCS: %(vcs)s' % PROJECT_INFO)
310 # General utility commands
312 def _strip_email(*args):
313 """Remove email addresses from a series of names.
318 >>> _strip_email('J Doe <jdoe@a.com>')
320 >>> _strip_email('J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>')
321 ['J Doe', 'JJJ Smith']
324 for i,arg in enumerate(args):
327 author,addr = email.utils.parseaddr(arg)
331 def _reverse_aliases(aliases):
332 """Reverse an `aliases` dict.
334 Input: key: canonical name, value: list of aliases
335 Output: key: alias, value: canonical name
341 ... 'J Doe <jdoe@a.com>':['Johnny <jdoe@b.edu>', 'J'],
342 ... 'JJJ Smith <jjjs@a.com>':['Jingly <jjjs@b.edu>'],
343 ... None:['Anonymous <a@a.com>'],
345 >>> r = _reverse_aliases(aliases)
346 >>> for item in sorted(r.items()):
348 ('Anonymous <a@a.com>', None)
349 ('J', 'J Doe <jdoe@a.com>')
350 ('Jingly <jjjs@b.edu>', 'JJJ Smith <jjjs@a.com>')
351 ('Johnny <jdoe@b.edu>', 'J Doe <jdoe@a.com>')
354 for canonical_name,_aliases in aliases.items():
355 for alias in _aliases:
356 output[alias] = canonical_name
359 def _replace_aliases(authors, with_email=True, aliases=None):
360 """Consolidate and sort `authors`.
362 Make the replacements listed in the `aliases` dict (key: canonical
363 name, value: list of aliases). If `aliases` is ``None``, default
367 ... 'J Doe <jdoe@a.com>':['Johnny <jdoe@b.edu>'],
368 ... 'JJJ Smith <jjjs@a.com>':['Jingly <jjjs@b.edu>'],
369 ... None:['Anonymous <a@a.com>'],
371 >>> _replace_aliases(['JJJ Smith <jjjs@a.com>', 'Johnny <jdoe@b.edu>',
372 ... 'Jingly <jjjs@b.edu>', 'Anonymous <a@a.com>'],
373 ... with_email=True, aliases=aliases)
374 ['J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>']
375 >>> _replace_aliases(['JJJ Smith', 'Johnny', 'Jingly', 'Anonymous'],
376 ... with_email=False, aliases=aliases)
377 ['J Doe', 'JJJ Smith']
378 >>> _replace_aliases(['JJJ Smith <jjjs@a.com>', 'Johnny <jdoe@b.edu>',
379 ... 'Jingly <jjjs@b.edu>', 'J Doe <jdoe@a.com>'],
380 ... with_email=True, aliases=aliases)
381 ['J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>']
385 if with_email == False:
386 aliases = dict([(_strip_email(author)[0], _strip_email(*_aliases))
387 for author,_aliases in aliases.items()])
388 rev_aliases = _reverse_aliases(aliases)
389 for i,author in enumerate(authors):
390 if author in rev_aliases:
391 authors[i] = rev_aliases[author]
392 authors = sorted(list(set(authors)))
397 def _copyright_string(original_year, final_year, authors, prefix=''):
399 >>> print _copyright_string(original_year=2005,
401 ... authors=['A <a@a.com>', 'B <b@b.edu>'],
403 ... ) # doctest: +ELLIPSIS
404 # Copyright (C) 2005 A <a@a.com>
408 >>> print _copyright_string(original_year=2005,
410 ... authors=['A <a@a.com>', 'B <b@b.edu>']
411 ... ) # doctest: +ELLIPSIS
412 Copyright (C) 2005-2009 A <a@a.com>
417 if original_year == final_year:
418 date_range = '%s' % original_year
420 date_range = '%s-%s' % (original_year, final_year)
421 lines = ['Copyright (C) %s %s' % (date_range, authors[0])]
422 for author in authors[1:]:
423 lines.append(' '*(len('Copyright (C) ')+len(date_range)+1) +
426 lines.extend((COPY_RIGHT_TEXT % PROJECT_INFO).splitlines())
427 for i,line in enumerate(lines):
428 lines[i] = (prefix + line).rstrip()
429 return '\n'.join(lines)
431 def _tag_copyright(contents):
433 >>> contents = '''Some file
435 ... # Copyright (copyright begins)
436 ... # (copyright continues)
441 >>> print _tag_copyright(contents).replace('COPY-RIGHT', 'CR')
451 for line in contents.splitlines():
452 if incopy == False and line.startswith('# Copyright'):
454 lines.append(COPY_RIGHT_TAG)
455 elif incopy == True and not line.startswith('#'):
458 lines.append(line.rstrip('\n'))
459 return '\n'.join(lines)+'\n'
461 def _update_copyright(contents, original_year, authors):
463 >>> contents = '''Some file
465 ... # Copyright (copyright begins)
466 ... # (copyright continues)
471 >>> print _update_copyright(contents, 2008, ['Jack', 'Jill']
472 ... ) # doctest: +ELLIPSIS, +REPORT_UDIFF
475 # Copyright (C) 2008-... Jack
483 current_year = time.gmtime()[0]
484 copyright_string = _copyright_string(
485 original_year, current_year, authors, prefix='# ')
486 contents = _tag_copyright(contents)
487 return contents.replace(COPY_RIGHT_TAG, copyright_string)
489 def ignored_file(filename, ignored_paths=None, ignored_files=None,
490 check_disk=True, check_vcs=True):
492 >>> ignored_paths = ['./a/', './b/']
493 >>> ignored_files = ['x', 'y']
494 >>> ignored_file('./a/z', ignored_paths, ignored_files, False, False)
496 >>> ignored_file('./ab/z', ignored_paths, ignored_files, False, False)
498 >>> ignored_file('./ab/x', ignored_paths, ignored_files, False, False)
500 >>> ignored_file('./ab/xy', ignored_paths, ignored_files, False, False)
502 >>> ignored_file('./z', ignored_paths, ignored_files, False, False)
505 if ignored_paths == None:
506 ignored_paths = IGNORED_PATHS
507 if ignored_files == None:
508 ignored_files = IGNORED_FILES
509 if check_disk == True and os.path.isfile(filename) == False:
511 for path in ignored_paths:
512 if filename.startswith(path):
514 if os.path.basename(filename) in ignored_files:
516 if check_vcs == True and is_versioned(filename) == False:
520 def _set_contents(filename, contents, original_contents=None, dry_run=False,
522 if original_contents == None and os.path.isfile(filename):
523 f = open(filename, 'r')
524 original_contents = f.read()
527 print "checking %s ... " % filename,
528 if contents != original_contents:
530 if original_contents == None:
534 if verbose > 1 and original_contents != None:
536 difflib.unified_diff(
537 original_contents.splitlines(), contents.splitlines(),
538 fromfile=os.path.normpath(os.path.join('a', filename)),
539 tofile=os.path.normpath(os.path.join('b', filename)),
542 f = file(filename, 'w')
550 def update_authors(authors_fn=authors_list, dry_run=False, verbose=0):
551 authors = authors_fn()
552 authors = _replace_aliases(authors, with_email=True, aliases=ALIASES)
553 new_contents = '%s was written by:\n%s\n' % (
554 PROJECT_INFO['project'],
557 _set_contents('AUTHORS', new_contents, dry_run=dry_run, verbose=verbose)
559 def update_file(filename, original_year_fn=original_year, authors_fn=authors,
560 dry_run=False, verbose=0):
561 f = file(filename, 'r')
565 original_year = original_year_fn(filename)
566 authors = authors_fn(filename)
567 authors = _replace_aliases(authors, with_email=True, aliases=ALIASES)
569 new_contents = _update_copyright(contents, original_year, authors)
570 _set_contents(filename, contents=new_contents, original_contents=contents,
571 dry_run=dry_run, verbose=verbose)
573 def update_files(files=None, dry_run=False, verbose=0):
574 if files == None or len(files) == 0:
576 for dirpath,dirnames,filenames in os.walk('.'):
577 for filename in filenames:
578 files.append(os.path.join(dirpath, filename))
580 for filename in files:
581 if ignored_file(filename) == True:
583 update_file(filename, dry_run=dry_run, verbose=verbose)
589 if __name__ == '__main__':
593 usage = """%%prog [options] [file ...]
595 Update copyright information in source code with information from
596 the %(vcs)s repository. Run from the %(project)s repository root.
598 Replaces every line starting with '^# Copyright' and continuing with
599 '^#' with an auto-generated copyright blurb. If you want to add
600 #-commented material after a copyright blurb, please insert a blank
601 line between the blurb and your comment, so the next run of
602 ``update_copyright.py`` doesn't clobber your comment.
604 If no files are given, a list of files to update is generated
607 p = optparse.OptionParser(usage)
608 p.add_option('--test', dest='test', default=False,
609 action='store_true', help='Run internal tests and exit')
610 p.add_option('--dry-run', dest='dry_run', default=False,
611 action='store_true', help="Don't make any changes")
612 p.add_option('-v', '--verbose', dest='verbose', default=0,
613 action='count', help='Increment verbosity')
614 options,args = p.parse_args()
616 if options.test == True:
620 update_authors(dry_run=options.dry_run, verbose=options.verbose)
621 update_files(files=args, dry_run=options.dry_run, verbose=options.verbose)