e04364fcc05c2720504f5e322744a876d3e47867
[update-copyright.git] / update_copyright / project.py
1 # Copyright (C) 2012-2014 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.mercurial import MercurialBackend as _MercurialBackend
31 except ImportError as _mercurial_import_error:
32     _MercurialBackend = None
33
34
35 class Project (object):
36     def __init__(self, root='.', name=None, vcs=None, copyright=None,
37                  short_copyright=None):
38         self._root = _os_path.normpath(_os_path.abspath(root))
39         self._name = name
40         self._vcs = vcs
41         self._author_hacks = None
42         self._year_hacks = None
43         self._aliases = None
44         self._copyright = None
45         self._short_copyright = None
46         self.with_authors = False
47         self.with_files = False
48         self._ignored_paths = None
49         self._pyfile = None
50         self._encoding = None
51         self._width = 79
52
53         # unlikely to occur in the wild :p
54         self._copyright_tag = '-xyz-COPY' + '-RIGHT-zyx-'
55
56     def load_config(self, stream):
57         parser = _configparser.RawConfigParser()
58         parser.optionxform = str
59         parser.readfp(stream)
60         for section in parser.sections():
61             clean_section = section.replace('-', '_')
62             try:
63                 loader = getattr(self, '_load_{}_conf'.format(clean_section))
64             except AttributeError as e:
65                 _LOG.error('invalid {} section'.format(section))
66                 raise
67             loader(parser=parser)
68
69     def _load_project_conf(self, parser):
70         try:
71             project = parser['project']
72         except KeyError:
73             project = {}
74         self._name = project.get('name')
75         vcs = project.get('vcs')
76         if vcs:
77             kwargs = {
78                 'root': self._root,
79                 'author_hacks': self._author_hacks,
80                 'year_hacks': self._year_hacks,
81                 'aliases': self._aliases,
82                 }
83             if vcs == 'Git':
84                 self._vcs = _GitBackend(**kwargs)
85             elif vcs == 'Mercurial':
86                 if _MercurialBackend is None:
87                     raise _mercurial_import_error
88                 self._vcs = _MercurialBackend(**kwargs)
89             else:
90                 raise NotImplementedError('vcs: {}'.format(vcs))
91
92     def _load_copyright_conf(self, parser):
93         try:
94             copyright = parser['copyright']
95         except KeyError:
96             copyright = {}
97         if 'long' in copyright:
98             self._copyright = self._split_paragraphs(copyright['long'])
99         if 'short' in copyright:
100             self._short_copyright = self._split_paragraphs(copyright['short'])
101
102     def _split_paragraphs(self, text):
103         return [p.strip() for p in text.split('\n\n')]
104
105     def _load_files_conf(self, parser):
106         files = parser['files']
107         self.with_authors = files.getboolean('authors')
108         self.with_files = files.getboolean('files')
109         ignored = files.get('ignored')
110         if ignored:
111             self._ignored_paths = [pth.strip() for pth in ignored.split('|')]
112         pyfile = files.get('pyfile')
113         if pyfile:
114             self._pyfile = _os_path.join(self._root, pyfile)
115
116     def _load_author_hacks_conf(self, parser):
117         try:
118             section = parser['author-hacks']
119         except KeyError:
120             section = {}
121         author_hacks = {}
122         for path, authors in section.items():
123             author_hacks[tuple(path.split('/'))] = set(
124                 a.strip() for a in authors.split('|'))
125         self._author_hacks = author_hacks
126         if self._vcs is not None:
127             self._vcs._author_hacks = self._author_hacks
128
129     def _load_year_hacks_conf(self, parser):
130         try:
131             section = parser['year-hacks']
132         except KeyError:
133             section = {}
134         year_hacks = {}
135         for path, year in section.items():
136             year_hacks[tuple(path.split('/'))] = int(year)
137         self._year_hacks = year_hacks
138         if self._vcs is not None:
139             self._vcs._year_hacks = self._year_hacks
140
141     def _load_aliases_conf(self, parser):
142         try:
143             section = parser['aliases']
144         except KeyError:
145             section = {}
146         aliases = {}
147         for author, _aliases in section.items():
148             aliases[author] = set(
149                 a.strip() for a in _aliases.split('|'))
150         self._aliases = aliases
151         if self._vcs is not None:
152             self._vcs._aliases = self._aliases
153
154     def _info(self):
155         return {
156             'project': self._name,
157             'vcs': self._vcs.name,
158             }
159
160     def update_authors(self, dry_run=False):
161         _LOG.info('update AUTHORS')
162         authors = self._vcs.authors()
163         new_contents = '{} was written by:\n{}\n'.format(
164             self._name, '\n'.join(authors))
165         _utils.set_contents(
166             _os_path.join(self._root, 'AUTHORS'),
167             new_contents, unicode=True, encoding=self._encoding,
168             dry_run=dry_run)
169
170     def update_file(self, filename, dry_run=False):
171         _LOG.info('update {}'.format(filename))
172         contents = _utils.get_contents(
173             filename=filename, unicode=True, encoding=self._encoding)
174         years = self._vcs.years(filename=filename)
175         authors = self._vcs.authors(filename=filename)
176         new_contents = _utils.update_copyright(
177             contents=contents, years=years, authors=authors,
178             text=self._copyright, info=self._info(), prefix=('# ', '# ', None),
179             width=self._width, tag=self._copyright_tag)
180         new_contents = _utils.update_copyright(
181             contents=new_contents, years=years,
182             authors=authors, text=self._copyright, info=self._info(),
183             prefix=('/* ', ' * ', ' */'), width=self._width,
184             tag=self._copyright_tag)
185         _utils.set_contents(
186             filename=filename, contents=new_contents,
187             original_contents=contents, unicode=True, encoding=self._encoding,
188             dry_run=dry_run)
189
190     def update_files(self, files=None, dry_run=False):
191         if files is None or len(files) == 0:
192             files = _utils.list_files(root=self._root)
193         for filename in files:
194             if self._ignored_file(filename=filename):
195                 continue
196             self.update_file(filename=filename, dry_run=dry_run)
197
198     def update_pyfile(self, dry_run=False):
199         if self._pyfile is None:
200             _LOG.info('no pyfile location configured, skip `update_pyfile`')
201             return
202         _LOG.info('update pyfile at {}'.format(self._pyfile))
203         current_year = _time.gmtime()[0]
204         years = self._vcs.years()
205         authors = self._vcs.authors()
206         lines = [
207             _utils.copyright_string(
208                 years=years, authors=authors, text=self._copyright,
209                 info=self._info(), prefix=('# ', '# ', None),
210                 width=self._width),
211             '', 'import textwrap as _textwrap', '', '',
212             'LICENSE = """',
213             _utils.copyright_string(
214                 years=years, authors=authors, text=self._copyright,
215                 info=self._info(), prefix=('', '', None), width=self._width),
216             '""".strip()',
217             '',
218             'def short_license(info, wrap=True, **kwargs):',
219             '    paragraphs = [',
220             ]
221         paragraphs = _utils.copyright_string(
222             years=years, authors=authors, text=self._short_copyright,
223             info=self._info(), author_format_fn=_utils.short_author_formatter,
224             wrap=False,
225             ).split('\n\n')
226         for p in paragraphs:
227             lines.append("        '{}'.format(**info),".format(
228                     p.replace("'", r"\'")))
229         lines.extend([
230                 '        ]',
231                 '    if wrap:',
232                 '        for i,p in enumerate(paragraphs):',
233                 '            paragraphs[i] = _textwrap.fill(p, **kwargs)',
234                 r"    return '\n\n'.join(paragraphs)",
235                 '',  # for terminal endline
236                 ])
237         new_contents = '\n'.join(lines)
238         _utils.set_contents(
239             filename=self._pyfile, contents=new_contents, unicode=True,
240             encoding=self._encoding, dry_run=dry_run)
241
242     def _ignored_file(self, filename):
243         """
244         >>> p = Project()
245         >>> p._ignored_paths = ['a', './b/']
246         >>> p._ignored_file('./a/')
247         True
248         >>> p._ignored_file('b')
249         True
250         >>> p._ignored_file('a/z')
251         True
252         >>> p._ignored_file('ab/z')
253         False
254         >>> p._ignored_file('./ab/a')
255         False
256         >>> p._ignored_file('./z')
257         False
258         """
259         filename = _os_path.relpath(filename, self._root)
260         if self._ignored_paths is not None:
261             base = filename
262             while base not in ['', '.', '..']:
263                 for path in self._ignored_paths:
264                     if _fnmatch.fnmatch(base, _os_path.normpath(path)):
265                         _LOG.debug('ignoring {} (matched {})'.format(
266                                 filename, path))
267                         return True
268                 base = _os_path.split(base)[0]
269         if self._vcs and not self._vcs.is_versioned(filename):
270             _LOG.debug('ignoring {} (not versioned))'.format(filename))
271             return True
272         return False