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