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/
38 import mercurial.dispatch
46 # Break "copyright" into "copy" and "right" to avoid matching the
49 This file is part of %(project)s.
51 %(project)s is free software: you can redistribute it and/or
52 modify it under the terms of the GNU Lesser General Public
53 License as published by the Free Software Foundation, either
54 version 3 of the License, or (at your option) any later version.
56 %(project)s is distributed in the hope that it will be useful,
57 but WITHOUT ANY WARRANTY; without even the implied warranty of
58 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
59 GNU Lesser General Public License for more details.
61 You should have received a copy of the GNU Lesser General Public
62 License along with %(project)s. If not, see
63 <http://www.gnu.org/licenses/>.
66 COPY_RIGHT_TAG='-xyz-COPY' + '-RIGHT-zyx-' # unlikely to occur in the wild :p
71 'Alberto Gomez-Casado':
73 'Massimo Sandal <devicerandom@gmail.com>':
78 ['fabrizio.benedetti.82'],
79 'Richard Naud <richard.naud@epfl.ch>':
81 'Rolf Schmidt <rschmidt@alcor.concordia.ca>':
90 IGNORED_PATHS = ['./.hg/', './doc/img', './test/data/',
91 './build/', '/doc/build/']
92 IGNORED_FILES = ['COPYING', 'COPYING.LESSER']
94 # Work around missing author holes in the VCS history
96 ('hooke','driver','hdf5.py'):['Massimo Sandal'],
97 ('hooke','driver','mcs.py'):['Allen Chen'],
98 ('hooke','driver','mfp3d.py'):['A. Seeholzer','Richard Naud','Rolf Schmidt',
99 'Alberto Gomez-Casado'],
100 ('hooke','plugin','peakspot.py'):['Fabrizio Benedetti'],
101 ('hooke','plugin','showconvoluted.py'):['Rolf Schmidt'],
102 ('hooke','ui','gui','formatter.py'):['Francesco Musiani','Massimo Sandal'],
103 ('hooke','ui','gui','prettyformat.py'):['Rolf Schmidt'],
106 # Work around missing year holes in the VCS history
108 ('hooke','driver','hdf5.py'):2009,
109 ('hooke','driver','mfp3d.py'):2008,
110 ('hooke','driver','picoforce.py'):2006,
111 ('hooke','driver','picoforcealt.py'):2006,
112 ('hooke','plugin','peakspot.py'):2007,
113 ('hooke','plugin','showconvoluted.py'):2009,
114 ('hooke','plugin','tutorial.py'):2007,
115 ('hooke','ui','gui','formatter.py'):2006,
116 ('hooke','ui','gui','prettyformat.py'):2009,
119 # Helpers for VCS-specific commands
122 """Recursively split a path into elements.
127 >>> splitpath(os.path.join('a', 'b', 'c'))
129 >>> splitpath(os.path.join('.', 'a', 'b', 'c'))
132 path = os.path.normpath(path)
135 dirname,basename = os.path.split(path)
136 elements.insert(0,basename)
137 if dirname in ['', '.']:
140 return tuple(elements)
142 # VCS-specific commands
144 def mercurial_cmd(*args):
148 tmp_stdout = StringIO.StringIO()
149 tmp_stderr = StringIO.StringIO()
150 sys.stdout = tmp_stdout
151 sys.stderr = tmp_stderr
153 mercurial.dispatch.dispatch(list(args))
158 return (tmp_stdout.getvalue().rstrip('\n'),
159 tmp_stderr.getvalue().rstrip('\n'))
161 def original_year(filename, year_hacks=YEAR_HACKS):
162 # shortdate filter: YEAR-MONTH-DAY
163 output,error = mercurial_cmd('log', '--follow',
164 '--template', '{date|shortdate}\n',
166 years = [int(line.split('-', 1)[0]) for line in output.splitlines()]
167 if splitpath(filename) in year_hacks:
168 years.append(year_hacks[splitpath(filename)])
172 def authors(filename, author_hacks=AUTHOR_HACKS):
173 output,error = mercurial_cmd('log', '--follow',
174 '--template', '{author}\n',
176 ret = list(set(output.splitlines()))
177 if splitpath(filename) in author_hacks:
178 ret.extend(author_hacks[splitpath(filename)])
181 def authors_list(author_hacks=AUTHOR_HACKS):
182 output,error = mercurial_cmd('log', '--follow',
183 '--template', '{author}\n')
184 ret = list(set(output.splitlines()))
185 for path,authors in author_hacks.items():
189 def is_versioned(filename):
190 output,error = mercurial_cmd('log', '--follow',
191 '--template', '{date|shortdate}\n',
197 # General utility commands
199 def _strip_email(*args):
200 """Remove email addresses from a series of names.
205 >>> _strip_email('J Doe <jdoe@a.com>')
207 >>> _strip_email('J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>')
208 ['J Doe', 'JJJ Smith']
211 for i,arg in enumerate(args):
214 author,addr = email.utils.parseaddr(arg)
218 def _reverse_aliases(aliases):
219 """Reverse an `aliases` dict.
221 Input: key: canonical name, value: list of aliases
222 Output: key: alias, value: canonical name
228 ... 'J Doe <jdoe@a.com>':['Johnny <jdoe@b.edu>', 'J'],
229 ... 'JJJ Smith <jjjs@a.com>':['Jingly <jjjs@b.edu>'],
230 ... None:['Anonymous <a@a.com>'],
232 >>> r = _reverse_aliases(aliases)
233 >>> for item in sorted(r.items()):
235 ('Anonymous <a@a.com>', None)
236 ('J', 'J Doe <jdoe@a.com>')
237 ('Jingly <jjjs@b.edu>', 'JJJ Smith <jjjs@a.com>')
238 ('Johnny <jdoe@b.edu>', 'J Doe <jdoe@a.com>')
241 for canonical_name,_aliases in aliases.items():
242 for alias in _aliases:
243 output[alias] = canonical_name
246 def _replace_aliases(authors, with_email=True, aliases=None):
247 """Consolidate and sort `authors`.
249 Make the replacements listed in the `aliases` dict (key: canonical
250 name, value: list of aliases). If `aliases` is ``None``, default
254 ... 'J Doe <jdoe@a.com>':['Johnny <jdoe@b.edu>'],
255 ... 'JJJ Smith <jjjs@a.com>':['Jingly <jjjs@b.edu>'],
256 ... None:['Anonymous <a@a.com>'],
258 >>> _replace_aliases(['JJJ Smith <jjjs@a.com>', 'Johnny <jdoe@b.edu>',
259 ... 'Jingly <jjjs@b.edu>', 'Anonymous <a@a.com>'],
260 ... with_email=True, aliases=aliases)
261 ['J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>']
262 >>> _replace_aliases(['JJJ Smith', 'Johnny', 'Jingly', 'Anonymous'],
263 ... with_email=False, aliases=aliases)
264 ['J Doe', 'JJJ Smith']
265 >>> _replace_aliases(['JJJ Smith <jjjs@a.com>', 'Johnny <jdoe@b.edu>',
266 ... 'Jingly <jjjs@b.edu>', 'J Doe <jdoe@a.com>'],
267 ... with_email=True, aliases=aliases)
268 ['J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>']
272 if with_email == False:
273 aliases = dict([(_strip_email(author)[0], _strip_email(*_aliases))
274 for author,_aliases in aliases.items()])
275 rev_aliases = _reverse_aliases(aliases)
276 for i,author in enumerate(authors):
277 if author in rev_aliases:
278 authors[i] = rev_aliases[author]
279 authors = sorted(list(set(authors)))
284 def _copyright_string(original_year, final_year, authors, prefix=''):
286 >>> print _copyright_string(original_year=2005,
288 ... authors=['A <a@a.com>', 'B <b@b.edu>'],
290 ... ) # doctest: +ELLIPSIS
291 # Copyright (C) 2005 A <a@a.com>
295 >>> print _copyright_string(original_year=2005,
297 ... authors=['A <a@a.com>', 'B <b@b.edu>']
298 ... ) # doctest: +ELLIPSIS
299 Copyright (C) 2005-2009 A <a@a.com>
304 if original_year == final_year:
305 date_range = '%s' % original_year
307 date_range = '%s-%s' % (original_year, final_year)
308 lines = ['Copyright (C) %s %s' % (date_range, authors[0])]
309 for author in authors[1:]:
310 lines.append(' '*(len('Copyright (C) ')+len(date_range)+1) +
313 lines.extend((COPY_RIGHT_TEXT % PROJECT_INFO).splitlines())
314 for i,line in enumerate(lines):
315 lines[i] = (prefix + line).rstrip()
316 return '\n'.join(lines)
318 def _tag_copyright(contents):
320 >>> contents = '''Some file
322 ... # Copyright (copyright begins)
323 ... # (copyright continues)
328 >>> print _tag_copyright(contents).replace('COPY-RIGHT', 'CR')
338 for line in contents.splitlines():
339 if incopy == False and line.startswith('# Copyright'):
341 lines.append(COPY_RIGHT_TAG)
342 elif incopy == True and not line.startswith('#'):
345 lines.append(line.rstrip('\n'))
346 return '\n'.join(lines)+'\n'
348 def _update_copyright(contents, original_year, authors):
350 >>> contents = '''Some file
352 ... # Copyright (copyright begins)
353 ... # (copyright continues)
358 >>> print _update_copyright(contents, 2008, ['Jack', 'Jill']
359 ... ) # doctest: +ELLIPSIS, +REPORT_UDIFF
362 # Copyright (C) 2008-... Jack
370 current_year = time.gmtime()[0]
371 copyright_string = _copyright_string(
372 original_year, current_year, authors, prefix='# ')
373 contents = _tag_copyright(contents)
374 return contents.replace(COPY_RIGHT_TAG, copyright_string)
376 def ignored_file(filename, ignored_paths=None, ignored_files=None,
377 check_disk=True, check_vcs=True):
379 >>> ignored_paths = ['./a/', './b/']
380 >>> ignored_files = ['x', 'y']
381 >>> ignored_file('./a/z', ignored_paths, ignored_files, False, False)
383 >>> ignored_file('./ab/z', ignored_paths, ignored_files, False, False)
385 >>> ignored_file('./ab/x', ignored_paths, ignored_files, False, False)
387 >>> ignored_file('./ab/xy', ignored_paths, ignored_files, False, False)
389 >>> ignored_file('./z', ignored_paths, ignored_files, False, False)
392 if ignored_paths == None:
393 ignored_paths = IGNORED_PATHS
394 if ignored_files == None:
395 ignored_files = IGNORED_FILES
396 if check_disk == True and os.path.isfile(filename) == False:
398 for path in ignored_paths:
399 if filename.startswith(path):
401 if os.path.basename(filename) in ignored_files:
403 if check_vcs == True and is_versioned(filename) == False:
407 def _set_contents(filename, contents, original_contents=None, dry_run=False,
409 if original_contents == None and os.path.isfile(filename):
410 f = open(filename, 'r')
411 original_contents = f.read()
414 print "checking %s ... " % filename,
415 if contents != original_contents:
417 if original_contents == None:
421 if verbose > 1 and original_contents != None:
423 difflib.unified_diff(
424 original_contents.splitlines(), contents.splitlines(),
425 fromfile=os.path.normpath(os.path.join('a', filename)),
426 tofile=os.path.normpath(os.path.join('b', filename)),
429 f = file(filename, 'w')
437 def update_authors(authors_fn=authors_list, dry_run=False, verbose=0):
438 authors = authors_fn()
439 authors = _replace_aliases(authors, with_email=True, aliases=ALIASES)
440 new_contents = '%s was written by:\n%s\n' % (
441 PROJECT_INFO['project'],
444 _set_contents('AUTHORS', new_contents, dry_run=dry_run, verbose=verbose)
446 def update_file(filename, original_year_fn=original_year, authors_fn=authors,
447 dry_run=False, verbose=0):
448 f = file(filename, 'r')
452 original_year = original_year_fn(filename)
453 authors = authors_fn(filename)
454 authors = _replace_aliases(authors, with_email=True, aliases=ALIASES)
456 new_contents = _update_copyright(contents, original_year, authors)
457 _set_contents(filename, contents=new_contents, original_contents=contents,
458 dry_run=dry_run, verbose=verbose)
460 def update_files(files=None, dry_run=False, verbose=0):
461 if files == None or len(files) == 0:
463 for dirpath,dirnames,filenames in os.walk('.'):
464 for filename in filenames:
465 files.append(os.path.join(dirpath, filename))
467 for filename in files:
468 if ignored_file(filename) == True:
470 update_file(filename, dry_run=dry_run, verbose=verbose)
476 if __name__ == '__main__':
480 usage = """%%prog [options] [file ...]
482 Update copyright information in source code with information from
483 the %(vcs)s repository. Run from the %(project)s repository root.
485 Replaces every line starting with '^# Copyright' and continuing with
486 '^#' with an auto-generated copyright blurb. If you want to add
487 #-commented material after a copyright blurb, please insert a blank
488 line between the blurb and your comment, so the next run of
489 ``update_copyright.py`` doesn't clobber your comment.
491 If no files are given, a list of files to update is generated
494 p = optparse.OptionParser(usage)
495 p.add_option('--test', dest='test', default=False,
496 action='store_true', help='Run internal tests and exit')
497 p.add_option('--dry-run', dest='dry_run', default=False,
498 action='store_true', help="Don't make any changes")
499 p.add_option('-v', '--verbose', dest='verbose', default=0,
500 action='count', help='Increment verbosity')
501 options,args = p.parse_args()
503 if options.test == True:
507 update_authors(dry_run=options.dry_run, verbose=options.verbose)
508 update_files(files=args, dry_run=options.dry_run, verbose=options.verbose)