Passed
Branch v4.0-dev (e005f1)
by Emmanuel
05:49
created

stakkr.command._print_errors()   A

Complexity

Conditions 5

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 11
nop 1
dl 0
loc 15
ccs 11
cts 11
cp 1
crap 5
rs 9.3333
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
Useful when you need to write a plugin that outputs some progress or info.
7
"""
8
9 1
import subprocess
10 1
import sys
11 1
from io import BufferedReader
12 1
from click import echo, style
13
14
15 1
def launch_cmd_displays_output(cmd: list, print_msg: bool = True, print_err: bool = True,
16
                               err_to_out: bool = False):
17
    """Launch a command and displays conditionally messages and / or errors."""
18 1
    try:
19 1
        stderr = subprocess.PIPE if err_to_out is False else subprocess.STDOUT
20 1
        result = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=stderr)
21 1
    except Exception as error:
22 1
        raise SystemError('Cannot run the command: {}'.format(error))
23
24 1
    _read_messages(result, print_msg)
25 1
    if print_err is True and err_to_out is False:
26 1
        _print_errors(result)
27
28 1
    return result
29
30
31 1
def verbose(display: bool, message: str):
32
    """Display a message if verbose is On."""
33 1
    if display is True:
34
        echo(style('[VERBOSE]', fg='green') + ' {}'.format(message), file=sys.stderr)
35
36
37 1
def _read_messages(result: BufferedReader, display: bool = False):
38
    """Print messages sent to the STDOUT."""
39 1
    for line in result.stdout:
40 1
        line = line.decode()
41 1
        line = line if display is True else '.'
42 1
        print(line, end='')
43 1
        sys.stdout.flush()
44
45 1
    print()
46
47
48 1
def _print_errors(result: BufferedReader):
49
    """Print messages sent to the STDERR."""
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