1 # Copyright (C) 2012-2014 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.mercurial import MercurialBackend as _MercurialBackend
31 except ImportError as _mercurial_import_error:
32 _MercurialBackend = None
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))
41 self._author_hacks = None
42 self._year_hacks = 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
53 # unlikely to occur in the wild :p
54 self._copyright_tag = '-xyz-COPY' + '-RIGHT-zyx-'
56 def load_config(self, stream):
57 parser = _configparser.RawConfigParser()
58 parser.optionxform = str
60 for section in parser.sections():
61 clean_section = section.replace('-', '_')
63 loader = getattr(self, '_load_{}_conf'.format(clean_section))
64 except AttributeError as e:
65 _LOG.error('invalid {} section'.format(section))
69 def _load_project_conf(self, parser):
71 project = parser['project']
74 self._name = project.get('name')
75 vcs = project.get('vcs')
79 'author_hacks': self._author_hacks,
80 'year_hacks': self._year_hacks,
81 'aliases': self._aliases,
84 self._vcs = _GitBackend(**kwargs)
85 elif vcs == 'Mercurial':
86 if _MercurialBackend is None:
87 raise _mercurial_import_error
88 self._vcs = _MercurialBackend(**kwargs)
90 raise NotImplementedError('vcs: {}'.format(vcs))
92 def _load_copyright_conf(self, parser):
94 copyright = parser['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'])
102 def _split_paragraphs(self, text):
103 return [p.strip() for p in text.split('\n\n')]
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')
111 self._ignored_paths = [pth.strip() for pth in ignored.split('|')]
112 pyfile = files.get('pyfile')
114 self._pyfile = _os_path.join(self._root, pyfile)
116 def _load_author_hacks_conf(self, parser):
118 section = parser['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
129 def _load_year_hacks_conf(self, parser):
131 section = parser['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
141 def _load_aliases_conf(self, parser):
143 section = parser['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
156 'project': self._name,
157 'vcs': self._vcs.name,
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))
166 _os_path.join(self._root, 'AUTHORS'),
167 new_contents, unicode=True, encoding=self._encoding,
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)
186 filename=filename, contents=new_contents,
187 original_contents=contents, unicode=True, encoding=self._encoding,
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):
196 self.update_file(filename=filename, dry_run=dry_run)
198 def update_pyfile(self, dry_run=False):
199 if self._pyfile is None:
200 _LOG.info('no pyfile location configured, skip `update_pyfile`')
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()
207 _utils.copyright_string(
208 years=years, authors=authors, text=self._copyright,
209 info=self._info(), prefix=('# ', '# ', None),
211 '', 'import textwrap as _textwrap', '', '',
213 _utils.copyright_string(
214 years=years, authors=authors, text=self._copyright,
215 info=self._info(), prefix=('', '', None), width=self._width),
218 'def short_license(info, wrap=True, **kwargs):',
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,
227 lines.append(" '{}'.format(**info),".format(
228 p.replace("'", r"\'")))
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
237 new_contents = '\n'.join(lines)
239 filename=self._pyfile, contents=new_contents, unicode=True,
240 encoding=self._encoding, dry_run=dry_run)
242 def _ignored_file(self, filename):
245 >>> p._ignored_paths = ['a', './b/']
246 >>> p._ignored_file('./a/')
248 >>> p._ignored_file('b')
250 >>> p._ignored_file('a/z')
252 >>> p._ignored_file('ab/z')
254 >>> p._ignored_file('./ab/a')
256 >>> p._ignored_file('./z')
259 filename = _os_path.relpath(filename, self._root)
260 if self._ignored_paths is not None:
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(
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))