Ran update-copyright.
[update-copyright.git] / update_copyright / vcs / mercurial.py
1 # Copyright (C) 2012 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 from __future__ import absolute_import
19
20 import StringIO as _StringIO
21 import os as _os
22 import sys as _sys
23
24 import mercurial as _mercurial
25 from mercurial.__version__ import version as _version
26 import mercurial.dispatch as _mercurial_dispatch
27
28 from . import VCSBackend as _VCSBackend
29 from . import utils as _utils
30
31
32 class MercurialBackend (_VCSBackend):
33     name = 'Mercurial'
34
35     def __init__(self, **kwargs):
36         super(MercurialBackend, self).__init__(**kwargs)
37         self._version = _version
38
39     def _hg_cmd(*args):
40         cwd = _os.getcwd()
41         stdout = _sys.stdout
42         stderr = _sys.stderr
43         tmp_stdout = _StringIO.StringIO()
44         tmp_stderr = _StringIO.StringIO()
45         _sys.stdout = tmp_stdout
46         _sys.stderr = tmp_stderr
47         _os.chdir(self._root)
48         try:
49             _mercurial_dispatch.dispatch(list(args))
50         finally:
51             _os.chdir(cwd)
52             _sys.stdout = stdout
53             _sys.stderr = stderr
54         return (tmp_stdout.getvalue().rstrip('\n'),
55                 tmp_stderr.getvalue().rstrip('\n'))
56
57     def _years(self, filename=None):
58         args = [
59             '--template', '{date|shortdate}\n',
60             # shortdate filter: YEAR-MONTH-DAY
61             ]
62         if filename is not None:
63             args.extend(['--follow', filename])
64         output,error = mercurial_cmd('log', *args)
65         years = set(int(line.split('-', 1)[0]) for line in output.splitlines())
66         return years
67
68     def _authors(self, filename=None):
69         args = ['--template', '{author}\n']
70         if filename is not None:
71             args.extend(['--follow', filename])
72         output,error = mercurial_cmd('log', *args)
73         authors = set(output.splitlines())
74         return authors
75
76     def is_versioned(self, filename):
77         output,error = mercurial_cmd('log', '--follow', filename)
78         if len(error) > 0:
79             return False
80         return True