1 # Copyright (C) 2012 W. Trevor King <wking@tremily.us>
3 # This file is part of update-copyright.
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
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
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/>.
18 """Project-specific configuration."""
20 import configparser as _configparser
21 import fnmatch as _fnmatch
22 import os.path as _os_path
26 from . import LOG as _LOG
27 from . import utils as _utils
28 from .vcs.git import GitBackend as _GitBackend
30 from .vcs.bazaar import BazaarBackend as _BazaarBackend
31 except ImportError as _bazaar_import_error:
34 from .vcs.mercurial import MercurialBackend as _MercurialBackend
35 except ImportError as _mercurial_import_error:
36 _MercurialBackend = None
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))
45 self._author_hacks = None
46 self._year_hacks = 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
57 # unlikely to occur in the wild :p
58 self._copyright_tag = '-xyz-COPY' + '-RIGHT-zyx-'
60 def load_config(self, stream):
61 parser = _configparser.RawConfigParser()
62 parser.optionxform = str
64 for section in parser.sections():
65 clean_section = section.replace('-', '_')
67 loader = getattr(self, '_load_{}_conf'.format(clean_section))
68 except AttributeError as 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 = self._split_paragraphs(
105 parser.get('copyright', 'long'))
106 except _configparser.NoOptionError:
109 self._short_copyright = self._split_paragraphs(
110 parser.get('copyright', 'short'))
111 except _configparser.NoOptionError:
114 def _split_paragraphs(self, text):
115 return [p.strip() for p in text.split('\n\n')]
117 def _load_files_conf(self, parser):
119 self.with_authors = parser.get('files', 'authors')
120 except _configparser.NoOptionError:
123 self.with_files = parser.get('files', 'files')
124 except _configparser.NoOptionError:
127 ignored = parser.get('files', 'ignored')
128 except _configparser.NoOptionError:
131 self._ignored_paths = [pth.strip() for pth in ignored.split('|')]
133 pyfile = parser.get('files', 'pyfile')
134 except _configparser.NoOptionError:
137 self._pyfile = _os_path.join(self._root, pyfile)
139 def _load_author_hacks_conf(self, parser, encoding=None):
141 encoding = self._encoding or _utils.ENCODING
143 for path in parser.options('author-hacks'):
144 authors = parser.get('author-hacks', path)
145 author_hacks[tuple(path.split('/'))] = set(
146 str(a.strip(), encoding) for a in authors.split('|'))
147 self._author_hacks = author_hacks
148 if self._vcs is not None:
149 self._vcs._author_hacks = self._author_hacks
151 def _load_year_hacks_conf(self, parser):
153 for path in parser.options('year-hacks'):
154 year = parser.get('year-hacks', path)
155 year_hacks[tuple(path.split('/'))] = int(year)
156 self._year_hacks = year_hacks
157 if self._vcs is not None:
158 self._vcs._year_hacks = self._year_hacks
160 def _load_aliases_conf(self, parser, encoding=None):
162 encoding = self._encoding or _utils.ENCODING
164 for author in parser.options('aliases'):
165 _aliases = parser.get('aliases', author)
166 author = str(author, encoding)
167 aliases[author] = set(
168 str(a.strip(), encoding) for a in _aliases.split('|'))
169 self._aliases = aliases
170 if self._vcs is not None:
171 self._vcs._aliases = self._aliases
175 'project': self._name,
176 'vcs': self._vcs.name,
179 def update_authors(self, dry_run=False):
180 _LOG.info('update AUTHORS')
181 authors = self._vcs.authors()
182 new_contents = '{} was written by:\n{}\n'.format(
183 self._name, '\n'.join(authors))
185 _os_path.join(self._root, 'AUTHORS'),
186 new_contents, unicode=True, encoding=self._encoding,
189 def update_file(self, filename, dry_run=False):
190 _LOG.info('update {}'.format(filename))
191 contents = _utils.get_contents(
192 filename=filename, unicode=True, encoding=self._encoding)
193 original_year = self._vcs.original_year(filename=filename)
194 authors = self._vcs.authors(filename=filename)
195 new_contents = _utils.update_copyright(
196 contents=contents, original_year=original_year, authors=authors,
197 text=self._copyright, info=self._info(), prefix=('# ', '# ', None),
198 width=self._width, tag=self._copyright_tag)
199 new_contents = _utils.update_copyright(
200 contents=new_contents, original_year=original_year,
201 authors=authors, text=self._copyright, info=self._info(),
202 prefix=('/* ', ' * ', ' */'), width=self._width,
203 tag=self._copyright_tag)
205 filename=filename, contents=new_contents,
206 original_contents=contents, unicode=True, encoding=self._encoding,
209 def update_files(self, files=None, dry_run=False):
210 if files is None or len(files) == 0:
211 files = _utils.list_files(root=self._root)
212 for filename in files:
213 if self._ignored_file(filename=filename):
215 self.update_file(filename=filename, dry_run=dry_run)
217 def update_pyfile(self, dry_run=False):
218 if self._pyfile is None:
219 _LOG.info('no pyfile location configured, skip `update_pyfile`')
221 _LOG.info('update pyfile at {}'.format(self._pyfile))
222 current_year = _time.gmtime()[0]
223 original_year = self._vcs.original_year()
224 authors = self._vcs.authors()
226 _utils.copyright_string(
227 original_year=original_year, final_year=current_year,
228 authors=authors, text=self._copyright, info=self._info(),
229 prefix=('# ', '# ', None), width=self._width),
230 '', 'import textwrap as _textwrap', '', '',
232 _utils.copyright_string(
233 original_year=original_year, final_year=current_year,
234 authors=authors, text=self._copyright, info=self._info(),
235 prefix=('', '', None), width=self._width),
238 'def short_license(info, wrap=True, **kwargs):',
241 paragraphs = _utils.copyright_string(
242 original_year=original_year, final_year=current_year,
243 authors=authors, text=self._short_copyright, info=self._info(),
244 author_format_fn=_utils.short_author_formatter, wrap=False,
247 lines.append(" '{}'.format(**info),".format(
248 p.replace("'", r"\'")))
252 ' for i,p in enumerate(paragraphs):',
253 ' paragraphs[i] = _textwrap.fill(p, **kwargs)',
254 r" return '\n\n'.join(paragraphs)",
255 '', # for terminal endline
257 new_contents = '\n'.join(lines)
259 filename=self._pyfile, contents=new_contents, unicode=True,
260 encoding=self._encoding, dry_run=dry_run)
262 def _ignored_file(self, filename):
265 >>> p._ignored_paths = ['a', './b/']
266 >>> p._ignored_file('./a/')
268 >>> p._ignored_file('b')
270 >>> p._ignored_file('a/z')
272 >>> p._ignored_file('ab/z')
274 >>> p._ignored_file('./ab/a')
276 >>> p._ignored_file('./z')
279 filename = _os_path.relpath(filename, self._root)
280 if self._ignored_paths is not None:
282 while base not in ['', '.', '..']:
283 for path in self._ignored_paths:
284 if _fnmatch.fnmatch(base, _os_path.normpath(path)):
285 _LOG.debug('ignoring {} (matched {})'.format(
288 base = _os_path.split(base)[0]
289 if self._vcs and not self._vcs.is_versioned(filename):
290 _LOG.debug('ignoring {} (not versioned))'.format(filename))