Passed
Pull Request — develop (#45)
by Jace
01:02
created

verchew.script.match_version()   A

Complexity

Conditions 2

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 7
nop 2
dl 0
loc 9
ccs 6
cts 6
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
#!/usr/bin/env python
2
# -*- coding: utf-8 -*-
3
4
# The MIT License (MIT)
5
# Copyright © 2016, Jace Browning
6
#
7
# Permission is hereby granted, free of charge, to any person obtaining a copy
8
# of this software and associated documentation files (the "Software"), to deal
9
# in the Software without restriction, including without limitation the rights
10
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
# copies of the Software, and to permit persons to whom the Software is
12
# furnished to do so, subject to the following conditions:
13
#
14
# The above copyright notice and this permission notice shall be included in
15
# all copies or substantial portions of the Software.
16
#
17
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
# SOFTWARE.
24
#
25
# Source: https://github.com/jacebrowning/verchew
26
# Documentation: https://verchew.readthedocs.io
27
# Package: https://pypi.org/project/verchew
28
29
30 1
from __future__ import unicode_literals
31
32 1
import argparse
33 1
import logging
34 1
import os
35 1
import re
36 1
import sys
37
from collections import OrderedDict
38
from subprocess import PIPE, STDOUT, Popen
39 1
40 1
41 1
try:
42
    import configparser  # Python 3
43 1
except ImportError:
44
    import ConfigParser as configparser  # Python 2
45 1
46 1
__version__ = '1.5a1'
47 1
48
PY2 = sys.version_info[0] == 2
49
CONFIG_FILENAMES = [
50
    'verchew.ini',
51
    '.verchew.ini',
52
    '.verchewrc',
53
    '.verchew',
54
]
55
SAMPLE_CONFIG = """
56
[Python]
57
58
cli = python
59
versions = Python 3.5 | Python 3.6
60
61
[Legacy Python]
62
63
cli = python2
64
version = Python 2.7
65
66
[virtualenv]
67
68
cli = virtualenv
69
version = 15
70
message = Only required with Python 2.
71
72
[Make]
73 1
74
cli = make
75
version = GNU Make
76
optional = true
77
78
""".strip()
79 1
STYLE = {
80
    "~": "✔",
81
    "*": "⭑",
82
    "?": "⚠",
83
    "x": "✘",
84
}
85
COLOR = {
86
    "x": "\033[91m",  # red
87 1
    "~": "\033[92m",  # green
88
    "?": "\033[93m",  # yellow
89
    "*": "\033[94m",  # cyan
90 1
    None: "\033[0m",  # reset
91 1
}
92 1
93
log = logging.getLogger(__name__)
94 1
95 1
96
def main():
97 1
    args = parse_args()
98 1
    configure_logging(args.verbose)
99
100 1
    log.debug("PWD: %s", os.getenv('PWD'))
101 1
    log.debug("PATH: %s", os.getenv('PATH'))
102
103
    path = find_config(args.root, generate=args.init)
104 1
    config = parse_config(path)
105 1
106
    if not check_dependencies(config) and args.exit_code:
107 1
        sys.exit(1)
108 1
109 1
110
def parse_args():
111 1
    parser = argparse.ArgumentParser()
112
113 1
    version = "%(prog)s v" + __version__
114
    parser.add_argument('--version', action='version', version=version)
115 1
    parser.add_argument('-r', '--root', metavar='PATH',
116
                        help="specify a custom project root directory")
117
    parser.add_argument('--init', action='store_true',
118 1
                        help="generate a sample configuration file")
119
    parser.add_argument('--exit-code', action='store_true',
120 1
                        help="return a non-zero exit code on failure")
121
    parser.add_argument('-v', '--verbose', action='count', default=0,
122
                        help="enable verbose logging")
123 1
124 1
    args = parser.parse_args()
125 1
126
    return args
127
128
129
def configure_logging(count=0):
130
    if count == 0:
131 1
        level = logging.WARNING
132
    elif count == 1:
133
        level = logging.INFO
134 1
    else:
135 1
        level = logging.DEBUG
136 1
137
    logging.basicConfig(level=level, format="%(levelname)s: %(message)s")
138 1
139 1
140 1
def find_config(root=None, filenames=None, generate=False):
141 1
    root = root or os.getcwd()
142 1
    filenames = filenames or CONFIG_FILENAMES
143 1
144 1
    path = None
145 1
    log.info("Looking for config file in: %s", root)
146
    log.debug("Filename options: %s", ", ".join(filenames))
147 1
    for filename in os.listdir(root):
148 1
        if filename in filenames:
149 1
            path = os.path.join(root, filename)
150
            log.info("Found config file: %s", path)
151 1
            return path
152 1
153
    if generate:
154
        path = generate_config(root, filenames)
155 1
        return path
156 1
157 1
    msg = "No config file found in: {0}".format(root)
158
    raise RuntimeError(msg)
159 1
160
161 1
def generate_config(root=None, filenames=None):
162 1
    root = root or os.getcwd()
163 1
    filenames = filenames or CONFIG_FILENAMES
164
165 1
    path = os.path.join(root, filenames[0])
166
167
    log.info("Generating sample config: %s", path)
168 1
    with open(path, 'w') as config:
169 1
        config.write(SAMPLE_CONFIG + '\n')
170
171 1
    return path
172 1
173 1
174
def parse_config(path):
175 1
    data = OrderedDict()
176 1
177 1
    log.info("Parsing config file: %s", path)
178 1
    config = configparser.ConfigParser()
179
    config.read(path)
180 1
181
    for section in config.sections():
182
        data[section] = OrderedDict()
183 1
        for name, value in config.items(section):
184 1
            data[section][name] = value
185
186 1
    for name in data:
187 1
        versions = data[name].get('versions', data[name].pop('version', ""))
188 1
        data[name]['versions'] = versions
189 1
        data[name]['patterns'] = [v.strip() for v in versions.split('|')]
190 1
191 1
    return data
192
193 1
194 1
def check_dependencies(config):
195 1
    success = []
196
197 1
    for name, settings in config.items():
198 1
        show("Checking for {0}...".format(name), head=True)
199 1
        output = get_version(settings['cli'], settings.get('cli_version_arg'))
200 1
201
        for pattern in settings['patterns']:
202 1
            if match_version(pattern, output):
203
                show(_("~") + " MATCHED: {0}".format(pattern))
204 1
                success.append(_("~"))
205
                break
206
        else:
207 1
            if settings.get('optional'):
208 1
                show(_("?") + " EXPECTED: {0}".format(settings['versions']))
209 1
                success.append(_("?"))
210
            else:
211 1
                show(_("x") + " EXPECTED: {0}".format(settings['versions']))
212 1
                success.append(_("x"))
213 1
            if settings.get('message'):
214
                show(_("*") + " MESSAGE: {0}".format(settings['message']))
215 1
216
    show("Results: " + " ".join(success), head=True)
217
218 1
    return _("x") not in success
219 1
220
221
def get_version(program, argument=None):
222 1
    if argument is None:
223 1
        args = [program, '--version']
224 1
    elif argument:
225 1
        args = [program, argument]
226 1
    else:
227 1
        args = [program]
228
229 1
    show("$ {0}".format(" ".join(args)))
230 1
    output = call(args)
231 1
    show(output.splitlines()[0])
232
233 1
    return output
234
235
236 1
def match_version(pattern, output):
237
    regex = pattern.replace('.', r'\.') + r'\b'
238 1
239 1
    log.debug("Matching %s: %s", regex, output)
240 1
    match = re.match(regex, output)
241
    if match is None:
242 1
        match = re.match(r'.*[^\d.]' + regex, output)
243 1
244
    return bool(match)
245 1
246 1
247
def call(args):
248 1
    try:
249 1
        process = Popen(args, stdout=PIPE, stderr=STDOUT)
250
    except OSError:
251
        log.debug("Command not found: %s", args[0])
252 1
        output = "sh: command not found: {0}".format(args[0])
253
    else:
254 1
        raw = process.communicate()[0]
255
        output = raw.decode('utf-8').strip()
256 1
        log.debug("Command output: %r", output)
257 1
258 1
    return output
259 1
260 1
261 1
def show(text, start='', end='\n', head=False):
262
    """Python 2 and 3 compatible version of print."""
263 1
    if head:
264 1
        start = '\n'
265
        end = '\n\n'
266 1
267 1
    if log.getEffectiveLevel() < logging.WARNING:
268
        log.info(text)
269 1
    else:
270 1
        formatted = (start + text + end)
271
        if PY2:
272 1
            formatted = formatted.encode('utf-8')
273
        sys.stdout.write(formatted)
274
        sys.stdout.flush()
275
276
277
def _(word, is_tty=None, supports_utf8=None, supports_ansi=None):
278
    """Format and colorize a word based on available encoding."""
279
    formatted = word
280
281
    if is_tty is None:
282
        is_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()
283
    if supports_utf8 is None:
284
        supports_utf8 = sys.stdout.encoding == 'UTF-8'
285
    if supports_ansi is None:
286
        supports_ansi = sys.platform != 'win32' or 'ANSICON' in os.environ
287
288
    style_support = supports_utf8
289
    color_support = is_tty and supports_ansi
290
291
    if style_support:
292
        formatted = STYLE.get(word, word)
293
294
    if color_support and COLOR.get(word):
295
        formatted = COLOR[word] + formatted + COLOR[None]
296
297
    return formatted
298
299
300
if __name__ == '__main__':  # pragma: no cover
301
    main()
302