5 """Automatically update copyright boilerplate.
7 This script is adapted from one written for `Bugs Everywhere`_.
9 .. _Bugs Everywhere: http://bugseverywhere.org/
22 import mercurial.dispatch
30 # Break "copyright" into "copy" and "right" to avoid matching the
33 This file is part of %(project)s.
35 %(project)s is free software: you can redistribute it and/or
36 modify it under the terms of the GNU Lesser General Public
37 License as published by the Free Software Foundation, either
38 version 3 of the License, or (at your option) any later version.
40 %(project)s is distributed in the hope that it will be useful,
41 but WITHOUT ANY WARRANTY; without even the implied warranty of
42 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
43 GNU Lesser General Public License for more details.
45 You should have received a copy of the GNU Lesser General Public
46 License along with %(project)s. If not, see
47 <http://www.gnu.org/licenses/>.
50 COPY_RIGHT_TAG='-xyz-COPY' + '-RIGHT-zyx-' # unlikely to occur in the wild :p
53 'Alberto Gomez-Casado':
55 'Massimo Sandal <devicerandom@gmail.com>':
59 'Fabrizio Benedetti':['fabrizio.benedetti.82'],
60 'Rolf Schmidt <rschmidt@alcor.concordia.ca>':
63 'Marco Brucale':['marcobrucale'],
64 'Pancaldi Paolo':['pancaldi.paolo'],
67 IGNORED_PATHS = ['./.hg/', './doc/img', './test/data/',
68 './build/', '/doc/build/']
69 IGNORED_FILES = ['COPYING', 'COPYING.LESSER']
71 # Work around missing author holes in the VCS history
73 ('hooke','driver','hdf5.py'):['Massimo Sandal'],
74 ('hooke','driver','mcs.py'):['Allen Chen'],
75 ('hooke','plugin','peakspot.py'):['Fabrizio Benedetti'],
78 # Work around missing year holes in the VCS history
80 ('hooke','driver','hdf5.py'):2009,
81 ('hooke','driver','picoforce.py'):2006,
82 ('hooke','driver','picoforcealt.py'):2006,
83 ('hooke','plugin','peakspot.py'):2007,
84 ('hooke','plugin','tutorial.py'):2007,
87 # Helpers for VCS-specific commands
90 """Recursively split a path into elements.
95 >>> splitpath(os.path.join('a', 'b', 'c'))
97 >>> splitpath(os.path.join('.', 'a', 'b', 'c'))
100 path = os.path.normpath(path)
103 dirname,basename = os.path.split(path)
104 elements.insert(0,basename)
105 if dirname in ['', '.']:
108 return tuple(elements)
110 # VCS-specific commands
112 def mercurial_cmd(*args):
116 tmp_stdout = StringIO.StringIO()
117 tmp_stderr = StringIO.StringIO()
118 sys.stdout = tmp_stdout
119 sys.stderr = tmp_stderr
121 mercurial.dispatch.dispatch(list(args))
126 return (tmp_stdout.getvalue().rstrip('\n'),
127 tmp_stderr.getvalue().rstrip('\n'))
129 def original_year(filename, year_hacks=YEAR_HACKS):
130 # shortdate filter: YEAR-MONTH-DAY
131 output,error = mercurial_cmd('log', '--follow',
132 '--template', '{date|shortdate}\n',
134 years = [int(line.split('-', 1)[0]) for line in output.splitlines()]
135 if splitpath(filename) in year_hacks:
136 years.append(year_hacks[splitpath(filename)])
140 def authors(filename, author_hacks=AUTHOR_HACKS):
141 output,error = mercurial_cmd('log', '--follow',
142 '--template', '{author}\n',
144 ret = list(set(output.splitlines()))
145 if splitpath(filename) in author_hacks:
146 ret.extend(author_hacks[splitpath(filename)])
150 output,error = mercurial_cmd('log', '--follow',
151 '--template', '{author}\n')
152 return list(set(output.splitlines()))
154 def is_versioned(filename):
155 output,error = mercurial_cmd('log', '--follow',
156 '--template', '{date|shortdate}\n',
162 # General utility commands
164 def _strip_email(*args):
165 """Remove email addresses from a series of names.
170 >>> _strip_email('J Doe <jdoe@a.com>')
172 >>> _strip_email('J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>')
173 ['J Doe', 'JJJ Smith']
176 for i,arg in enumerate(args):
179 author,addr = email.utils.parseaddr(arg)
183 def _reverse_aliases(aliases):
184 """Reverse an `aliases` dict.
186 Input: key: canonical name, value: list of aliases
187 Output: key: alias, value: canonical name
193 ... 'J Doe <jdoe@a.com>':['Johnny <jdoe@b.edu>', 'J'],
194 ... 'JJJ Smith <jjjs@a.com>':['Jingly <jjjs@b.edu>'],
195 ... None:['Anonymous <a@a.com>'],
197 >>> r = _reverse_aliases(aliases)
198 >>> for item in sorted(r.items()):
200 ('Anonymous <a@a.com>', None)
201 ('J', 'J Doe <jdoe@a.com>')
202 ('Jingly <jjjs@b.edu>', 'JJJ Smith <jjjs@a.com>')
203 ('Johnny <jdoe@b.edu>', 'J Doe <jdoe@a.com>')
206 for canonical_name,_aliases in aliases.items():
207 for alias in _aliases:
208 output[alias] = canonical_name
211 def _replace_aliases(authors, with_email=True, aliases=None):
212 """Consolidate and sort `authors`.
214 Make the replacements listed in the `aliases` dict (key: canonical
215 name, value: list of aliases). If `aliases` is ``None``, default
219 ... 'J Doe <jdoe@a.com>':['Johnny <jdoe@b.edu>'],
220 ... 'JJJ Smith <jjjs@a.com>':['Jingly <jjjs@b.edu>'],
221 ... None:['Anonymous <a@a.com>'],
223 >>> _replace_aliases(['JJJ Smith <jjjs@a.com>', 'Johnny <jdoe@b.edu>',
224 ... 'Jingly <jjjs@b.edu>', 'Anonymous <a@a.com>'],
225 ... with_email=True, aliases=aliases)
226 ['J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>']
227 >>> _replace_aliases(['JJJ Smith', 'Johnny', 'Jingly', 'Anonymous'],
228 ... with_email=False, aliases=aliases)
229 ['J Doe', 'JJJ Smith']
230 >>> _replace_aliases(['JJJ Smith <jjjs@a.com>', 'Johnny <jdoe@b.edu>',
231 ... 'Jingly <jjjs@b.edu>', 'J Doe <jdoe@a.com>'],
232 ... with_email=True, aliases=aliases)
233 ['J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>']
237 if with_email == False:
238 aliases = dict([(_strip_email(author)[0], _strip_email(*_aliases))
239 for author,_aliases in aliases.items()])
240 rev_aliases = _reverse_aliases(aliases)
241 for i,author in enumerate(authors):
242 if author in rev_aliases:
243 authors[i] = rev_aliases[author]
244 authors = sorted(list(set(authors)))
249 def _copyright_string(original_year, final_year, authors, prefix=''):
251 >>> print _copyright_string(original_year=2005,
253 ... authors=['A <a@a.com>', 'B <b@b.edu>'],
255 ... ) # doctest: +ELLIPSIS
256 # Copyright (C) 2005 A <a@a.com>
260 >>> print _copyright_string(original_year=2005,
262 ... authors=['A <a@a.com>', 'B <b@b.edu>']
263 ... ) # doctest: +ELLIPSIS
264 Copyright (C) 2005-2009 A <a@a.com>
269 if original_year == final_year:
270 date_range = '%s' % original_year
272 date_range = '%s-%s' % (original_year, final_year)
273 lines = ['Copyright (C) %s %s' % (date_range, authors[0])]
274 for author in authors[1:]:
275 lines.append(' '*(len('Copyright (C) ')+len(date_range)+1) +
278 lines.extend((COPY_RIGHT_TEXT % PROJECT_INFO).splitlines())
279 for i,line in enumerate(lines):
280 lines[i] = (prefix + line).rstrip()
281 return '\n'.join(lines)
283 def _tag_copyright(contents):
285 >>> contents = '''Some file
287 ... # Copyright (copyright begins)
288 ... # (copyright continues)
293 >>> print _tag_copyright(contents).replace('COPY-RIGHT', 'CR')
303 for line in contents.splitlines():
304 if incopy == False and line.startswith('# Copyright'):
306 lines.append(COPY_RIGHT_TAG)
307 elif incopy == True and not line.startswith('#'):
310 lines.append(line.rstrip('\n'))
311 return '\n'.join(lines)+'\n'
313 def _update_copyright(contents, original_year, authors):
315 >>> contents = '''Some file
317 ... # Copyright (copyright begins)
318 ... # (copyright continues)
323 >>> print _update_copyright(contents, 2008, ['Jack', 'Jill']
324 ... ) # doctest: +ELLIPSIS, +REPORT_UDIFF
327 # Copyright (C) 2008-... Jack
335 current_year = time.gmtime()[0]
336 copyright_string = _copyright_string(
337 original_year, current_year, authors, prefix='# ')
338 contents = _tag_copyright(contents)
339 return contents.replace(COPY_RIGHT_TAG, copyright_string)
341 def ignored_file(filename, ignored_paths=None, ignored_files=None,
342 check_disk=True, check_vcs=True):
344 >>> ignored_paths = ['./a/', './b/']
345 >>> ignored_files = ['x', 'y']
346 >>> ignored_file('./a/z', ignored_paths, ignored_files, False, False)
348 >>> ignored_file('./ab/z', ignored_paths, ignored_files, False, False)
350 >>> ignored_file('./ab/x', ignored_paths, ignored_files, False, False)
352 >>> ignored_file('./ab/xy', ignored_paths, ignored_files, False, False)
354 >>> ignored_file('./z', ignored_paths, ignored_files, False, False)
357 if ignored_paths == None:
358 ignored_paths = IGNORED_PATHS
359 if ignored_files == None:
360 ignored_files = IGNORED_FILES
361 if check_disk == True and os.path.isfile(filename) == False:
363 for path in ignored_paths:
364 if filename.startswith(path):
366 if os.path.basename(filename) in ignored_files:
368 if check_vcs == True and is_versioned(filename) == False:
372 def _set_contents(filename, contents, original_contents=None, dry_run=False,
374 if original_contents == None and os.path.isfile(filename):
375 f = open(filename, 'r')
376 original_contents = f.read()
379 print "checking %s ... " % filename,
380 if contents != original_contents:
382 if original_contents == None:
386 if verbose > 1 and original_contents != None:
388 difflib.unified_diff(
389 original_contents.splitlines(), contents.splitlines(),
390 fromfile=os.path.normpath(os.path.join('a', filename)),
391 tofile=os.path.normpath(os.path.join('b', filename)),
394 f = file(filename, 'w')
402 def update_authors(authors_fn=authors_list, dry_run=False, verbose=0):
403 new_contents = '%s was written by:\n%s\n' % (
404 PROJECT_INFO['project'],
405 '\n'.join(authors_fn())
407 _set_contents('AUTHORS', new_contents, dry_run=dry_run, verbose=verbose)
409 def update_file(filename, original_year_fn=original_year, authors_fn=authors,
410 dry_run=False, verbose=0):
411 f = file(filename, 'r')
415 original_year = original_year_fn(filename)
416 authors = authors_fn(filename)
417 authors = _replace_aliases(authors, with_email=True, aliases=ALIASES)
419 new_contents = _update_copyright(contents, original_year, authors)
420 _set_contents(filename, contents=new_contents, original_contents=contents,
421 dry_run=dry_run, verbose=verbose)
423 def update_files(files=None, dry_run=False, verbose=0):
424 if files == None or len(files) == 0:
426 for dirpath,dirnames,filenames in os.walk('.'):
427 for filename in filenames:
428 files.append(os.path.join(dirpath, filename))
430 for filename in files:
431 if ignored_file(filename) == True:
433 update_file(filename, dry_run=dry_run, verbose=verbose)
439 if __name__ == '__main__':
443 usage = """%%prog [options] [file ...]
445 Update copyright information in source code with information from
446 the %(vcs)s repository. Run from the %(project)s repository root.
448 Replaces every line starting with '^# Copyright' and continuing with
449 '^#' with an auto-generated copyright blurb. If you want to add
450 #-commented material after a copyright blurb, please insert a blank
451 line between the blurb and your comment, so the next run of
452 ``update_copyright.py`` doesn't clobber your comment.
454 If no files are given, a list of files to update is generated
457 p = optparse.OptionParser(usage)
458 p.add_option('--test', dest='test', default=False,
459 action='store_true', help='Run internal tests and exit')
460 p.add_option('--dry-run', dest='dry_run', default=False,
461 action='store_true', help="Don't make any changes")
462 p.add_option('-v', '--verbose', dest='verbose', default=0,
463 action='count', help='Increment verbosity')
464 options,args = p.parse_args()
466 if options.test == True:
470 update_authors(dry_run=options.dry_run, verbose=options.verbose)
471 update_files(files=args, dry_run=options.dry_run, verbose=options.verbose)