Passed
Push — master ( 0fd795...73442f )
by Emmanuel
14:19
created

command.verbose()   A

Complexity

Conditions 2

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2.1481

Importance

Changes 0
Metric Value
cc 2
eloc 3
nop 2
dl 0
loc 4
ccs 2
cts 3
cp 0.6667
crap 2.1481
rs 10
c 0
b 0
f 0
1
"""
2
A command wrapper to get a live output displayed.
3
Useful when you need to write a plugin that outputs some progress or info.
4
"""
5
6 1
import subprocess
7 1
import sys
8 1
from io import BufferedReader
9 1
from click import echo, style
10
11
12 1
def launch_cmd_displays_output(cmd: list, print_msg: bool = True,
13
                               print_err: bool = True, err_to_out: bool = False):
14
    """Launch a command and displays conditionnaly messages and / or errors"""
15
16 1
    try:
17 1
        stderr = subprocess.PIPE if err_to_out is False else subprocess.STDOUT
18 1
        result = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=stderr)
19 1
    except Exception as error:
20 1
        raise SystemError('Cannot run the command: {}'.format(error))
21
22 1
    _read_messages(result, print_msg)
23 1
    if print_err is True and err_to_out is False:
24 1
        _print_errors(result)
25
26 1
    return result
27
28
29 1
def verbose(display: bool, message: str):
30
    """Display a message if verbose is On"""
31 1
    if display is True:
32
        echo(style('[VERBOSE]', fg='green') + ' {}'.format(message), file=sys.stderr)
33
34
35 1
def _read_messages(result: BufferedReader, display: bool = False):
36
    """Print messages sent to the STDOUT"""
37
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
50 1
    num = 0
51 1
    for line in result.stderr:
52 1
        err = line.decode()
53
54 1
        if num is 0:
55 1
            print(style("Command returned errors :", fg='red'))
56
57 1
        if num < 5:
58 1
            print(err, end='')
59 1
        elif num is 5:
60 1
            print(style('... and more', fg='red'))
61
62
        num += 1
63