1# This Source Code Form is subject to the terms of the Mozilla Public
2# License, v. 2.0. If a copy of the MPL was not distributed with this
3# file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5import subprocess
6from functools import partial
7
8from mozlog import get_default_logger
9
10logger = None
11
12def vcs(bin_name):
13    def inner(command, *args, **kwargs):
14        global logger
15
16        if logger is None:
17            logger = get_default_logger("vcs")
18
19        repo = kwargs.pop("repo", None)
20        log_error = kwargs.pop("log_error", True)
21        if kwargs:
22            raise TypeError, kwargs
23
24        args = list(args)
25
26        proc_kwargs = {}
27        if repo is not None:
28            proc_kwargs["cwd"] = repo
29
30        command_line = [bin_name, command] + args
31        logger.debug(" ".join(command_line))
32        try:
33            return subprocess.check_output(command_line, stderr=subprocess.STDOUT, **proc_kwargs)
34        except subprocess.CalledProcessError as e:
35            if log_error:
36                logger.error(e.output)
37            raise
38    return inner
39
40git = vcs("git")
41hg = vcs("hg")
42
43
44def bind_to_repo(vcs_func, repo):
45    return partial(vcs_func, repo=repo)
46
47
48def is_git_root(path):
49    try:
50        rv = git("rev-parse", "--show-cdup", repo=path)
51    except subprocess.CalledProcessError:
52        return False
53    return rv == "\n"
54