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 import ConfigParser as _configparser
22 import fnmatch as _fnmatch
23 import os.path as _os_path
27 from . import LOG as _LOG
28 from . import utils as _utils
29 from .vcs.git import GitBackend as _GitBackend
31 from .vcs.bazaar import BazaarBackend as _BazaarBackend
32 except ImportError, _bazaar_import_error:
35 from .vcs.mercurial import MercurialBackend as _MercurialBackend
36 except ImportError, _mercurial_import_error:
37 _MercurialBackend = None
40 class Project (object):
41 def __init__(self, root='.', name=None, vcs=None, copyright=None,
42 short_copyright=None):
43 self._root = _os_path.normpath(_os_path.abspath(root))
46 self._author_hacks = None
47 self._year_hacks = None
49 self._copyright = None
50 self._short_copyright = None
51 self.with_authors = False
52 self.with_files = False
53 self._ignored_paths = None
58 # unlikely to occur in the wild :p
59 self._copyright_tag = u'-xyz-COPY' + u'-RIGHT-zyx-'
61 def load_config(self, stream):
62 parser = _configparser.RawConfigParser()
64 for section in parser.sections():
65 clean_section = section.replace('-', '_')
67 loader = getattr(self, '_load_{}_conf'.format(clean_section))
68 except AttributeError, e:
69 _LOG.error('invalid {} section'.format(section))
73 def _load_project_conf(self, parser):
75 self._name = parser.get('project', 'name')
76 except _configparser.NoOptionError:
79 vcs = parser.get('project', 'vcs')
80 except _configparser.NoOptionError:
85 'author_hacks': self._author_hacks,
86 'year_hacks': self._year_hacks,
87 'aliases': self._aliases,
90 self._vcs = _GitBackend(**kwargs)
92 if _BazaarBackend is None:
93 raise _bazaar_import_error
94 self._vcs = _BazaarBackend(**kwargs)
95 elif vcs == 'Mercurial':
96 if _MercurialBackend is None:
97 raise _mercurial_import_error
98 self._vcs = _MercurialBackend(**kwargs)
100 raise NotImplementedError('vcs: {}'.format(vcs))
102 def _load_copyright_conf(self, parser):
104 self._copyright = parser.get('copyright', 'long').splitlines()
105 except _configparser.NoOptionError:
108 self._short_copyright = parser.get(
109 'copyright', 'short').splitlines()
110 except _configparser.NoOptionError:
113 def _load_files_conf(self, parser):
115 self.with_authors = parser.get('files', 'authors')
116 except _configparser.NoOptionError:
119 self.with_files = parser.get('files', 'files')
120 except _configparser.NoOptionError:
123 ignored = parser.get('files', 'ignored')
124 except _configparser.NoOptionError:
127 self._ignored_paths = [pth.strip() for pth in ignored.split(',')]
129 pyfile = parser.get('files', 'pyfile')
130 except _configparser.NoOptionError:
133 self._pyfile = _os_path.join(self._root, pyfile)
135 def _load_author_hacks_conf(self, parser, encoding=None):
137 encoding = self._encoding or _utils.ENCODING
139 for path in parser.options('author-hacks'):
140 authors = parser.get('author-hacks', path)
141 author_hacks[tuple(path.split('/'))] = set(
142 unicode(a.strip(), encoding) for a in authors.split(','))
143 self._author_hacks = author_hacks
144 if self._vcs is not None:
145 self._vcs._author_hacks = self._author_hacks
147 def _load_year_hacks_conf(self, parser):
149 for path in parser.options('year-hacks'):
150 year = parser.get('year-hacks', path)
151 year_hacks[tuple(path.split('/'))] = int(year)
152 self._year_hacks = year_hacks
153 if self._vcs is not None:
154 self._vcs._year_hacks = self._year_hacks
156 def _load_aliases_conf(self, parser, encoding=None):
158 encoding = self._encoding or _utils.ENCODING
160 for author in parser.options('aliases'):
161 _aliases = parser.get('aliases', author)
162 aliases[author] = set(
163 unicode(a.strip(), encoding) for a in _aliases.split(','))
164 self._aliases = aliases
165 if self._vcs is not None:
166 self._vcs._aliases = self._aliases
170 'project': self._name,
171 'vcs': self._vcs.name,
174 def update_authors(self, dry_run=False):
175 _LOG.info('update AUTHORS')
176 authors = self._vcs.authors()
177 new_contents = u'{} was written by:\n{}\n'.format(
178 self._name, u'\n'.join(authors))
180 _os_path.join(self._root, 'AUTHORS'),
181 new_contents, unicode=True, encoding=self._encoding,
184 def update_file(self, filename, dry_run=False):
185 _LOG.info('update {}'.format(filename))
186 contents = _utils.get_contents(
187 filename=filename, unicode=True, encoding=self._encoding)
188 original_year = self._vcs.original_year(filename=filename)
189 authors = self._vcs.authors(filename=filename)
190 new_contents = _utils.update_copyright(
191 contents=contents, original_year=original_year, authors=authors,
192 text=self._copyright, info=self._info(), prefix='# ',
193 width=self._width, tag=self._copyright_tag)
195 filename=filename, contents=new_contents,
196 original_contents=contents, unicode=True, encoding=self._encoding,
199 def update_files(self, files=None, dry_run=False):
200 if files is None or len(files) == 0:
201 files = _utils.list_files(root=self._root)
202 for filename in files:
203 if self._ignored_file(filename=filename):
205 self.update_file(filename=filename, dry_run=dry_run)
207 def update_pyfile(self, dry_run=False):
208 if self._pyfile is None:
209 _LOG.info('no pyfile location configured, skip `update_pyfile`')
211 _LOG.info('update pyfile at {}'.format(self._pyfile))
212 current_year = _time.gmtime()[0]
213 original_year = self._vcs.original_year()
214 authors = self._vcs.authors()
216 _utils.copyright_string(
217 original_year=original_year, final_year=current_year,
218 authors=authors, text=self._copyright, info=self._info(),
219 prefix=u'# ', width=self._width),
220 u'', u'import textwrap as _textwrap', u'', u'',
222 _utils.copyright_string(
223 original_year=original_year, final_year=current_year,
224 authors=authors, text=self._copyright, info=self._info(),
225 prefix=u'', width=self._width),
228 u'def short_license(info, wrap=True, **kwargs):',
231 paragraphs = _utils.copyright_string(
232 original_year=original_year, final_year=current_year,
233 authors=authors, text=self._short_copyright, info=self._info(),
234 author_format_fn=_utils.short_author_formatter, wrap=False,
237 lines.append(u" '{}' % info,".format(
238 p.replace(u"'", ur"\'")))
242 u' for i,p in enumerate(paragraphs):',
243 u' paragraphs[i] = _textwrap.fill(p, **kwargs)',
244 ur" return '\n\n'.join(paragraphs)",
245 u'', # for terminal endline
247 new_contents = u'\n'.join(lines)
249 filename=self._pyfile, contents=new_contents, unicode=True,
250 encoding=self._encoding, dry_run=dry_run)
252 def _ignored_file(self, filename):
255 >>> p._ignored_paths = ['a', './b/']
256 >>> p._ignored_file('./a/')
258 >>> p._ignored_file('b')
260 >>> p._ignored_file('a/z')
262 >>> p._ignored_file('ab/z')
264 >>> p._ignored_file('./ab/a')
266 >>> p._ignored_file('./z')
269 filename = _os_path.relpath(filename, self._root)
270 if self._ignored_paths is not None:
272 while base not in ['', '.', '..']:
273 for path in self._ignored_paths:
274 if _fnmatch.fnmatch(base, _os_path.normpath(path)):
275 _LOG.debug('ignoring {} (matched {})'.format(
278 base = _os_path.split(base)[0]
279 if self._vcs and not self._vcs.is_versioned(filename):
280 _LOG.debug('ignoring {} (not versioned))'.format(filename))