Ran update-copyright.
[update-copyright.git] / update_copyright / project.py
1 # Copyright (C) 2012 W. Trevor King <wking@tremily.us>
2 #
3 # This file is part of update-copyright.
4 #
5 # update-copyright is free software: you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by the Free
7 # Software Foundation, either version 3 of the License, or (at your option) any
8 # later version.
9 #
10 # update-copyright is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 # FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
13 # more details.
14 #
15 # You should have received a copy of the GNU General Public License along with
16 # update-copyright.  If not, see <http://www.gnu.org/licenses/>.
17
18 """Project-specific configuration."""
19
20 import ConfigParser as _configparser
21 import fnmatch as _fnmatch
22 import os.path as _os_path
23 import sys
24 import time as _time
25
26 from . import LOG as _LOG
27 from . import utils as _utils
28 from .vcs.git import GitBackend as _GitBackend
29 try:
30     from .vcs.bazaar import BazaarBackend as _BazaarBackend
31 except ImportError, _bazaar_import_error:
32     _BazaarBackend = None
33 try:
34     from .vcs.mercurial import MercurialBackend as _MercurialBackend
35 except ImportError, _mercurial_import_error:
36     _MercurialBackend = None
37
38
39 class Project (object):
40     def __init__(self, root='.', name=None, vcs=None, copyright=None,
41                  short_copyright=None):
42         self._root = _os_path.normpath(_os_path.abspath(root))
43         self._name = name
44         self._vcs = vcs
45         self._author_hacks = None
46         self._year_hacks = None
47         self._aliases = None
48         self._copyright = None
49         self._short_copyright = None
50         self.with_authors = False
51         self.with_files = False
52         self._ignored_paths = None
53         self._pyfile = None
54         self._encoding = None
55         self._width = 79
56
57         # unlikely to occur in the wild :p
58         self._copyright_tag = u'-xyz-COPY' + u'-RIGHT-zyx-'
59
60     def load_config(self, stream):
61         parser = _configparser.RawConfigParser()
62         parser.readfp(stream)
63         for section in parser.sections():
64             clean_section = section.replace('-', '_')
65             try:
66                 loader = getattr(self, '_load_{}_conf'.format(clean_section))
67             except AttributeError, e:
68                 _LOG.error('invalid {} section'.format(section))
69                 raise
70             loader(parser=parser)
71
72     def _load_project_conf(self, parser):
73         try:
74             self._name = parser.get('project', 'name')
75         except _configparser.NoOptionError:
76             pass
77         try:
78             vcs = parser.get('project', 'vcs')
79         except _configparser.NoOptionError:
80             pass
81         else:
82             kwargs = {
83                 'root': self._root,
84                 'author_hacks': self._author_hacks,
85                 'year_hacks': self._year_hacks,
86                 'aliases': self._aliases,
87                 }
88             if vcs == 'Git':
89                 self._vcs = _GitBackend(**kwargs)
90             elif vcs == 'Bazaar':
91                 if _BazaarBackend is None:
92                     raise _bazaar_import_error
93                 self._vcs = _BazaarBackend(**kwargs)
94             elif vcs == 'Mercurial':
95                 if _MercurialBackend is None:
96                     raise _mercurial_import_error
97                 self._vcs = _MercurialBackend(**kwargs)
98             else:
99                 raise NotImplementedError('vcs: {}'.format(vcs))
100
101     def _load_copyright_conf(self, parser):
102         try:
103             self._copyright = parser.get('copyright', 'long').splitlines()
104         except _configparser.NoOptionError:
105             pass
106         try:
107             self._short_copyright = parser.get(
108                 'copyright', 'short').splitlines()
109         except _configparser.NoOptionError:
110             pass
111
112     def _load_files_conf(self, parser):
113         try:
114             self.with_authors = parser.get('files', 'authors')
115         except _configparser.NoOptionError:
116             pass
117         try:
118             self.with_files = parser.get('files', 'files')
119         except _configparser.NoOptionError:
120             pass
121         try:
122             ignored = parser.get('files', 'ignored')
123         except _configparser.NoOptionError:
124             pass
125         else:
126             self._ignored_paths = [pth.strip() for pth in ignored.split(',')]
127         try:
128             pyfile = parser.get('files', 'pyfile')
129         except _configparser.NoOptionError:
130             pass
131         else:
132             self._pyfile = _os_path.join(self._root, pyfile)
133
134     def _load_author_hacks_conf(self, parser, encoding=None):
135         if encoding is None:
136             encoding = self._encoding or _utils.ENCODING
137         author_hacks = {}
138         for path in parser.options('author-hacks'):
139             authors = parser.get('author-hacks', path)
140             author_hacks[tuple(path.split('/'))] = set(
141                 unicode(a.strip(), encoding) for a in authors.split(','))
142         self._author_hacks = author_hacks
143         if self._vcs is not None:
144             self._vcs._author_hacks = self._author_hacks
145
146     def _load_year_hacks_conf(self, parser):
147         year_hacks = {}
148         for path in parser.options('year-hacks'):
149             year = parser.get('year-hacks', path)
150             year_hacks[tuple(path.split('/'))] = int(year)
151         self._year_hacks = year_hacks
152         if self._vcs is not None:
153             self._vcs._year_hacks = self._year_hacks
154
155     def _load_aliases_conf(self, parser, encoding=None):
156         if encoding is None:
157             encoding = self._encoding or _utils.ENCODING
158         aliases = {}
159         for author in parser.options('aliases'):
160             _aliases = parser.get('aliases', author)
161             aliases[author] = set(
162                 unicode(a.strip(), encoding) for a in _aliases.split(','))
163         self._aliases = aliases
164         if self._vcs is not None:
165             self._vcs._aliases = self._aliases
166
167     def _info(self):
168         return {
169             'project': self._name,
170             'vcs': self._vcs.name,
171             }
172
173     def update_authors(self, dry_run=False):
174         _LOG.info('update AUTHORS')
175         authors = self._vcs.authors()
176         new_contents = u'{} was written by:\n{}\n'.format(
177             self._name, u'\n'.join(authors))
178         _utils.set_contents(
179             _os_path.join(self._root, 'AUTHORS'),
180             new_contents, unicode=True, encoding=self._encoding,
181             dry_run=dry_run)
182
183     def update_file(self, filename, dry_run=False):
184         _LOG.info('update {}'.format(filename))
185         contents = _utils.get_contents(
186             filename=filename, unicode=True, encoding=self._encoding)
187         original_year = self._vcs.original_year(filename=filename)
188         authors = self._vcs.authors(filename=filename)
189         new_contents = _utils.update_copyright(
190             contents=contents, original_year=original_year, authors=authors,
191             text=self._copyright, info=self._info(), prefix=('# ', '# ', None),
192             width=self._width, tag=self._copyright_tag)
193         new_contents = _utils.update_copyright(
194             contents=new_contents, original_year=original_year,
195             authors=authors, text=self._copyright, info=self._info(),
196             prefix=('/* ', ' * ', ' */'), width=self._width,
197             tag=self._copyright_tag)
198         _utils.set_contents(
199             filename=filename, contents=new_contents,
200             original_contents=contents, unicode=True, encoding=self._encoding,
201             dry_run=dry_run)
202
203     def update_files(self, files=None, dry_run=False):
204         if files is None or len(files) == 0:
205             files = _utils.list_files(root=self._root)
206         for filename in files:
207             if self._ignored_file(filename=filename):
208                 continue
209             self.update_file(filename=filename, dry_run=dry_run)
210
211     def update_pyfile(self, dry_run=False):
212         if self._pyfile is None:
213             _LOG.info('no pyfile location configured, skip `update_pyfile`')
214             return
215         _LOG.info('update pyfile at {}'.format(self._pyfile))
216         current_year = _time.gmtime()[0]
217         original_year = self._vcs.original_year()
218         authors = self._vcs.authors()
219         lines = [
220             _utils.copyright_string(
221                 original_year=original_year, final_year=current_year,
222                 authors=authors, text=self._copyright, info=self._info(),
223                 prefix=u'# ', width=self._width),
224             u'', u'import textwrap as _textwrap', u'', u'',
225             u'LICENSE = """',
226             _utils.copyright_string(
227                 original_year=original_year, final_year=current_year,
228                 authors=authors, text=self._copyright, info=self._info(),
229                 prefix=u'', width=self._width),
230             u'""".strip()',
231             u'',
232             u'def short_license(info, wrap=True, **kwargs):',
233             u'    paragraphs = [',
234             ]
235         paragraphs = _utils.copyright_string(
236             original_year=original_year, final_year=current_year,
237             authors=authors, text=self._short_copyright, info=self._info(),
238             author_format_fn=_utils.short_author_formatter, wrap=False,
239             ).split(u'\n\n')
240         for p in paragraphs:
241             lines.append(u"        '{}' % info,".format(
242                     p.replace(u"'", ur"\'")))
243         lines.extend([
244                 u'        ]',
245                 u'    if wrap:',
246                 u'        for i,p in enumerate(paragraphs):',
247                 u'            paragraphs[i] = _textwrap.fill(p, **kwargs)',
248                 ur"    return '\n\n'.join(paragraphs)",
249                 u'',  # for terminal endline
250                 ])
251         new_contents = u'\n'.join(lines)
252         _utils.set_contents(
253             filename=self._pyfile, contents=new_contents, unicode=True,
254             encoding=self._encoding, dry_run=dry_run)
255
256     def _ignored_file(self, filename):
257         """
258         >>> p = Project()
259         >>> p._ignored_paths = ['a', './b/']
260         >>> p._ignored_file('./a/')
261         True
262         >>> p._ignored_file('b')
263         True
264         >>> p._ignored_file('a/z')
265         True
266         >>> p._ignored_file('ab/z')
267         False
268         >>> p._ignored_file('./ab/a')
269         False
270         >>> p._ignored_file('./z')
271         False
272         """
273         filename = _os_path.relpath(filename, self._root)
274         if self._ignored_paths is not None:
275             base = filename
276             while base not in ['', '.', '..']:
277                 for path in self._ignored_paths:
278                     if _fnmatch.fnmatch(base, _os_path.normpath(path)):
279                         _LOG.debug('ignoring {} (matched {})'.format(
280                                 filename, path))
281                         return True
282                 base = _os_path.split(base)[0]
283         if self._vcs and not self._vcs.is_versioned(filename):
284             _LOG.debug('ignoring {} (not versioned))'.format(filename))
285             return True
286         return False