4684d380dd1fed225a89a707da2a584577d3fd8d
[update-copyright.git] / update_copyright / project.py
1 # Copyright (C) 2012 W. Trevor King
2 #
3 # This file is part of update-copyright.
4 #
5 # update-copyright is free software: you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License as
7 # published by the Free Software Foundation, either version 3 of the
8 # License, or (at your option) any later version.
9 #
10 # update-copyright is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 # General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with update-copyright.  If not, see
17 # <http://www.gnu.org/licenses/>.
18
19 """Project-specific configuration.
20
21 # Convert author names to canonical forms.
22 # ALIASES[<canonical name>] = <list of aliases>
23 # for example,
24 # ALIASES = {
25 #     'John Doe <jdoe@a.com>':
26 #         ['John Doe', 'jdoe', 'J. Doe <j@doe.net>'],
27 #     }
28 # Git-based projects are encouraged to use .mailmap instead of
29 # ALIASES.  See git-shortlog(1) for details.
30
31 # List of paths that should not be scanned for copyright updates.
32 # IGNORED_PATHS = ['./.git/']
33 IGNORED_PATHS = ['./.git']
34 # List of files that should not be scanned for copyright updates.
35 # IGNORED_FILES = ['COPYING']
36 IGNORED_FILES = ['COPYING']
37
38 # Work around missing author holes in the VCS history.
39 # AUTHOR_HACKS[<path tuple>] = [<missing authors]
40 # for example, if John Doe contributed to module.py but wasn't listed
41 # in the VCS history of that file:
42 # AUTHOR_HACKS = {
43 #     ('path', 'to', 'module.py'):['John Doe'],
44 #     }
45 AUTHOR_HACKS = {}
46
47 # Work around missing year holes in the VCS history.
48 # YEAR_HACKS[<path tuple>] = <original year>
49 # for example, if module.py was published in 2008 but the VCS history
50 # only goes back to 2010:
51 # YEAR_HACKS = {
52 #     ('path', 'to', 'module.py'):2008,
53 #     }
54 YEAR_HACKS = {}
55 """
56
57 import ConfigParser as _configparser
58 import fnmatch as _fnmatch
59 import os.path as _os_path
60 import sys
61 import time as _time
62
63 from . import LOG as _LOG
64 from . import utils as _utils
65 from .vcs.git import GitBackend as _GitBackend
66 try:
67     from .vcs.bazaar import BazaarBackend as _BazaarBackend
68 except ImportError, _bazaar_import_error:
69     _BazaarBackend = None
70 try:
71     from .vcs.mercurial import MercurialBackend as _MercurialBackend
72 except ImportError, _mercurial_import_error:
73     _MercurialBackend = None
74
75
76 class Project (object):
77     def __init__(self, name=None, vcs=None, copyright=None,
78                  short_copyright=None):
79         self._name = name
80         self._vcs = vcs
81         self._copyright = None
82         self._short_copyright = None
83         self.with_authors = False
84         self.with_files = False
85         self._ignored_paths = None
86         self._pyfile = None
87         self._encoding = None
88         self._width = 79
89
90         # unlikely to occur in the wild :p
91         self._copyright_tag = u'-xyz-COPY' + u'-RIGHT-zyx-'
92
93     def load_config(self, stream):
94         p = _configparser.RawConfigParser()
95         p.readfp(stream)
96         try:
97             self._name = p.get('project', 'name')
98         except _configparser.NoOptionError:
99             pass
100         try:
101             vcs = p.get('project', 'vcs')
102         except _configparser.NoOptionError:
103             pass
104         else:
105             if vcs == 'Git':
106                 self._vcs = _GitBackend()
107             elif vcs == 'Bazaar':
108                 if _BazaarBackend is None:
109                     raise _bazaar_import_error
110                 self._vcs = _BazaarBackend()
111             elif vcs == 'Mercurial':
112                 if _MercurialBackend is None:
113                     raise _mercurial_import_error
114                 self._vcs = _MercurialBackend()
115             else:
116                 raise NotImplementedError('vcs: {}'.format(vcs))
117         try:
118             self._copyright = p.get('copyright', 'long').splitlines()
119         except _configparser.NoOptionError:
120             pass
121         try:
122             self._short_copyright = p.get('copyright', 'short').splitlines()
123         except _configparser.NoOptionError:
124             pass
125         try:
126             self.with_authors = p.get('files', 'authors')
127         except _configparser.NoOptionError:
128             pass
129         try:
130             self.with_files = p.get('files', 'files')
131         except _configparser.NoOptionError:
132             pass
133         try:
134             ignored = p.get('files', 'ignored')
135         except _configparser.NoOptionError:
136             pass
137         else:
138             self._ignored_paths = [pth.strip() for pth in ignored.split(',')]
139         try:
140             self._pyfile = p.get('files', 'pyfile')
141         except _configparser.NoOptionError:
142             pass
143
144     def _info(self):
145         return {
146             'project': self._name,
147             'vcs': self._vcs.name,
148             }
149
150     def update_authors(self, dry_run=False):
151         _LOG.info('update AUTHORS')
152         authors = self._vcs.authors()
153         new_contents = u'{} was written by:\n{}\n'.format(
154             self._name, u'\n'.join(authors))
155         _utils.set_contents(
156             'AUTHORS', new_contents, unicode=True, encoding=self._encoding,
157             dry_run=dry_run)
158
159     def update_file(self, filename, dry_run=False):
160         _LOG.info('update {}'.format(filename))
161         contents = _utils.get_contents(
162             filename=filename, unicode=True, encoding=self._encoding)
163         original_year = self._vcs.original_year(filename=filename)
164         authors = self._vcs.authors(filename=filename)
165         new_contents = _utils.update_copyright(
166             contents=contents, original_year=original_year, authors=authors,
167             text=self._copyright, info=self._info(), prefix='# ',
168             width=self._width, tag=self._copyright_tag)
169         _utils.set_contents(
170             filename=filename, contents=new_contents,
171             original_contents=contents, unicode=True, encoding=self._encoding,
172             dry_run=dry_run)
173
174     def update_files(self, files=None, dry_run=False):
175         if files is None or len(files) == 0:
176             files = _utils.list_files(root='.')
177         for filename in files:
178             if self._ignored_file(filename=filename):
179                 continue
180             self.update_file(filename=filename, dry_run=dry_run)
181
182     def update_pyfile(self, dry_run=False):
183         if self._pyfile is None:
184             _LOG.info('no pyfile location configured, skip `update_pyfile`')
185             return
186         _LOG.info('update pyfile at {}'.format(self._pyfile))
187         current_year = _time.gmtime()[0]
188         original_year = self._vcs.original_year()
189         authors = self._vcs.authors()
190         lines = [
191             _utils.copyright_string(
192                 original_year=original_year, final_year=current_year,
193                 authors=authors, text=self._copyright, info=self._info(),
194                 prefix=u'# ', width=self._width),
195             u'', u'import textwrap as _textwrap', u'', u'',
196             u'LICENSE = """',
197             _utils.copyright_string(
198                 original_year=original_year, final_year=current_year,
199                 authors=authors, text=self._copyright, info=self._info(),
200                 prefix=u'', width=self._width),
201             u'""".strip()',
202             u'',
203             u'def short_license(info, wrap=True, **kwargs):',
204             u'    paragraphs = [',
205             ]
206         paragraphs = _utils.copyright_string(
207             original_year=original_year, final_year=current_year,
208             authors=authors, text=self._short_copyright, info=self._info(),
209             author_format_fn=_utils.short_author_formatter, wrap=False,
210             ).split(u'\n\n')
211         for p in paragraphs:
212             lines.append(u"        '{}' % info,".format(
213                     p.replace(u"'", ur"\'")))
214         lines.extend([
215                 u'        ]',
216                 u'    if wrap:',
217                 u'        for i,p in enumerate(paragraphs):',
218                 u'            paragraphs[i] = _textwrap.fill(p, **kwargs)',
219                 ur"    return '\n\n'.join(paragraphs)",
220                 u'',  # for terminal endline
221                 ])
222         new_contents = u'\n'.join(lines)
223         _utils.set_contents(
224             filename=self._pyfile, contents=new_contents, unicode=True,
225             encoding=self._encoding, dry_run=dry_run)
226
227     def _ignored_file(self, filename):
228         """
229         >>> ignored_paths = ['./a/', './b/']
230         >>> ignored_files = ['x', 'y']
231         >>> ignored_file('./a/z', ignored_paths, ignored_files, False, False)
232         True
233         >>> ignored_file('./ab/z', ignored_paths, ignored_files, False, False)
234         False
235         >>> ignored_file('./ab/x', ignored_paths, ignored_files, False, False)
236         True
237         >>> ignored_file('./ab/xy', ignored_paths, ignored_files, False, False)
238         False
239         >>> ignored_file('./z', ignored_paths, ignored_files, False, False)
240         False
241         """
242         if self._ignored_paths is not None:
243             for path in self._ignored_paths:
244                 if _fnmatch.fnmatch(filename, path):
245                     _LOG.debug('ignoring {} (matched {})'.format(
246                             filename, path))
247                     return True
248         if self._vcs and not self._vcs.is_versioned(filename):
249             _LOG.debug('ignoring {} (not versioned))'.format(filename))
250             return True
251         return False