Passed
Push — master ( 868477...1b1f92 )
by Emmanuel
06:17
created

stakkr.command._read_messages()   A

Complexity

Conditions 3

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

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