Ran update_copyright.py
[calibcant.git] / update_copyright.py
1 #!/usr/bin/python
2 #
3 # Copyright (C) 2010 W. Trevor King <wking@drexel.edu>
4 #
5 # This file is part of CalibCant.
6 #
7 # CalibCant 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.
11 #
12 # CalibCant 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.
16 #
17 # You should have received a copy of the GNU Lesser General Public
18 # License along with CalibCant.  If not, see
19 # <http://www.gnu.org/licenses/>.
20
21 """Automatically update copyright boilerplate.
22
23 This script is adapted from one written for `Bugs Everywhere`_
24 and Hooke_.
25
26 .. _Bugs Everywhere: http://bugseverywhere.org/
27 .. _Hooke: http://code.google.com/p/hooke/
28 """
29
30 import difflib
31 import email.utils
32 import os
33 import os.path
34 import re
35 import StringIO
36 import sys
37 import time
38
39
40 PROJECT_INFO = {
41     'project': 'CalibCant',
42     'vcs': 'Git', 
43     }
44
45 # Break "copyright" into "copy" and "right" to avoid matching the
46 # REGEXP.
47 COPY_RIGHT_TEXT="""
48 This file is part of %(project)s.
49
50 %(project)s is free software: you can redistribute it and/or
51 modify it under the terms of the GNU Lesser General Public
52 License as published by the Free Software Foundation, either
53 version 3 of the License, or (at your option) any later version.
54
55 %(project)s is distributed in the hope that it will be useful,
56 but WITHOUT ANY WARRANTY; without even the implied warranty of
57 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
58 GNU Lesser General Public License for more details.
59
60 You should have received a copy of the GNU Lesser General Public
61 License along with %(project)s.  If not, see
62 <http://www.gnu.org/licenses/>.
63 """.strip()
64
65 COPY_RIGHT_TAG='-xyz-COPY' + '-RIGHT-zyx-' # unlikely to occur in the wild :p
66
67 # Convert author names to canonical forms.
68 # ALIASES[<canonical name>] = <list of aliases>
69 # for example,
70 # ALIASES = {
71 #     'John Doe <jdoe@a.com>':
72 #         ['John Doe', 'jdoe', 'J. Doe <j@doe.net>'],
73 #     }
74 # Git-based projects are encouraged to use .mailmap instead of
75 # ALIASES.  See git-shortlog(1) for details.
76 ALIASES = {}
77
78 # List of paths that should not be scanned for copyright updates.
79 # IGNORED_PATHS = ['./.git/']
80 IGNORED_PATHS = ['./.git/', './.be/', './build', './dist/',
81                  './calibcant.egg-info/']
82 # List of files that should not be scanned for copyright updates.
83 # IGNORED_FILES = ['COPYING']
84 IGNORED_FILES = ['COPYING']
85
86 # Work around missing author holes in the VCS history.
87 # AUTHOR_HACKS[<path tuple>] = [<missing authors]
88 # for example, if John Doe contributed to module.py but wasn't listed
89 # in the VCS history of that file:
90 # AUTHOR_HACKS = {
91 #     ('path', 'to', 'module.py'):['John Doe'],
92 #     }
93 AUTHOR_HACKS = {}
94
95 # Work around missing year holes in the VCS history.
96 # YEAR_HACKS[<path tuple>] = <original year>
97 # for example, if module.py was published in 2008 but the VCS history
98 # only goes back to 2010:
99 # YEAR_HACKS = {
100 #     ('path', 'to', 'module.py'):2008,
101 #     }
102 YEAR_HACKS = {}
103
104 # Helpers for VCS-specific commands
105
106 def splitpath(path):
107     """Recursively split a path into elements.
108
109     Examples
110     --------
111
112     >>> splitpath(os.path.join('a', 'b', 'c'))
113     ('a', 'b', 'c')
114     >>> splitpath(os.path.join('.', 'a', 'b', 'c'))
115     ('a', 'b', 'c')
116     """
117     path = os.path.normpath(path)
118     elements = []
119     while True:
120         dirname,basename = os.path.split(path)
121         elements.insert(0,basename)
122         if dirname in ['', '.']:
123             break
124         path = dirname
125     return tuple(elements)
126
127 # VCS-specific commands
128
129 if PROJECT_INFO['vcs'] == 'Git':
130
131     import subprocess
132
133     _MSWINDOWS = sys.platform == 'win32'
134     _POSIX = not _MSWINDOWS
135
136     def invoke(args, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, expect=(0,)):
137         """
138         expect should be a tuple of allowed exit codes.
139         """
140         try :
141             if _POSIX:
142                 q = subprocess.Popen(args, stdin=subprocess.PIPE,
143                                      stdout=stdout, stderr=stderr)
144             else:
145                 assert _MSWINDOWS == True, 'invalid platform'
146                 # win32 don't have os.execvp() so run the command in a shell
147                 q = subprocess.Popen(args, stdin=subprocess.PIPE,
148                                      stdout=stdout, stderr=stderr, shell=True)
149         except OSError, e:
150             raise ValueError([args, e])
151         stdout,stderr = q.communicate(input=stdin)
152         status = q.wait()
153         if status not in expect:
154             raise ValueError([args, status, stdout, stderr])
155         return status, stdout, stderr
156
157     def git_cmd(*args):
158         status,stdout,stderr = invoke(['git'] + list(args))
159         return stdout.rstrip('\n')
160         
161     def original_year(filename, year_hacks=YEAR_HACKS):
162         # shortdate filter: YEAR-MONTH-DAY
163         output = git_cmd('log', '--follow',
164                          '--format=format:%ad',  # Author date
165                          '--date=short',         # YYYY-MM-DD
166                          filename)
167         years = [int(line.split('-', 1)[0]) for line in output.splitlines()]
168         if splitpath(filename) in year_hacks:
169             years.append(year_hacks[splitpath(filename)])
170         years.sort()
171         return years[0]
172     
173     def authors(filename, author_hacks=AUTHOR_HACKS):
174         output = git_cmd('log', '--follow', '--format=format:%aN <%aE>',
175                          filename)   # Author name <author email>
176         ret = list(set(output.splitlines()))
177         if splitpath(filename) in author_hacks:
178             ret.extend(author_hacks[splitpath(filename)])
179         return ret
180     
181     def authors_list(author_hacks=AUTHOR_HACKS):
182         output = git_cmd('log', '--format=format:%aN <%aE>')
183         ret = list(set(output.splitlines()))
184         for path,authors in author_hacks.items():
185             ret.extend(authors)
186         return ret
187     
188     def is_versioned(filename):
189         output = git_cmd('log', '--follow', filename)
190         if len(output) == 0:
191             return False        
192         return True
193
194 elif PROJECT_INFO['vcs'] == 'Mercurial':
195
196     def mercurial_cmd(*args):
197         cwd = os.getcwd()
198         stdout = sys.stdout
199         stderr = sys.stderr
200         tmp_stdout = StringIO.StringIO()
201         tmp_stderr = StringIO.StringIO()
202         sys.stdout = tmp_stdout
203         sys.stderr = tmp_stderr
204         try:
205             mercurial.dispatch.dispatch(list(args))
206         finally:
207             os.chdir(cwd)
208             sys.stdout = stdout
209             sys.stderr = stderr
210         return (tmp_stdout.getvalue().rstrip('\n'),
211                 tmp_stderr.getvalue().rstrip('\n'))
212         
213     def original_year(filename, year_hacks=YEAR_HACKS):
214         # shortdate filter: YEAR-MONTH-DAY
215         output,error = mercurial_cmd('log', '--follow',
216                                      '--template', '{date|shortdate}\n',
217                                      filename)
218         years = [int(line.split('-', 1)[0]) for line in output.splitlines()]
219         if splitpath(filename) in year_hacks:
220             years.append(year_hacks[splitpath(filename)])
221         years.sort()
222         return years[0]
223     
224     def authors(filename, author_hacks=AUTHOR_HACKS):
225         output,error = mercurial_cmd('log', '-template', '{author}\n',
226                                      filename)
227         ret = list(set(output.splitlines()))
228         if splitpath(filename) in author_hacks:
229             ret.extend(author_hacks[splitpath(filename)])
230         return ret
231     
232     def authors_list(author_hacks=AUTHOR_HACKS):
233         output,error = mercurial_cmd('log', '--follow',
234                                      '--template', '{author}\n')
235         ret = list(set(output.splitlines()))
236         for path,authors in author_hacks.items():
237             ret.extend(authors)
238         return ret
239     
240     def is_versioned(filename):
241         output,error = mercurial_cmd('log', '--follow', filename)
242         if len(error) > 0:
243             return False
244         return True
245
246 elif PROJECT_INFO['vcs'] == 'Bazaar':
247     pass
248
249 else:
250     raise NotImplementedError('Unrecognized VCS: %(vcs)s' % PROJECT_INFO)
251
252 # General utility commands
253
254 def _strip_email(*args):
255     """Remove email addresses from a series of names.
256
257     Examples
258     --------
259
260     >>> _strip_email('J Doe <jdoe@a.com>')
261     ['J Doe']
262     >>> _strip_email('J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>')
263     ['J Doe', 'JJJ Smith']
264     """
265     args = list(args)
266     for i,arg in enumerate(args):
267         if arg == None:
268             continue
269         author,addr = email.utils.parseaddr(arg)
270         args[i] = author
271     return args
272
273 def _reverse_aliases(aliases):
274     """Reverse an `aliases` dict.
275
276     Input:   key: canonical name,  value: list of aliases
277     Output:  key: alias,           value: canonical name
278
279     Examples
280     --------
281
282     >>> aliases = {
283     ...     'J Doe <jdoe@a.com>':['Johnny <jdoe@b.edu>', 'J'],
284     ...     'JJJ Smith <jjjs@a.com>':['Jingly <jjjs@b.edu>'],
285     ...     None:['Anonymous <a@a.com>'],
286     ...     }
287     >>> r = _reverse_aliases(aliases)
288     >>> for item in sorted(r.items()):
289     ...     print item
290     ('Anonymous <a@a.com>', None)
291     ('J', 'J Doe <jdoe@a.com>')
292     ('Jingly <jjjs@b.edu>', 'JJJ Smith <jjjs@a.com>')
293     ('Johnny <jdoe@b.edu>', 'J Doe <jdoe@a.com>')
294     """
295     output = {}
296     for canonical_name,_aliases in aliases.items():
297         for alias in _aliases:
298             output[alias] = canonical_name
299     return output
300
301 def _replace_aliases(authors, with_email=True, aliases=None):
302     """Consolidate and sort `authors`.
303
304     Make the replacements listed in the `aliases` dict (key: canonical
305     name, value: list of aliases).  If `aliases` is ``None``, default
306     to ``ALIASES``.
307     
308     >>> aliases = {
309     ...     'J Doe <jdoe@a.com>':['Johnny <jdoe@b.edu>'],
310     ...     'JJJ Smith <jjjs@a.com>':['Jingly <jjjs@b.edu>'],
311     ...     None:['Anonymous <a@a.com>'],
312     ...     }
313     >>> _replace_aliases(['JJJ Smith <jjjs@a.com>', 'Johnny <jdoe@b.edu>',
314     ...                   'Jingly <jjjs@b.edu>', 'Anonymous <a@a.com>'],
315     ...                  with_email=True, aliases=aliases)
316     ['J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>']
317     >>> _replace_aliases(['JJJ Smith', 'Johnny', 'Jingly', 'Anonymous'],
318     ...                  with_email=False, aliases=aliases)
319     ['J Doe', 'JJJ Smith']
320     >>> _replace_aliases(['JJJ Smith <jjjs@a.com>', 'Johnny <jdoe@b.edu>',
321     ...                   'Jingly <jjjs@b.edu>', 'J Doe <jdoe@a.com>'],
322     ...                  with_email=True, aliases=aliases)
323     ['J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>']
324     """
325     if aliases == None:
326         aliases = ALIASES
327     if with_email == False:
328         aliases = dict([(_strip_email(author)[0], _strip_email(*_aliases))
329                         for author,_aliases in aliases.items()])
330     rev_aliases = _reverse_aliases(aliases)
331     for i,author in enumerate(authors):
332         if author in rev_aliases:
333             authors[i] = rev_aliases[author]
334     authors = sorted(list(set(authors)))
335     if None in authors:
336         authors.remove(None)
337     return authors
338
339 def _copyright_string(original_year, final_year, authors, prefix=''):
340     """
341     >>> print _copyright_string(original_year=2005,
342     ...                         final_year=2005,
343     ...                         authors=['A <a@a.com>', 'B <b@b.edu>'],
344     ...                         prefix='# '
345     ...                        ) # doctest: +ELLIPSIS
346     # Copyright (C) 2005 A <a@a.com>
347     #                    B <b@b.edu>
348     #
349     # This file...
350     >>> print _copyright_string(original_year=2005,
351     ...                         final_year=2009,
352     ...                         authors=['A <a@a.com>', 'B <b@b.edu>']
353     ...                        ) # doctest: +ELLIPSIS
354     Copyright (C) 2005-2009 A <a@a.com>
355                             B <b@b.edu>
356     <BLANKLINE>
357     This file...
358     """
359     if original_year == final_year:
360         date_range = '%s' % original_year
361     else:
362         date_range = '%s-%s' % (original_year, final_year)
363     lines = ['Copyright (C) %s %s' % (date_range, authors[0])]
364     for author in authors[1:]:
365         lines.append(' '*(len('Copyright (C) ')+len(date_range)+1) +
366                      author)
367     lines.append('')
368     lines.extend((COPY_RIGHT_TEXT % PROJECT_INFO).splitlines())
369     for i,line in enumerate(lines):
370         lines[i] = (prefix + line).rstrip()
371     return '\n'.join(lines)
372
373 def _tag_copyright(contents):
374     """
375     >>> contents = '''Some file
376     ... bla bla
377     ... # Copyright (copyright begins)
378     ... # (copyright continues)
379     ... # bla bla bla
380     ... (copyright ends)
381     ... bla bla bla
382     ... '''
383     >>> print _tag_copyright(contents).replace('COPY-RIGHT', 'CR')
384     Some file
385     bla bla
386     -xyz-CR-zyx-
387     (copyright ends)
388     bla bla bla
389     <BLANKLINE>
390     """
391     lines = []
392     incopy = False
393     for line in contents.splitlines():
394         if incopy == False and line.startswith('# Copyright'):
395             incopy = True
396             lines.append(COPY_RIGHT_TAG)
397         elif incopy == True and not line.startswith('#'):
398             incopy = False
399         if incopy == False:
400             lines.append(line.rstrip('\n'))
401     return '\n'.join(lines)+'\n'
402
403 def _update_copyright(contents, original_year, authors):
404     """
405     >>> contents = '''Some file
406     ... bla bla
407     ... # Copyright (copyright begins)
408     ... # (copyright continues)
409     ... # bla bla bla
410     ... (copyright ends)
411     ... bla bla bla
412     ... '''
413     >>> print _update_copyright(contents, 2008, ['Jack', 'Jill']
414     ...     ) # doctest: +ELLIPSIS, +REPORT_UDIFF
415     Some file
416     bla bla
417     # Copyright (C) 2008-... Jack
418     #                         Jill
419     #
420     # This file...
421     (copyright ends)
422     bla bla bla
423     <BLANKLINE>
424     """
425     current_year = time.gmtime()[0]
426     copyright_string = _copyright_string(
427         original_year, current_year, authors, prefix='# ')
428     contents = _tag_copyright(contents)
429     return contents.replace(COPY_RIGHT_TAG, copyright_string)
430
431 def ignored_file(filename, ignored_paths=None, ignored_files=None,
432                  check_disk=True, check_vcs=True):
433     """
434     >>> ignored_paths = ['./a/', './b/']
435     >>> ignored_files = ['x', 'y']
436     >>> ignored_file('./a/z', ignored_paths, ignored_files, False, False)
437     True
438     >>> ignored_file('./ab/z', ignored_paths, ignored_files, False, False)
439     False
440     >>> ignored_file('./ab/x', ignored_paths, ignored_files, False, False)
441     True
442     >>> ignored_file('./ab/xy', ignored_paths, ignored_files, False, False)
443     False
444     >>> ignored_file('./z', ignored_paths, ignored_files, False, False)
445     False
446     """
447     if ignored_paths == None:
448         ignored_paths = IGNORED_PATHS
449     if ignored_files == None:
450         ignored_files = IGNORED_FILES
451     if check_disk == True and os.path.isfile(filename) == False:
452         return True
453     for path in ignored_paths:
454         if filename.startswith(path):
455             return True
456     if os.path.basename(filename) in ignored_files:
457         return True
458     if check_vcs == True and is_versioned(filename) == False:
459         return True
460     return False
461
462 def _set_contents(filename, contents, original_contents=None, dry_run=False,
463                   verbose=0):
464     if original_contents == None and os.path.isfile(filename):
465         f = open(filename, 'r')
466         original_contents = f.read()
467         f.close()
468     if verbose > 0:
469         print "checking %s ... " % filename,
470     if contents != original_contents:
471         if verbose > 0:
472             if original_contents == None:
473                 print "[creating]"
474             else:
475                 print "[updating]"
476         if verbose > 1 and original_contents != None:
477             print '\n'.join(
478                 difflib.unified_diff(
479                     original_contents.splitlines(), contents.splitlines(),
480                     fromfile=os.path.normpath(os.path.join('a', filename)),
481                     tofile=os.path.normpath(os.path.join('b', filename)),
482                     n=3, lineterm=''))
483         if dry_run == False:
484             f = file(filename, 'w')
485             f.write(contents)
486             f.close()
487     elif verbose > 0:
488         print "[no change]"
489
490 # Update commands
491
492 def update_authors(authors_fn=authors_list, dry_run=False, verbose=0):
493     authors = authors_fn()
494     authors = _replace_aliases(authors, with_email=True, aliases=ALIASES)
495     new_contents = '%s was written by:\n%s\n' % (
496         PROJECT_INFO['project'],
497         '\n'.join(authors)
498         )
499     _set_contents('AUTHORS', new_contents, dry_run=dry_run, verbose=verbose)
500
501 def update_file(filename, original_year_fn=original_year, authors_fn=authors,
502                 dry_run=False, verbose=0):
503     f = file(filename, 'r')
504     contents = f.read()
505     f.close()
506
507     original_year = original_year_fn(filename)
508     authors = authors_fn(filename)
509     authors = _replace_aliases(authors, with_email=True, aliases=ALIASES)
510
511     new_contents = _update_copyright(contents, original_year, authors)
512     _set_contents(filename, contents=new_contents, original_contents=contents,
513                   dry_run=dry_run, verbose=verbose)
514
515 def update_files(files=None, dry_run=False, verbose=0):
516     if files == None or len(files) == 0:
517         files = []
518         for dirpath,dirnames,filenames in os.walk('.'):
519             for filename in filenames:
520                 files.append(os.path.join(dirpath, filename))
521
522     for filename in files:
523         if ignored_file(filename) == True:
524             continue
525         update_file(filename, dry_run=dry_run, verbose=verbose)
526
527 def test():
528     import doctest
529     doctest.testmod() 
530
531 if __name__ == '__main__':
532     import optparse
533     import sys
534
535     usage = """%%prog [options] [file ...]
536
537 Update copyright information in source code with information from
538 the %(vcs)s repository.  Run from the %(project)s repository root.
539
540 Replaces every line starting with '^# Copyright' and continuing with
541 '^#' with an auto-generated copyright blurb.  If you want to add
542 #-commented material after a copyright blurb, please insert a blank
543 line between the blurb and your comment, so the next run of
544 ``update_copyright.py`` doesn't clobber your comment.
545
546 If no files are given, a list of files to update is generated
547 automatically.
548 """ % PROJECT_INFO
549     p = optparse.OptionParser(usage)
550     p.add_option('--test', dest='test', default=False,
551                  action='store_true', help='Run internal tests and exit')
552     p.add_option('--dry-run', dest='dry_run', default=False,
553                  action='store_true', help="Don't make any changes")
554     p.add_option('-v', '--verbose', dest='verbose', default=0,
555                  action='count', help='Increment verbosity')
556     options,args = p.parse_args()
557
558     if options.test == True:
559         test()
560         sys.exit(0)
561
562     update_authors(dry_run=options.dry_run, verbose=options.verbose)
563     update_files(files=args, dry_run=options.dry_run, verbose=options.verbose)
564
565 #  LocalWords:  difflib