aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/cgitize/git.py
blob: a2be8dfd201618e3c0d99839937ef78b4290b2ef (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# Copyright (c) 2021 Egor Tensin <Egor.Tensin@gmail.com>
# This file is part of the "cgitize" project.
# For details, see https://github.com/egor-tensin/cgitize.
# Distributed under the MIT License.

from contextlib import contextmanager
import os

import cgitize.utils as utils


GIT_ENV = os.environ.copy()
GIT_ENV['GIT_SSH_COMMAND'] = 'ssh -oBatchMode=yes -oLogLevel=QUIET -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null'


class Config:
    def __init__(self, path):
        self.path = path

    def exists(self):
        return os.path.exists(self.path)

    def open(self, mode='r'):
        return open(self.path, mode=mode, encoding='utf-8')

    def read(self):
        with self.open(mode='r') as fd:
            return fd.read()

    def write(self, contents):
        with self.open(mode='w') as fd:
            fd.write(contents)

    @contextmanager
    def backup(self):
        old_contents = self.read()
        try:
            yield old_contents
        finally:
            self.write(old_contents)


class Git:
    EXE = 'git'

    @staticmethod
    def check(*args, **kwargs):
        return utils.try_run(Git.EXE, *args, env=GIT_ENV, **kwargs)

    @staticmethod
    def capture(*args, **kwargs):
        return utils.try_run_capture(Git.EXE, *args, env=GIT_ENV, **kwargs)

    @staticmethod
    def get_global_config():
        return Config(os.path.expanduser('~/.gitconfig'))

    @staticmethod
    @contextmanager
    def setup_auth(repo):
        if not repo.url_auth:
            yield
            return
        config = Git.get_global_config()
        with utils.protected_file(config.path):
            with config.backup() as old_contents:
                new_contents = f'''{old_contents}
[url "{repo.clone_url_with_auth}"]
    insteadOf = {repo.clone_url}
'''
                config.write(new_contents)
                yield