aboutsummaryrefslogtreecommitdiff
blob: eeea35658c2d07d67fffd359e6e39f8a1bddd898 (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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
# Copyright(c) 2009, Gentoo Foundation
#
# Licensed under the GNU General Public License, v2

"""Display USE flags for a given package"""

__docformat__ = "epytext"

# =======
# Imports
# =======

import os
import sys

from functools import partial
from getopt import gnu_getopt, GetoptError
from glob import glob

from portage import settings
from portage import _encodings, _unicode_encode

import gentoolkit.pprinter as pp
from gentoolkit import errors
from gentoolkit.equery import format_options, mod_usage, CONFIG
from gentoolkit.textwrap_ import TextWrapper
from gentoolkit.query import Query
from gentoolkit.flag import get_flags, reduce_flags

# =======
# Globals
# =======

QUERY_OPTS = {
    "all_versions": False,
    "forced_masked": False,
    "ignore_l10n": False,
}

# =========
# Functions
# =========


def print_help(with_description=True):
    """Print description, usage and a detailed help message.

    @type with_description: bool
    @param with_description: if true, print module's __doc__ string
    """

    if with_description:
        print(__doc__.strip())
        print()
    print(mod_usage(mod_name=__name__.split(".")[-1]))
    print()
    print(pp.command("options"))
    print(
        format_options(
            (
                (" -h, --help", "display this help message"),
                (" -a, --all", "include all package versions"),
                (" -f, --forced-masked", "include forced/masked USE flags"),
                (" -i, --ignore-l10n", "don't show l10n USE flags"),
            )
        )
    )


def display_useflags(output):
    """Print USE flag descriptions and statuses.

    @type output: list
    @param output: [(inuse, inused, flag, desc, restrict), ...]
            inuse (int) = 0, 1, 2, 3;
                    if 1, flag is set in make.conf;
                    if 2, flag is masked;
                    if 3, flag is forced
            inused (int) = 0, 1, 2, 3;
                    if 1, package is installed with flag enabled;
                    if 2, flag is masked;
                    if 3, flag is forced
            flag (str) = the name of the USE flag
            desc (str) = the flag's description
            restrict (str) = corresponds to the text of restrict in metadata
    """

    maxflag_len = len(max([t[2] for t in output], key=len))

    twrap = TextWrapper()
    twrap.width = CONFIG["termWidth"]
    twrap.subsequent_indent = " " * (maxflag_len + 8)

    markers = ("-", "+", "M", "F")
    # Colors for masked/forced = unset/set (mod 2)
    color = (partial(pp.useflag, enabled=False), partial(pp.useflag, enabled=True))
    for in_makeconf, in_installed, flag, desc, restrict in output:
        if CONFIG["verbose"]:
            flag_name = ""
            if in_makeconf != in_installed:
                flag_name += pp.emph(
                    " %s %s" % (markers[in_makeconf], markers[in_installed])
                )
            else:
                flag_name += " %s %s" % (markers[in_makeconf], markers[in_installed])

            flag_name += " " + color[in_makeconf % 2](flag.ljust(maxflag_len))
            flag_name += " : "

            # Strip initial whitespace at the start of the description
            # Bug 432530
            if desc:
                desc = desc.lstrip()

            # print description
            if restrict:
                restrict = "(%s %s)" % (pp.emph("Restricted to"), pp.cpv(restrict))
                twrap.initial_indent = flag_name
                pp.uprint(twrap.fill(restrict))
                if desc:
                    twrap.initial_indent = twrap.subsequent_indent
                    pp.uprint(twrap.fill(desc))
                else:
                    print(" : <unknown>")
            else:
                if desc:
                    twrap.initial_indent = flag_name
                    desc = twrap.fill(desc)
                    pp.uprint(desc)
                else:
                    twrap.initial_indent = flag_name
                    print(twrap.fill("<unknown>"))
        else:
            # Match emerge -v output for forced/masked flags
            if in_makeconf > 1:
                pp.uprint("(" + markers[in_makeconf % 2] + flag + ")")
            else:
                pp.uprint(markers[in_makeconf] + flag)


def get_global_useflags():
    """Get global and expanded USE flag variables from
    PORTDIR/profiles/use.desc and PORTDIR/profiles/desc/*.desc respectively.

    @rtype: dict
    @return: {'flag_name': 'flag description', ...}
    """

    global_usedesc = {}
    # Get global USE flag descriptions
    try:
        path = os.path.join(settings["PORTDIR"], "profiles", "use.desc")
        with open(
            _unicode_encode(path, encoding=_encodings["fs"]),
            encoding=_encodings["content"],
        ) as open_file:
            for line in open_file:
                if line.startswith("#"):
                    continue
                # Ex. of fields: ['syslog', 'Enables support for syslog\n']
                fields = line.split(" - ", 1)
                if len(fields) == 2:
                    global_usedesc[fields[0]] = fields[1].rstrip()
    except IOError:
        sys.stderr.write(
            pp.warn("Could not load USE flag descriptions from %s" % pp.path(path))
        )

    del path, open_file
    # Add USE_EXPANDED variables to usedesc hash -- Bug #238005
    for path in glob(os.path.join(settings["PORTDIR"], "profiles", "desc", "*.desc")):
        try:
            with open(
                _unicode_encode(path, encoding=_encodings["fs"]),
                encoding=_encodings["content"],
            ) as open_file:
                for line in open_file:
                    if line.startswith("#"):
                        continue
                    fields = [field.strip() for field in line.split(" - ", 1)]
                    if len(fields) == 2:
                        expanded_useflag = "%s_%s" % (
                            path.split("/")[-1][0:-5],
                            fields[0],
                        )
                        global_usedesc[expanded_useflag] = fields[1]
        except IOError:
            sys.stderr.write(
                pp.warn("Could not load USE flag descriptions from %s" % path)
            )

    return global_usedesc


def get_output_descriptions(pkg, global_usedesc):
    """Prepare descriptions and usage information for each USE flag."""

    if pkg.metadata is None:
        local_usedesc = []
    else:
        local_usedesc = pkg.metadata.use()

    useforced = []
    usemasked = []
    if QUERY_OPTS["forced_masked"]:
        iuse, final_use, useforced, usemasked = get_flags(
            pkg.cpv, final_setting=True, include_forced_masked=True
        )
    else:
        iuse, final_use = get_flags(
            pkg.cpv, final_setting=True, include_forced_masked=False
        )
    usevar = reduce_flags(iuse)
    usevar.sort()

    if QUERY_OPTS["ignore_l10n"]:
        for a in usevar[:]:
            if a.startswith("l10n_"):
                usevar.remove(a)

    if pkg.is_installed():
        used_flags = pkg.use().split()
    else:
        used_flags = settings["USE"].split()

    # store (inuse, inused, flag, desc, restrict)
    output = []
    for flag in usevar:
        inuse = 0
        inused = 0

        local_use = None
        for use in local_usedesc:
            if use.name == flag:
                local_use = use
                break

        try:
            desc = local_use.description
        except AttributeError:
            try:
                desc = global_usedesc[flag]
            except KeyError:
                desc = ""

        try:
            restrict = local_use.restrict
            restrict = restrict if restrict is not None else ""
        except AttributeError:
            restrict = ""

        if flag in final_use:
            inuse = 1
            if flag in useforced:
                inuse = 3
        elif flag in usemasked:
            inuse = 2

        if flag in used_flags:
            inused = 1
            if flag in useforced:
                inused = 3
        elif flag in usemasked:
            inused = 2

        output.append((inuse, inused, flag, desc, restrict))

    return output


def parse_module_options(module_opts):
    """Parse module options and update QUERY_OPTS"""

    opts = (x[0] for x in module_opts)
    for opt in opts:
        if opt in ("-h", "--help"):
            print_help()
            sys.exit(0)
        elif opt in ("-a", "--all"):
            QUERY_OPTS["all_versions"] = True
        elif opt in ("-f", "--forced-masked"):
            QUERY_OPTS["forced_masked"] = True
        elif opt in ("-i", "--ignore-l10n"):
            QUERY_OPTS["ignore_l10n"] = True


def print_legend():
    """Print a legend to explain the output format."""

    print("[ Legend : %s - final flag setting for installation]" % pp.emph("U"))
    print("[        : %s - package is installed with flag     ]" % pp.emph("I"))
    print(
        "[ Colors : %s, %s                             ]"
        % (pp.useflag("set", enabled=True), pp.useflag("unset", enabled=False))
    )


def main(input_args):
    """Parse input and run the program"""

    short_opts = "hafi"
    long_opts = ("help", "all", "forced-masked", "ignore-l10n")

    try:
        module_opts, queries = gnu_getopt(input_args, short_opts, long_opts)
    except GetoptError as err:
        sys.stderr.write(pp.error("Module %s" % err))
        print()
        print_help(with_description=False)
        sys.exit(2)

    parse_module_options(module_opts)

    if not queries:
        print_help()
        sys.exit(2)

    #
    # Output
    #

    first_run = True
    legend_printed = False
    for query in (Query(x) for x in queries):
        if not first_run:
            print()

        if QUERY_OPTS["all_versions"]:
            matches = query.find(include_masked=True)
        else:
            matches = [query.find_best()]

        if not any(matches):
            raise errors.GentoolkitNoMatches(query)

        matches.sort()

        global_usedesc = get_global_useflags()
        for pkg in matches:
            output = get_output_descriptions(pkg, global_usedesc)
            if output:
                if CONFIG["verbose"]:
                    if not legend_printed:
                        print_legend()
                        legend_printed = True
                    print((" * Found these USE flags for %s:" % pp.cpv(str(pkg.cpv))))
                    print(pp.emph(" U I"))
                display_useflags(output)
            else:
                if CONFIG["verbose"]:
                    sys.stderr.write(
                        pp.warn("No USE flags found for %s" % pp.cpv(pkg.cpv))
                    )

        first_run = False


# vim: set ts=4 sw=4 tw=79: