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