1# -*- coding: utf-8 -*-
2# flake8: noqa
3# pylint: skip-file
4"""Check available packages in pypi."""
5
6import os
7import sys
8from subprocess import PIPE, Popen
9
10from isbntools.contrib.modules.uxcolors import _colors as colors
11
12PY2 = sys.version < '3'
13PKGS = ('isbntools', 'isbnlib')
14WINDOWS = os.name == 'nt'
15EOL = '\r\n' if WINDOWS and not PY2 else '\n'
16PY3 = not PY2
17VIRTUAL = getattr(sys, 'base_prefix', sys.prefix) != sys.prefix or hasattr(
18    sys, 'real_prefix')
19BOLD = colors.BOLD
20RESET = colors.RESET
21
22
23def shell(shcmd=None):
24    """Run a shell command."""
25    if not shcmd:  # pragma: no cover
26        return
27    sp = Popen(shcmd,
28               shell=True,
29               stdin=PIPE,
30               stdout=PIPE,
31               stderr=PIPE,
32               close_fds=not WINDOWS)
33    (fo, fe) = (sp.stdout, sp.stderr)
34    if PY2:  # pragma: no cover
35        out = fo.read().strip(EOL)
36        err = fe.read().strip(EOL)
37    else:  # pragma: no cover
38        out = fo.read().decode('utf-8')
39        err = fe.read().decode('utf-8')
40    if out:
41        return out
42    if err:  # pragma: no cover
43        return 1
44
45
46def check_pypi(pkgs=PKGS):
47    """Check pypi for pkgs starting with pkgs."""
48    # (don't run this in appveyour)
49    if os.getenv('APPVEYOR', '') != '':
50        return 0
51    cmd = 'pip search '
52    try:
53        out = shell(cmd + ' '.join(pkgs))
54        if out.strip() == '1':  # pragma: no cover
55            print('')
56            print(
57                ' At %spypi%s, the "search" service is not available. Try later!'
58                % (BOLD, RESET))
59            return 1
60        if out:  # pragma: no cover
61            print('')
62            print(' At %spypi%s, the following packages are available:' %
63                  (BOLD, RESET))
64            print('')
65            print(out)
66        return 0
67    except Exception:  # pragma: no cover
68        return 1
69