aboutsummaryrefslogtreecommitdiff
path: root/delivery_merge/utils.py
blob: 2f23e0e0a3e912928ceb390479881e60be77ec0a (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
import os
from contextlib import contextmanager
from subprocess import run


def sh(prog, *args):
    """ Execute a program with arguments
    :param prog: str: path to program
    :param args: tuple: variadic arguments
                 Accepts any combination of strings passed as arguments
    :returns: subprocess.CompletedProcess
    """
    command = [prog]
    tmp = []
    for arg in args:
        tmp += arg.split()

    command += tmp
    print(f'Running: {" ".join(command)}')
    return run(command, capture_output=True)


def git(*args):
    """ Execute git commands
    :param args: tuple: variadic arguments to pass to git
    :returns: subprocess.CompletedProcess
    """
    return sh('git', *args)


def getenv(s):
    """ Convert string of key pairs to dictionary format
    :param s: str: key pairs separated by newlines
    :returns: dict: converted key pairs
    """
    results = []
    for x in s.splitlines():
        if not x:
            continue
        pair = x.split('=', 1)
        if len(pair) < 2:
            pair.append('')
        results.append(pair)
    return dict(results)


@contextmanager
def pushd(path):
    """ Equivalent to shell pushd/popd behavior
    :param path: str: path to directory
    """
    last = os.path.abspath(os.getcwd())
    os.chdir(path)
    try:
        yield
    finally:
        os.chdir(last)