Completed
Push — develop ( 0e26e2...395b20 )
by Jace
06:01
created

main()   B

Complexity

Conditions 5

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 5

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 5
c 4
b 0
f 0
dl 0
loc 24
ccs 14
cts 14
cp 1
crap 5
rs 8.1671
1
"""Update project metrics on The Coverage Space.
2
3
Usage:
4
  coverage.space <owner/repo> <metric> [<value>] [--verbose] [--exit-code]
5
  coverage.space <owner/repo> --reset [--verbose]
6
  coverage.space (-h | --help)
7
  coverage.space (-V | --version)
8
9
Options:
10
  -h --help         Show this help screen.
11
  -V --version      Show the program version.
12
  -v --verbose      Always display the coverage metrics.
13
  -x --exit-code    Return non-zero exit code on failures.
14
15
"""
16
17 1
from __future__ import unicode_literals
18
19 1
import sys
20 1
import json
21 1
import logging
22
23 1
import six
24 1
from docopt import docopt, DocoptExit
0 ignored issues
show
Configuration introduced by Jace Browning
The import docopt could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

This error could indicate a configuration issue of Pylint. Make sure that your libraries are available by adding the necessary commands.

# .scrutinizer.yml
before_commands:
    - sudo pip install abc # Python2
    - sudo pip3 install abc # Python3
Tip: We are currently not using virtualenv to run pylint, when installing your modules make sure to use the command for the correct version.

2. Missing __init__.py files

This error could also result from missing __init__.py files in your module folders. Make sure that you place one file in each sub-folder.

Loading history...
25 1
import colorama
26 1
from backports.shutil_get_terminal_size import get_terminal_size
0 ignored issues
show
Configuration introduced by Jace Browning
The import backports.shutil_get_terminal_size could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

This error could indicate a configuration issue of Pylint. Make sure that your libraries are available by adding the necessary commands.

# .scrutinizer.yml
before_commands:
    - sudo pip install abc # Python2
    - sudo pip3 install abc # Python3
Tip: We are currently not using virtualenv to run pylint, when installing your modules make sure to use the command for the correct version.

2. Missing __init__.py files

This error could also result from missing __init__.py files in your module folders. Make sure that you place one file in each sub-folder.

Loading history...
27
28 1
from . import API, VERSION
29 1
from . import services, client
30 1
from .plugins import get_coverage
31
32
33 1
log = logging.getLogger(__name__)
34
35
36 1
def main():
37
    """Parse command-line arguments, configure logging, and run the program."""
38 1
    colorama.init(autoreset=True)
39 1
    arguments = docopt(__doc__, version=VERSION)
40
41 1
    slug = arguments['<owner/repo>']
42 1
    metric = arguments['<metric>']
43 1
    reset = arguments['--reset']
44 1
    value = arguments['<value>']
45 1
    verbose = arguments['--verbose']
46 1
    hardfail = arguments['--exit-code']
47
48 1
    logging.basicConfig(
49
        level=logging.DEBUG if verbose else logging.WARNING,
50
        format="%(levelname)s: %(name)s: %(message)s",
51
    )
52
53 1
    if '/' not in slug:
54
        raise DocoptExit("<owner/repo> slug must contain a slash" + '\n')
55 1
56 1
    success = run(slug, metric, value, reset, verbose, hardfail)
57
58
    if not success and hardfail:
59 1
        sys.exit(1)
60
61 1
62 1
def run(*args, **kwargs):
63 1
    """Run the program."""
64
    if services.detected():
65 1
        log.info("Coverage check skipped when running on CI service")
66
        return True
67
    else:
68 1
        return call(*args, **kwargs)
69
70 1
71 1
def call(slug, metric, value, reset=False, verbose=False, hardfail=False):
72 1
    """Call the API and display errors."""
73 1
    url = "{}/{}".format(API, slug)
74
    if reset:
75 1
        data = {metric: None}
76 1
        response = client.delete(url, data)
77
    else:
78 1
        data = {metric: value or get_coverage()}
79 1
        response = client.get(url, data)
80 1
81 1
    if response.status_code == 200:
82
        if verbose:
83 1
            display("coverage increased", response.json(), colorama.Fore.GREEN)
0 ignored issues
show
Bug introduced by Jace Browning
The Instance of AnsiCodes does not seem to have a member named GREEN.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
84 1
        return True
85 1
86
    elif response.status_code == 202:
87 1
        display("coverage reset", response.json(), colorama.Fore.BLUE)
0 ignored issues
show
Bug introduced by Jace Browning
The Instance of AnsiCodes does not seem to have a member named BLUE.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
88 1
        return True
89 1
90 1
    elif response.status_code == 422:
91
        color = colorama.Fore.RED if hardfail else colorama.Fore.YELLOW
0 ignored issues
show
Bug introduced by Jace Browning
The Instance of AnsiCodes does not seem to have a member named RED.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
Bug introduced by Jace Browning
The Instance of AnsiCodes does not seem to have a member named YELLOW.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
92 1
        data = response.json()
93 1
        data['help'] = \
94
            "To reset metrics, run: coverage.space {} --reset".format(slug)
95
        display("coverage decreased", data, color)
96 1
        return False
97 1
98 1
    else:
99 1
        try:
100 1
            data = response.json()
101 1
            display("coverage unknown", data, colorama.Fore.RED)
0 ignored issues
show
Bug introduced by Jace Browning
The Instance of AnsiCodes does not seem to have a member named RED.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
102 1
        except (TypeError, ValueError) as exc:
103
            data = response.data.decode('utf-8')
104
            log.error("%s\n\nwhen decoding response:\n\n%s\n", exc, data)
105 1
        return False
106
107 1
108 1
def display(title, data, color=""):
109 1
    """Write colored text to the console."""
110 1
    color += colorama.Style.BRIGHT
0 ignored issues
show
Bug introduced by Jace Browning
The Instance of AnsiCodes does not seem to have a member named BRIGHT.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
111 1
    width, _ = get_terminal_size()
112
    six.print_(color + "{0:=^{1}}".format(' ' + title + ' ', width))
113
    six.print_(color + json.dumps(data, indent=4))
114
    six.print_(color + '=' * width)
115