aboutsummaryrefslogtreecommitdiff
blob: e1c5e8cb7ca0669003f3e4a04ceca1775225e1ad (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
#!/usr/bin/env python

"""Copyright 2011 Gentoo Foundation
Distributed under the terms of the GNU General Public License v2
"""

from __future__ import print_function
import os

# Meta

__author__ = "Corentin Chary (iksaif)"
__email__ = "corentin.chary@gmail.com"
__version__ = "git"
__productname__ = "euscan"
__description__ = "A tool to detect new upstream releases."


# Imports

import sys
import getopt
from errno import EINTR, EINVAL
from httplib import HTTPConnection

from portage import settings
from portage.output import white, yellow, turquoise, green
from portage.exception import AmbiguousPackageName

from gentoolkit import pprinter as pp
from gentoolkit.errors import GentoolkitException

from euscan import CONFIG, output
from euscan.out import progress_bar


# Globals
isatty = os.environ.get('TERM') != 'dumb' and sys.stdout.isatty()
isatty_stderr = os.environ.get('TERM') != 'dumb' and sys.stderr.isatty()


def exit_helper(status):
    if CONFIG["format"]:
        print(output.get_formatted_output())
    sys.exit(status)


def setup_signals():
    """This block ensures that ^C interrupts are handled quietly."""
    import signal

    def exithandler(signum, frame):
        signal.signal(signal.SIGINT, signal.SIG_IGN)
        signal.signal(signal.SIGTERM, signal.SIG_IGN)
        print()
        exit_helper(EINTR)

    signal.signal(signal.SIGINT, exithandler)
    signal.signal(signal.SIGTERM, exithandler)
    signal.signal(signal.SIGPIPE, signal.SIG_DFL)


def print_version():
    """Output the version info."""
    print("%s (%s) - %s" \
            % (__productname__, __version__, __description__))
    print()
    print("Author: %s <%s>" % (__author__, __email__))
    print("Copyright 2011 Gentoo Foundation")
    print("Distributed under the terms of the GNU General Public License v2")


def print_usage(_error=None, help=None):
    """Print help message. May also print partial help to stderr if an
    error from {'options'} is specified."""

    out = sys.stdout
    if _error:
        out = sys.stderr

    if not _error in ('global-options', 'packages',):
        _error = None

    if not _error and not help:
        help = 'all'

    if _error in ('global-options',):
        output.eerror("Wrong option on command line.\n")

    if _error in ('packages',):
        output.eerror("You need to specify exactly one package.\n")

    print(white("Usage:"), file=out)
    if _error in ('global-options', 'packages',) or help == 'all':
        print(" " + turquoise(__productname__),
               yellow("[options]"),
               green("<package> [<package> [...]]"), file=out)
    if _error in ('global-options',) or help == 'all':
        print(" " + turquoise(__productname__),
               yellow("[--help, --version]"), file=out)

    print(file=out)
    if _error in ('global-options',) or help:
        print("Available ", yellow("options") + ":", file=out)
        print(yellow(" -C, --nocolor") +
            "                      - turn off colors on output", file=out)
        print(yellow(" -q, --quiet") +
            "                        - be as quiet as possible", file=out)
        print(yellow(" -h, --help") +
            "                         - display the help screen", file=out)
        print(yellow(" -V, --version") +
            "                      - display version info", file=out)
        print(file=out)
        print(yellow(" -1, --oneshot") +
            "                      - stop as soon as a new version is found",
            file=out)
        print(yellow(" -b, --brute-force=<level>") +
            "          - define the brute force " + yellow("<level>") +
            " (default: 2)\n" +
            " " * 38 + "bigger levels will generate more versions numbers\n" +
            " " * 38 + "0 means disabled", file=out)
        print(yellow(" -f, --format=<format>") +
            "              - define the output " + yellow("<format>") +
            " (available: json, xml)", file=out)
        print(yellow(" -p, --progress") +
            "                     - display a progress bar", file=out)
        print(yellow(" -i, --ignore-pre-release") +
            " " * 11 + "- Ignore non-stable versions", file=out)
        print(yellow(" -I, --ignore-pre-release-if-stable") +
            " - Ignore non-stable versions only if current\n" +
            " " * 38 + "version is stable", file=out)
        print(yellow("     --mirror") +
            "                       - use mirror:// URIs", file=out)
        print(yellow("     --ebuild-uri") +
            "                   - use ebuild variables in URIs", file=out)
        print(yellow("     --no-handlers") +
            "                  - exclude handlers (comma-separated list)",
            file=out)
        print(file=out)

    if _error in ('packages',) or help:
        print(green(" package") +
            " " * 28 + "- the packages (or ebuilds) you want to scan",
            file=out)
        print(file=out)

        #print( "More detailed instruction can be found in",
        #turquoise("`man %s`" % __productname__), file=out)


class ParseArgsException(Exception):
    """For parseArgs() -> main() communications."""
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return repr(self.value)


def parse_args():
    """Parse the command line arguments. Raise exceptions on
    errors. Returns packages and affects the CONFIG dict.
    """

    def option_switch(opts):
        """local function for interpreting command line options
        and setting options accordingly"""
        return_code = True
        for o, a in opts:
            if o in ("-h", "--help"):
                raise ParseArgsException('help')
            elif o in ("-V", "--version"):
                raise ParseArgsException('version')
            elif o in ("-C", "--nocolor"):
                CONFIG['nocolor'] = True
                pp.output.nocolor()
            elif o in ("-q", "--quiet"):
                CONFIG['quiet'] = True
                CONFIG['verbose'] = 0
            elif o in ("-1", "--oneshot"):
                CONFIG['oneshot'] = True
            elif o in ("-b", "--brute-force"):
                CONFIG['brute-force'] = int(a)
            elif o in ("-v", "--verbose") and not CONFIG['quiet']:
                CONFIG['verbose'] += 1
            elif o in ("-f", "--format"):
                CONFIG['format'] = a
                CONFIG['nocolor'] = True
                pp.output.nocolor()
            elif o in ("-p", "--progress"):
                CONFIG['progress'] = isatty_stderr
            elif o in ("--mirror"):
                CONFIG['mirror'] = True
            elif o in ("-i", "--ignore-pre-release"):
                CONFIG['ignore-pre-release'] = True
            elif o in ("-I", "--ignore-pre-release-if-stable"):
                CONFIG['ignore-pre-release-if-stable'] = True
            elif o in ("--ebuild-uri"):
                CONFIG['ebuild-uri'] = True
            elif o in ("--no-handlers"):
                CONFIG['handlers-exclude'] = a.split(",")
            else:
                return_code = False

        return return_code

    # here are the different allowed command line options (getopt args)
    getopt_options = {'short': {}, 'long': {}}
    getopt_options['short']['global'] = "hVCqv1bf:piI"
    getopt_options['long']['global'] = [
        "help", "version", "nocolor", "quiet", "verbose", "oneshot",
        "brute-force=", "format=", "progress", "mirror", "ignore-pre-release",
        "ignore-pre-release-if-stable", "ebuild-uri", "no-handlers="
    ]

    short_opts = getopt_options['short']['global']
    long_opts = getopt_options['long']['global']
    opts_mode = 'global'

    # apply getopts to command line, show partial help on failure
    try:
        opts, args = getopt.getopt(sys.argv[1:], short_opts, long_opts)
    except:
        raise ParseArgsException(opts_mode + '-options')

    # set options accordingly
    option_switch(opts)

    if len(args) < 1:
        raise ParseArgsException('packages')

    return args


def main():
    """Parse command line and execute all actions."""
    CONFIG['nocolor'] = (
        CONFIG['nocolor'] or
        (settings["NOCOLOR"] in ('yes', 'true') or not isatty)
    )
    if CONFIG['nocolor']:
        pp.output.nocolor()

    # parse command line options and actions
    try:
        queries = parse_args()
    except ParseArgsException as e:
        if e.value == 'help':
            print_usage(help='all')
            exit_helper(0)

        elif e.value[:5] == 'help-':
            print_usage(help=e.value[5:])
            exit_helper(0)

        elif e.value == 'version':
            print_version()
            exit_helper(0)

        else:
            print_usage(e.value)
            exit_helper(EINVAL)

    if CONFIG['verbose'] > 2:
        HTTPConnection.debuglevel = 1

    if not CONFIG["format"] and not CONFIG['quiet']:
        CONFIG["progress"] = False

    on_progress = None
    if CONFIG['progress']:
        on_progress_gen = progress_bar()
        on_progress = on_progress_gen.next()
        on_progress(maxval=len(queries) * 100, increment=0, label="Working...")

    # Importing stuff here for performance reasons
    from euscan.scan import scan_upstream

    for query in queries:
        if CONFIG["progress"]:
            on_progress(increment=10, label=query)

        ret = []

        output.set_query(query)

        try:
            ret = scan_upstream(query, on_progress)
        except AmbiguousPackageName as e:
            pkgs = e.args[0]
            output.eerror("\n".join(pkgs))

            from os.path import basename  # To get the short name

            output.eerror(
                "The short ebuild name '%s' is ambiguous. Please specify" %
                    basename(pkgs[0]) +
                "one of the above fully-qualified ebuild names instead."
            )
            exit_helper(1)

        except GentoolkitException as err:
            output.eerror('%s: %s' % (query, str(err)))
            exit_helper(1)

        except Exception as err:
            import traceback
            print ('-' * 60)
            traceback.print_exc(file=sys.stderr)
            print ('-' * 60)

            output.eerror('%s: %s' % (query, str(err)))
            exit_helper(1)

        if not ret and not CONFIG['quiet']:
            output.einfo(
                "Didn't find any new version, check package's homepage " +
                "for more informations"
            )

        if not (CONFIG['format'] or CONFIG['quiet']) and len(queries) > 1:
            print("")

    if CONFIG['progress']:
        on_progress_gen.next()
        print("\n", file=sys.stderr)

    output.set_query(None)


if __name__ == "__main__":
    setup_signals()
    main()
    exit_helper(0)