Passed
Push — master ( 61e6a6...28b40d )
by Emmanuel
07:42
created

stakkr.command   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
eloc 37
dl 0
loc 62
ccs 0
cts 36
cp 0
rs 10
c 0
b 0
f 0
wmc 15

4 Functions

Rating   Name   Duplication   Size   Complexity  
A _read_messages() 0 9 3
A launch_cmd_displays_output() 0 14 5
A verbose() 0 4 2
A _print_errors() 0 15 5
1
# coding: utf-8
2
"""
3
Command Wrapper.
4
5
A command wrapper to get a live output displayed.
6
"""
7
8
import subprocess
9
import sys
10
from io import BufferedReader
11
from click import echo, style
12
13
14
def launch_cmd_displays_output(cmd: list, print_msg: bool = True, print_err: bool = True,
15
                               err_to_out: bool = False):
16
    """Launch a command and displays conditionally messages and / or errors."""
17
    try:
18
        stderr = subprocess.PIPE if err_to_out is False else subprocess.STDOUT
19
        result = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=stderr)
20
    except Exception as error:
21
        raise SystemError('Cannot run the command: {}'.format(error))
22
23
    _read_messages(result, print_msg)
24
    if print_err is True and err_to_out is False:
25
        _print_errors(result)
26
27
    return result
28
29
30
def verbose(display: bool, message: str):
31
    """Display a message if verbose is On."""
32
    if display is True:
33
        echo(style('[VERBOSE]', fg='green') + ' {}'.format(message), file=sys.stderr)
34
35
36
def _read_messages(result: BufferedReader, display: bool = False):
37
    """Print messages sent to the STDOUT."""
38
    for line in result.stdout:
39
        line = line.decode()
40
        line = line if display is True else '.'
41
        print(line, end='')
42
        sys.stdout.flush()
43
44
    print()
45
46
47
def _print_errors(result: BufferedReader):
48
    """Print messages sent to the STDERR."""
49
    num = 0
50
    for line in result.stderr:
51
        err = line.decode()
52
53
        if num == 0:
54
            print(style("Command returned errors :", fg='red'))
55
56
        if num < 5:
57
            print(err, end='')
58
        elif num == 5:
59
            print(style('... and more', fg='red'))
60
61
        num += 1
62