Ran update_copyright.py
[chemdb.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 ChemDB.
6 #
7 # ChemDB 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.
11 #
12 # ChemDB 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.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with ChemDB.  If not, see <http://www.gnu.org/licenses/>.
19
20 """Automatically update copyright boilerplate.
21
22 This script is adapted from one written for `Bugs Everywhere`_.
23
24 .. _Bugs Everywhere: http://bugseverywhere.org/
25 """
26
27 import difflib
28 import email.utils
29 import os
30 import os.path
31 import re
32 import sys
33 import time
34
35
36 PROJECT_INFO = {
37     'project': 'ChemDB',
38     'vcs': 'Git', 
39     }
40
41 # Break "copyright" into "copy" and "right" to avoid matching the
42 # REGEXP.
43 COPY_RIGHT_TEXT="""
44 This file is part of %(project)s.
45
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.
50
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.
55
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/>.
58 """.strip()
59
60 COPY_RIGHT_TAG='-xyz-COPY' + '-RIGHT-zyx-' # unlikely to occur in the wild :p
61 COMMENT_CHARS=['#', '%'] # allowed comment characters
62
63 # Convert author names to canonical forms.
64 # ALIASES[<canonical name>] = <list of aliases>
65 # for example,
66 # ALIASES = {
67 #     'John Doe <jdoe@a.com>':
68 #         ['John Doe', 'jdoe', 'J. Doe <j@doe.net>'],
69 #     }
70 # Git-based projects are encouraged to use .mailmap instead of
71 # ALIASES.  See git-shortlog(1) for details.
72 ALIASES = {
73     'W. Trevor King <wking@drexel.edu>':
74         ['William Trevor King <wking@thor.yang.physics.drexel.edu>',
75          'wking <wking@loki.(none)>'],
76 }
77
78 # List of paths that should not be scanned for copyright updates.
79 # IGNORED_PATHS = ['./.git/']
80 IGNORED_PATHS = ['./.git/', './template/web/']
81 # List of files that should not be scanned for copyright updates.
82 # IGNORED_FILES = ['COPYING']
83 IGNORED_FILES = ['COPYING', 'certgen.py', 'mk_simple_certs.py',
84                  'daemon.py']
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         output = git_cmd('log', '--follow',
163                          '--format=format:%ad',  # Author date
164                          '--date=short',         # YYYY-MM-DD
165                          filename)
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)])
169         years.sort()
170         return years[0]
171     
172     def authors(filename, author_hacks=AUTHOR_HACKS):
173         output = git_cmd('log', '--follow', '--format=format:%aN <%aE>',
174                          filename)   # Author name <author email>
175         ret = list(set(output.splitlines()))
176         if splitpath(filename) in author_hacks:
177             ret.extend(author_hacks[splitpath(filename)])
178         return ret
179     
180     def authors_list(author_hacks=AUTHOR_HACKS):
181         output = git_cmd('log', '--format=format:%aN <%aE>')
182         ret = list(set(output.splitlines()))
183         for path,authors in author_hacks.items():
184             ret.extend(authors)
185         return ret
186     
187     def is_versioned(filename):
188         output = git_cmd('log', '--follow', filename)
189         if len(output) == 0:
190             return False        
191         return True
192
193 elif PROJECT_INFO['vcs'] == 'Mercurial':
194
195     import StringIO
196     import mercurial
197     import mercurial.dispatch
198
199     def mercurial_cmd(*args):
200         cwd = os.getcwd()
201         stdout = sys.stdout
202         stderr = sys.stderr
203         tmp_stdout = StringIO.StringIO()
204         tmp_stderr = StringIO.StringIO()
205         sys.stdout = tmp_stdout
206         sys.stderr = tmp_stderr
207         try:
208             mercurial.dispatch.dispatch(list(args))
209         finally:
210             os.chdir(cwd)
211             sys.stdout = stdout
212             sys.stderr = stderr
213         return (tmp_stdout.getvalue().rstrip('\n'),
214                 tmp_stderr.getvalue().rstrip('\n'))
215         
216     def original_year(filename, year_hacks=YEAR_HACKS):
217         # shortdate filter: YEAR-MONTH-DAY
218         output,error = mercurial_cmd('log', '--follow',
219                                      '--template', '{date|shortdate}\n',
220                                      filename)
221         years = [int(line.split('-', 1)[0]) for line in output.splitlines()]
222         if splitpath(filename) in year_hacks:
223             years.append(year_hacks[splitpath(filename)])
224         years.sort()
225         return years[0]
226     
227     def authors(filename, author_hacks=AUTHOR_HACKS):
228         output,error = mercurial_cmd('log', '--follow',
229                                      '--template', '{author}\n',
230                                      filename)
231         ret = list(set(output.splitlines()))
232         if splitpath(filename) in author_hacks:
233             ret.extend(author_hacks[splitpath(filename)])
234         return ret
235     
236     def authors_list(author_hacks=AUTHOR_HACKS):
237         output,error = mercurial_cmd('log', '--template', '{author}\n')
238         ret = list(set(output.splitlines()))
239         for path,authors in author_hacks.items():
240             ret.extend(authors)
241         return ret
242     
243     def is_versioned(filename):
244         output,error = mercurial_cmd('log', '--follow', filename)
245         if len(error) > 0:
246             return False
247         return True
248
249 elif PROJECT_INFO['vcs'] == 'Bazaar':
250
251     import StringIO
252     import bzrlib
253     import bzrlib.builtins
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         cmd.run(file_list=[filename])
310         return True
311
312 else:
313     raise NotImplementedError('Unrecognized VCS: %(vcs)s' % PROJECT_INFO)
314
315 # General utility commands
316
317 def _strip_email(*args):
318     """Remove email addresses from a series of names.
319
320     Examples
321     --------
322
323     >>> _strip_email('J Doe <jdoe@a.com>')
324     ['J Doe']
325     >>> _strip_email('J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>')
326     ['J Doe', 'JJJ Smith']
327     """
328     args = list(args)
329     for i,arg in enumerate(args):
330         if arg == None:
331             continue
332         author,addr = email.utils.parseaddr(arg)
333         args[i] = author
334     return args
335
336 def _reverse_aliases(aliases):
337     """Reverse an `aliases` dict.
338
339     Input:   key: canonical name,  value: list of aliases
340     Output:  key: alias,           value: canonical name
341
342     Examples
343     --------
344
345     >>> aliases = {
346     ...     'J Doe <jdoe@a.com>':['Johnny <jdoe@b.edu>', 'J'],
347     ...     'JJJ Smith <jjjs@a.com>':['Jingly <jjjs@b.edu>'],
348     ...     None:['Anonymous <a@a.com>'],
349     ...     }
350     >>> r = _reverse_aliases(aliases)
351     >>> for item in sorted(r.items()):
352     ...     print item
353     ('Anonymous <a@a.com>', None)
354     ('J', 'J Doe <jdoe@a.com>')
355     ('Jingly <jjjs@b.edu>', 'JJJ Smith <jjjs@a.com>')
356     ('Johnny <jdoe@b.edu>', 'J Doe <jdoe@a.com>')
357     """
358     output = {}
359     for canonical_name,_aliases in aliases.items():
360         for alias in _aliases:
361             output[alias] = canonical_name
362     return output
363
364 def _replace_aliases(authors, with_email=True, aliases=None):
365     """Consolidate and sort `authors`.
366
367     Make the replacements listed in the `aliases` dict (key: canonical
368     name, value: list of aliases).  If `aliases` is ``None``, default
369     to ``ALIASES``.
370     
371     >>> aliases = {
372     ...     'J Doe <jdoe@a.com>':['Johnny <jdoe@b.edu>'],
373     ...     'JJJ Smith <jjjs@a.com>':['Jingly <jjjs@b.edu>'],
374     ...     None:['Anonymous <a@a.com>'],
375     ...     }
376     >>> _replace_aliases(['JJJ Smith <jjjs@a.com>', 'Johnny <jdoe@b.edu>',
377     ...                   'Jingly <jjjs@b.edu>', 'Anonymous <a@a.com>'],
378     ...                  with_email=True, aliases=aliases)
379     ['J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>']
380     >>> _replace_aliases(['JJJ Smith', 'Johnny', 'Jingly', 'Anonymous'],
381     ...                  with_email=False, aliases=aliases)
382     ['J Doe', 'JJJ Smith']
383     >>> _replace_aliases(['JJJ Smith <jjjs@a.com>', 'Johnny <jdoe@b.edu>',
384     ...                   'Jingly <jjjs@b.edu>', 'J Doe <jdoe@a.com>'],
385     ...                  with_email=True, aliases=aliases)
386     ['J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>']
387     """
388     if aliases == None:
389         aliases = ALIASES
390     if with_email == False:
391         aliases = dict([(_strip_email(author)[0], _strip_email(*_aliases))
392                         for author,_aliases in aliases.items()])
393     rev_aliases = _reverse_aliases(aliases)
394     for i,author in enumerate(authors):
395         if author in rev_aliases:
396             authors[i] = rev_aliases[author]
397     authors = sorted(list(set(authors)))
398     if None in authors:
399         authors.remove(None)
400     return authors
401
402 def _copyright_string(original_year, final_year, authors, prefix=''):
403     """
404     >>> print _copyright_string(original_year=2005,
405     ...                         final_year=2005,
406     ...                         authors=['A <a@a.com>', 'B <b@b.edu>'],
407     ...                         prefix='# '
408     ...                        ) # doctest: +ELLIPSIS
409     # Copyright (C) 2005 A <a@a.com>
410     #                    B <b@b.edu>
411     #
412     # This file...
413     >>> print _copyright_string(original_year=2005,
414     ...                         final_year=2009,
415     ...                         authors=['A <a@a.com>', 'B <b@b.edu>']
416     ...                        ) # doctest: +ELLIPSIS
417     Copyright (C) 2005-2009 A <a@a.com>
418                             B <b@b.edu>
419     <BLANKLINE>
420     This file...
421     """
422     if original_year == final_year:
423         date_range = '%s' % original_year
424     else:
425         date_range = '%s-%s' % (original_year, final_year)
426     lines = ['Copyright (C) %s %s' % (date_range, authors[0])]
427     for author in authors[1:]:
428         lines.append(' '*(len('Copyright (C) ')+len(date_range)+1) +
429                      author)
430     lines.append('')
431     lines.extend((COPY_RIGHT_TEXT % PROJECT_INFO).splitlines())
432     for i,line in enumerate(lines):
433         lines[i] = (prefix + line).rstrip()
434     return '\n'.join(lines)
435
436 def _tag_copyright(contents):
437     """
438     >>> contents = '''Some file
439     ... bla bla
440     ... # Copyright (copyright begins)
441     ... # (copyright continues)
442     ... # bla bla bla
443     ... (copyright ends)
444     ... bla bla bla
445     ... '''
446     >>> print _tag_copyright(contents).replace('COPY-RIGHT', 'CR')
447     Some file
448     bla bla
449     -xyz-CR-zyx-#
450     (copyright ends)
451     bla bla bla
452     <BLANKLINE>
453     >>> contents = contents.replace('#', '%')
454     >>> print _tag_copyright(contents).replace('COPY-RIGHT', 'CR')
455     Some file
456     bla bla
457     -xyz-CR-zyx-%
458     (copyright ends)
459     bla bla bla
460     <BLANKLINE>
461     """
462     lines = []
463     incopy = False
464     comment_char = None
465     for line in contents.splitlines():
466         if incopy == False:
467             for c in COMMENT_CHARS:
468                 if line.startswith('%s Copyright' % c):
469                     incopy = True
470                     comment_char = c
471                     lines.append(COPY_RIGHT_TAG + c)
472                     continue
473         elif incopy == True and not line.startswith(comment_char):
474             incopy = False
475             comment_char = None
476         if incopy == False:
477             lines.append(line.rstrip('\n'))
478     return '\n'.join(lines)+'\n'
479
480 def _update_copyright(contents, original_year, authors):
481     """
482     >>> contents = '''Some file
483     ... bla bla
484     ... # Copyright (copyright begins)
485     ... # (copyright continues)
486     ... # bla bla bla
487     ... (copyright ends)
488     ... bla bla bla
489     ... '''
490     >>> print _update_copyright(contents, 2008, ['Jack', 'Jill']
491     ...     ) # doctest: +ELLIPSIS, +REPORT_UDIFF
492     Some file
493     bla bla
494     # Copyright (C) 2008-... Jack
495     #                         Jill
496     #
497     # This file...
498     (copyright ends)
499     bla bla bla
500     <BLANKLINE>
501     >>> contents = contents.replace('#', '%')
502     >>> print _update_copyright(contents, 2008, ['Jack', 'Jill']
503     ...     ) # doctest: +ELLIPSIS, +REPORT_UDIFF
504     Some file
505     bla bla
506     % Copyright (C) 2008-... Jack
507     %                         Jill
508     %
509     % This file...
510     (copyright ends)
511     bla bla bla
512     <BLANKLINE>
513     """
514     current_year = time.gmtime()[0]
515     contents = _tag_copyright(contents)
516     lines = []
517     for line in contents.splitlines():
518         if line.startswith(COPY_RIGHT_TAG):
519             comment_char = line[len(COPY_RIGHT_TAG):]
520             copyright_string = _copyright_string(
521                 original_year, current_year, authors,
522                 prefix='%s ' % comment_char)
523             lines.append(copyright_string.rstrip('\n'))
524         else:
525             lines.append(line.rstrip('\n'))
526     return '\n'.join(lines)+'\n'
527
528
529 def ignored_file(filename, ignored_paths=None, ignored_files=None,
530                  check_disk=True, check_vcs=True):
531     """
532     >>> ignored_paths = ['./a/', './b/']
533     >>> ignored_files = ['x', 'y']
534     >>> ignored_file('./a/z', ignored_paths, ignored_files, False, False)
535     True
536     >>> ignored_file('./ab/z', ignored_paths, ignored_files, False, False)
537     False
538     >>> ignored_file('./ab/x', ignored_paths, ignored_files, False, False)
539     True
540     >>> ignored_file('./ab/xy', ignored_paths, ignored_files, False, False)
541     False
542     >>> ignored_file('./z', ignored_paths, ignored_files, False, False)
543     False
544     """
545     if ignored_paths == None:
546         ignored_paths = IGNORED_PATHS
547     if ignored_files == None:
548         ignored_files = IGNORED_FILES
549     if check_disk == True and os.path.isfile(filename) == False:
550         return True
551     for path in ignored_paths:
552         if filename.startswith(path):
553             return True
554     if os.path.basename(filename) in ignored_files:
555         return True
556     if check_vcs == True and is_versioned(filename) == False:
557         return True
558     return False
559
560 def _set_contents(filename, contents, original_contents=None, dry_run=False,
561                   verbose=0):
562     if original_contents == None and os.path.isfile(filename):
563         f = open(filename, 'r')
564         original_contents = f.read()
565         f.close()
566     if verbose > 0:
567         print "checking %s ... " % filename,
568     if contents != original_contents:
569         if verbose > 0:
570             if original_contents == None:
571                 print "[creating]"
572             else:
573                 print "[updating]"
574         if verbose > 1 and original_contents != None:
575             print '\n'.join(
576                 difflib.unified_diff(
577                     original_contents.splitlines(), contents.splitlines(),
578                     fromfile=os.path.normpath(os.path.join('a', filename)),
579                     tofile=os.path.normpath(os.path.join('b', filename)),
580                     n=3, lineterm=''))
581         if dry_run == False:
582             f = file(filename, 'w')
583             f.write(contents)
584             f.close()
585     elif verbose > 0:
586         print "[no change]"
587
588 # Update commands
589
590 def update_authors(authors_fn=authors_list, dry_run=False, verbose=0):
591     authors = authors_fn()
592     authors = _replace_aliases(authors, with_email=True, aliases=ALIASES)
593     new_contents = '%s was written by:\n%s\n' % (
594         PROJECT_INFO['project'],
595         '\n'.join(authors)
596         )
597     _set_contents('AUTHORS', new_contents, dry_run=dry_run, verbose=verbose)
598
599 def update_file(filename, original_year_fn=original_year, authors_fn=authors,
600                 dry_run=False, verbose=0):
601     f = file(filename, 'r')
602     contents = f.read()
603     f.close()
604
605     original_year = original_year_fn(filename)
606     authors = authors_fn(filename)
607     authors = _replace_aliases(authors, with_email=True, aliases=ALIASES)
608
609     new_contents = _update_copyright(contents, original_year, authors)
610     _set_contents(filename, contents=new_contents, original_contents=contents,
611                   dry_run=dry_run, verbose=verbose)
612
613 def update_files(files=None, dry_run=False, verbose=0):
614     if files == None or len(files) == 0:
615         files = []
616         for dirpath,dirnames,filenames in os.walk('.'):
617             for filename in filenames:
618                 files.append(os.path.join(dirpath, filename))
619
620     for filename in files:
621         if ignored_file(filename) == True:
622             continue
623         update_file(filename, dry_run=dry_run, verbose=verbose)
624
625 def test():
626     import doctest
627     doctest.testmod() 
628
629 if __name__ == '__main__':
630     import optparse
631     import sys
632
633     PROJECT_INFO['comment_chars'] = COMMENT_CHARS
634     usage = """%%prog [options] [file ...]
635
636 Update copyright information in source code with information from
637 the %(vcs)s repository.  Run from the %(project)s repository root.
638
639 Replaces every line starting with '^# Copyright' and continuing with
640 '^#' with an auto-generated copyright blurb.  If you want to add
641 #-commented material after a copyright blurb, please insert a blank
642 line between the blurb and your comment, so the next run of
643 ``update_copyright.py`` doesn't clobber your comment.  The comment
644 character ('#' above) can be any of %(comment_chars)s.'
645
646 If no files are given, a list of files to update is generated
647 automatically.
648 """ % PROJECT_INFO
649     p = optparse.OptionParser(usage)
650     p.add_option('--test', dest='test', default=False,
651                  action='store_true', help='Run internal tests and exit')
652     p.add_option('--dry-run', dest='dry_run', default=False,
653                  action='store_true', help="Don't make any changes")
654     p.add_option('-v', '--verbose', dest='verbose', default=0,
655                  action='count', help='Increment verbosity')
656     options,args = p.parse_args()
657
658     if options.test == True:
659         test()
660         sys.exit(0)
661
662     update_authors(dry_run=options.dry_run, verbose=options.verbose)
663     update_files(files=args, dry_run=options.dry_run, verbose=options.verbose)