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

stakkr.command   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Test Coverage

Coverage 97.22%

Importance

Changes 0
Metric Value
eloc 37
dl 0
loc 62
ccs 35
cts 36
cp 0.9722
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 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