aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/pull/utils.py
blob: 2ce7cbeab4e3d940950b1b16bd9bed3d6bfe6dc7 (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
import contextlib
import logging
import os
import subprocess


def check_output(*args, stdout=subprocess.PIPE, **kwargs):
    result = subprocess.run(args, stdout=stdout, stderr=subprocess.STDOUT,
                            encoding='utf-8', **kwargs)
    try:
        result.check_returncode()
        if stdout != subprocess.DEVNULL:
            if result.stdout is None:
                logging.debug('%s', args)
            else:
                logging.debug('%s\n%s', args, result.stdout)
        return result.returncode == 0, result.stdout
    except subprocess.CalledProcessError as e:
        if stdout != subprocess.DEVNULL:
            logging.error('%s\n%s', e, e.output)
        return e.returncode == 0, e.output


def run(*args, discard_output=False, **kwargs):
    if discard_output:
        success, _ = check_output(*args, stdout=subprocess.DEVNULL, **kwargs)
    else:
        success, _ = check_output(*args, **kwargs)
    return success


@contextlib.contextmanager
def chdir(new_cwd):
    old_cwd = os.getcwd()
    os.chdir(new_cwd)
    try:
        yield
    finally:
        os.chdir(old_cwd)