1 # Copyright (C) 2012 W. Trevor King
3 # This file is part of update-copyright.
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.
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.
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/>.
19 """Project-specific configuration.
21 # Convert author names to canonical forms.
22 # ALIASES[<canonical name>] = <list of aliases>
25 # 'John Doe <jdoe@a.com>':
26 # ['John Doe', 'jdoe', 'J. Doe <j@doe.net>'],
28 # Git-based projects are encouraged to use .mailmap instead of
29 # ALIASES. See git-shortlog(1) for details.
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']
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:
43 # ('path', 'to', 'module.py'):['John Doe'],
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:
52 # ('path', 'to', 'module.py'):2008,
57 import ConfigParser as _configparser
58 import fnmatch as _fnmatch
59 import os.path as _os_path
63 from . import LOG as _LOG
64 from . import utils as _utils
65 from .vcs.git import GitBackend as _GitBackend
67 from .vcs.bazaar import BazaarBackend as _BazaarBackend
68 except ImportError, _bazaar_import_error:
71 from .vcs.mercurial import MercurialBackend as _MercurialBackend
72 except ImportError, _mercurial_import_error:
73 _MercurialBackend = None
76 class Project (object):
77 def __init__(self, name=None, vcs=None, copyright=None,
78 short_copyright=None):
81 self._copyright = None
82 self._short_copyright = None
83 self.with_authors = False
84 self.with_files = False
85 self._ignored_paths = None
90 # unlikely to occur in the wild :p
91 self._copyright_tag = u'-xyz-COPY' + u'-RIGHT-zyx-'
93 def load_config(self, stream):
94 parser = _configparser.RawConfigParser()
96 for section in parser.sections():
98 loader = getattr(self, '_load_{}_conf'.format(section))
99 except AttributeError, e:
100 _LOG.error('invalid {} section'.format(section))
102 loader(parser=parser)
104 def _load_project_conf(self, parser):
106 self._name = parser.get('project', 'name')
107 except _configparser.NoOptionError:
110 vcs = parser.get('project', 'vcs')
111 except _configparser.NoOptionError:
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()
125 raise NotImplementedError('vcs: {}'.format(vcs))
127 def _load_copyright_conf(self, parser):
129 self._copyright = parser.get('copyright', 'long').splitlines()
130 except _configparser.NoOptionError:
133 self._short_copyright = parser.get(
134 'copyright', 'short').splitlines()
135 except _configparser.NoOptionError:
138 def _load_files_conf(self, parser):
140 self.with_authors = parser.get('files', 'authors')
141 except _configparser.NoOptionError:
144 self.with_files = parser.get('files', 'files')
145 except _configparser.NoOptionError:
148 ignored = parser.get('files', 'ignored')
149 except _configparser.NoOptionError:
152 self._ignored_paths = [pth.strip() for pth in ignored.split(',')]
154 self._pyfile = parser.get('files', 'pyfile')
155 except _configparser.NoOptionError:
160 'project': self._name,
161 'vcs': self._vcs.name,
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))
170 'AUTHORS', new_contents, unicode=True, encoding=self._encoding,
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)
184 filename=filename, contents=new_contents,
185 original_contents=contents, unicode=True, encoding=self._encoding,
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):
194 self.update_file(filename=filename, dry_run=dry_run)
196 def update_pyfile(self, dry_run=False):
197 if self._pyfile is None:
198 _LOG.info('no pyfile location configured, skip `update_pyfile`')
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()
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'',
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),
217 u'def short_license(info, wrap=True, **kwargs):',
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,
226 lines.append(u" '{}' % info,".format(
227 p.replace(u"'", ur"\'")))
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
236 new_contents = u'\n'.join(lines)
238 filename=self._pyfile, contents=new_contents, unicode=True,
239 encoding=self._encoding, dry_run=dry_run)
241 def _ignored_file(self, filename):
243 >>> ignored_paths = ['./a/', './b/']
244 >>> ignored_files = ['x', 'y']
245 >>> ignored_file('./a/z', ignored_paths, ignored_files, False, False)
247 >>> ignored_file('./ab/z', ignored_paths, ignored_files, False, False)
249 >>> ignored_file('./ab/x', ignored_paths, ignored_files, False, False)
251 >>> ignored_file('./ab/xy', ignored_paths, ignored_files, False, False)
253 >>> ignored_file('./z', ignored_paths, ignored_files, False, False)
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(
262 if self._vcs and not self._vcs.is_versioned(filename):
263 _LOG.debug('ignoring {} (not versioned))'.format(filename))