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