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