Convert update-copyright.py to a more modular framework.
[update-copyright.git] / update_copyright / vcs / mercurial.py
1 # Copyright
2
3 from __future__ import absolute_import
4
5 import StringIO as _StringIO
6 import os as _os
7 import sys as _sys
8
9 import mercurial as _mercurial
10 from mercurial.__version__ import version as _version
11 import mercurial.dispatch as _mercurial_dispatch
12
13 from . import VCSBackend as _VCSBackend
14 from . import utils as _utils
15
16
17 class MercurialBackend (_VCSBackend):
18     name = 'Mercurial'
19
20     @staticmethod
21     def _hg_cmd(*args):
22         cwd = _os.getcwd()
23         stdout = _sys.stdout
24         stderr = _sys.stderr
25         tmp_stdout = _StringIO.StringIO()
26         tmp_stderr = _StringIO.StringIO()
27         _sys.stdout = tmp_stdout
28         _sys.stderr = tmp_stderr
29         try:
30             _mercurial_dispatch.dispatch(list(args))
31         finally:
32             _os.chdir(cwd)
33             _sys.stdout = stdout
34             _sys.stderr = stderr
35         return (tmp_stdout.getvalue().rstrip('\n'),
36                 tmp_stderr.getvalue().rstrip('\n'))
37
38     def __init__(self, **kwargs):
39         super(MercurialBackend, self).__init__(**kwargs)
40         self._version = _version
41
42     def _years(self, filename=None):
43         args = [
44             '--template', '{date|shortdate}\n',
45             # shortdate filter: YEAR-MONTH-DAY
46             ]
47         if filename is not None:
48             args.extend(['--follow', filename])
49         output,error = mercurial_cmd('log', *args)
50         years = set(int(line.split('-', 1)[0]) for line in output.splitlines())
51         return years
52
53     def _authors(self, filename=None):
54         args = ['--template', '{author}\n']
55         if filename is not None:
56             args.extend(['--follow', filename])
57         output,error = mercurial_cmd('log', *args)
58         authors = set(output.splitlines())
59         return authors
60
61     def is_versioned(self, filename):
62         output,error = mercurial_cmd('log', '--follow', filename)
63         if len(error) > 0:
64             return False
65         return True