Completed
Push — develop ( 604c57...dfb4a1 )
by Jace
8s
created

run()   A

Complexity

Conditions 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
dl 0
loc 7
ccs 5
cts 5
cp 1
crap 2
rs 9.4285
c 0
b 0
f 0
1
"""Update project metrics on The Coverage Space.
2
3
Usage:
4
  coverage.space <owner/repo> <metric> [<value>] [--verbose] [--exit-code]
5
  coverage.space (-h | --help)
6
  coverage.space (-V | --version)
7
8
Options:
9
  -h --help         Show this help screen.
10
  -V --version      Show the program version.
11
  -v --verbose      Always display the coverage metrics.
12
  -x --exit-code    Return non-zero exit code on failures.
13
14
"""
15
16 1
from __future__ import unicode_literals
17
18 1
import sys
19 1
import time
20 1
import json
21 1
import logging
22
23 1
import six
24 1
from docopt import docopt
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 requests
26 1
import colorama
27 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...
28
29 1
from . import API, VERSION
30 1
from . import services
31 1
from .plugins import get_coverage
32 1
from .cache import Cache
33
34
35 1
log = logging.getLogger(__name__)
36 1
cache = Cache()
37
38
39 1
def main():
40
    """Parse command-line arguments, configure logging, and run the program."""
41 1
    colorama.init(autoreset=True)
42 1
    arguments = docopt(__doc__, version=VERSION)
43
44 1
    slug = arguments['<owner/repo>']
45 1
    metric = arguments['<metric>']
46 1
    value = arguments['<value>'] or get_coverage()
47 1
    verbose = arguments['--verbose']
48 1
    hardfail = arguments['--exit-code']
49
50 1
    logging.basicConfig(
51
        level=logging.DEBUG if verbose else logging.WARNING,
52
        format="%(levelname)s: %(name)s: %(message)s",
53
    )
54
55 1
    success = run(slug, metric, value, verbose, hardfail)
56
57 1
    if not success and hardfail:
58 1
        sys.exit(1)
59
60
61 1
def run(*args, **kwargs):
62
    """Run the program."""
63 1
    if services.detected():
64 1
        log.warning("Command skipped when running on CI service")
65 1
        return True
66
    else:
67 1
        return call(*args, **kwargs)
68
69
70 1
def call(slug, metric, value, verbose=False, hardfail=False):
71
    """Call the API and display errors."""
72 1
    url = "{}/{}".format(API, slug)
73 1
    data = {metric: value}
74 1
    response = request(url, data)
75
76 1
    if response.status_code == 200:
77 1
        if verbose:
78 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...
79 1
        return True
80
81 1
    elif response.status_code == 422:
82 1
        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...
83 1
        display("coverage decreased", response.json(), color)
84 1
        return False
85
86
    else:
87 1
        try:
88 1
            data = response.json()
89 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...
90 1
        except (TypeError, ValueError) as exc:
91 1
            data = response.data.decode('utf-8')
92 1
            log.error("%s\n\nwhen decoding response:\n\n%s\n", exc, data)
93 1
        return False
94
95
96 1
def request(url, data):
97
    """Make request to external API."""
98 1
    log.info("Updating %s: %s", url, data)
99
100 1
    response = cache.get(url, data)
101 1
    if response is None:
102 1
        for _ in range(3):
103 1
            response = requests.put(url, data=data)
104 1
            if response.status_code == 500:
105 1
                time.sleep(3)
106 1
                continue
107
            else:
108 1
                break
109 1
        cache.set(url, data, response)
110
111 1
    log.info("Response: %s", response)
112
113 1
    return response
114
115
116 1
def display(title, data, color=""):
117
    """Write colored text to the console."""
118 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...
119 1
    width, _ = get_terminal_size()
120 1
    six.print_(color + "{0:=^{1}}".format(' ' + title + ' ', width))
121 1
    six.print_(color + json.dumps(data, indent=4))
122
    six.print_(color + '=' * width)
123