Make config file parsing more modular.
[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         parser = _configparser.RawConfigParser()
95         parser.readfp(stream)
96         for section in parser.sections():
97             try:
98                 loader = getattr(self, '_load_{}_conf'.format(section))
99             except AttributeError, e:
100                 _LOG.error('invalid {} section'.format(section))
101                 raise
102             loader(parser=parser)
103
104     def _load_project_conf(self, parser):
105         try:
106             self._name = parser.get('project', 'name')
107         except _configparser.NoOptionError:
108             pass
109         try:
110             vcs = parser.get('project', 'vcs')
111         except _configparser.NoOptionError:
112             pass
113         else:
114             if vcs == 'Git':
115                 self._vcs = _GitBackend()
116             elif vcs == 'Bazaar':
117                 if _BazaarBackend is None:
118                     raise _bazaar_import_error
119                 self._vcs = _BazaarBackend()
120             elif vcs == 'Mercurial':
121                 if _MercurialBackend is None:
122                     raise _mercurial_import_error
123                 self._vcs = _MercurialBackend()
124             else:
125                 raise NotImplementedError('vcs: {}'.format(vcs))
126
127     def _load_copyright_conf(self, parser):
128         try:
129             self._copyright = parser.get('copyright', 'long').splitlines()
130         except _configparser.NoOptionError:
131             pass
132         try:
133             self._short_copyright = parser.get(
134                 'copyright', 'short').splitlines()
135         except _configparser.NoOptionError:
136             pass
137
138     def _load_files_conf(self, parser):
139         try:
140             self.with_authors = parser.get('files', 'authors')
141         except _configparser.NoOptionError:
142             pass
143         try:
144             self.with_files = parser.get('files', 'files')
145         except _configparser.NoOptionError:
146             pass
147         try:
148             ignored = parser.get('files', 'ignored')
149         except _configparser.NoOptionError:
150             pass
151         else:
152             self._ignored_paths = [pth.strip() for pth in ignored.split(',')]
153         try:
154             self._pyfile = parser.get('files', 'pyfile')
155         except _configparser.NoOptionError:
156             pass
157
158     def _info(self):
159         return {
160             'project': self._name,
161             'vcs': self._vcs.name,
162             }
163
164     def update_authors(self, dry_run=False):
165         _LOG.info('update AUTHORS')
166         authors = self._vcs.authors()
167         new_contents = u'{} was written by:\n{}\n'.format(
168             self._name, u'\n'.join(authors))
169         _utils.set_contents(
170             'AUTHORS', new_contents, unicode=True, encoding=self._encoding,
171             dry_run=dry_run)
172
173     def update_file(self, filename, dry_run=False):
174         _LOG.info('update {}'.format(filename))
175         contents = _utils.get_contents(
176             filename=filename, unicode=True, encoding=self._encoding)
177         original_year = self._vcs.original_year(filename=filename)
178         authors = self._vcs.authors(filename=filename)
179         new_contents = _utils.update_copyright(
180             contents=contents, original_year=original_year, authors=authors,
181             text=self._copyright, info=self._info(), prefix='# ',
182             width=self._width, tag=self._copyright_tag)
183         _utils.set_contents(
184             filename=filename, contents=new_contents,
185             original_contents=contents, unicode=True, encoding=self._encoding,
186             dry_run=dry_run)
187
188     def update_files(self, files=None, dry_run=False):
189         if files is None or len(files) == 0:
190             files = _utils.list_files(root='.')
191         for filename in files:
192             if self._ignored_file(filename=filename):
193                 continue
194             self.update_file(filename=filename, dry_run=dry_run)
195
196     def update_pyfile(self, dry_run=False):
197         if self._pyfile is None:
198             _LOG.info('no pyfile location configured, skip `update_pyfile`')
199             return
200         _LOG.info('update pyfile at {}'.format(self._pyfile))
201         current_year = _time.gmtime()[0]
202         original_year = self._vcs.original_year()
203         authors = self._vcs.authors()
204         lines = [
205             _utils.copyright_string(
206                 original_year=original_year, final_year=current_year,
207                 authors=authors, text=self._copyright, info=self._info(),
208                 prefix=u'# ', width=self._width),
209             u'', u'import textwrap as _textwrap', u'', u'',
210             u'LICENSE = """',
211             _utils.copyright_string(
212                 original_year=original_year, final_year=current_year,
213                 authors=authors, text=self._copyright, info=self._info(),
214                 prefix=u'', width=self._width),
215             u'""".strip()',
216             u'',
217             u'def short_license(info, wrap=True, **kwargs):',
218             u'    paragraphs = [',
219             ]
220         paragraphs = _utils.copyright_string(
221             original_year=original_year, final_year=current_year,
222             authors=authors, text=self._short_copyright, info=self._info(),
223             author_format_fn=_utils.short_author_formatter, wrap=False,
224             ).split(u'\n\n')
225         for p in paragraphs:
226             lines.append(u"        '{}' % info,".format(
227                     p.replace(u"'", ur"\'")))
228         lines.extend([
229                 u'        ]',
230                 u'    if wrap:',
231                 u'        for i,p in enumerate(paragraphs):',
232                 u'            paragraphs[i] = _textwrap.fill(p, **kwargs)',
233                 ur"    return '\n\n'.join(paragraphs)",
234                 u'',  # for terminal endline
235                 ])
236         new_contents = u'\n'.join(lines)
237         _utils.set_contents(
238             filename=self._pyfile, contents=new_contents, unicode=True,
239             encoding=self._encoding, dry_run=dry_run)
240
241     def _ignored_file(self, filename):
242         """
243         >>> ignored_paths = ['./a/', './b/']
244         >>> ignored_files = ['x', 'y']
245         >>> ignored_file('./a/z', ignored_paths, ignored_files, False, False)
246         True
247         >>> ignored_file('./ab/z', ignored_paths, ignored_files, False, False)
248         False
249         >>> ignored_file('./ab/x', ignored_paths, ignored_files, False, False)
250         True
251         >>> ignored_file('./ab/xy', ignored_paths, ignored_files, False, False)
252         False
253         >>> ignored_file('./z', ignored_paths, ignored_files, False, False)
254         False
255         """
256         if self._ignored_paths is not None:
257             for path in self._ignored_paths:
258                 if _fnmatch.fnmatch(filename, path):
259                     _LOG.debug('ignoring {} (matched {})'.format(
260                             filename, path))
261                     return True
262         if self._vcs and not self._vcs.is_versioned(filename):
263             _LOG.debug('ignoring {} (not versioned))'.format(filename))
264             return True
265         return False