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