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