aboutsummaryrefslogtreecommitdiff
blob: 39e0b25586f973a55ef9d1518676d54ab18b1cf0 (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
# Copyright(c) 2009, Gentoo Foundation
#
# Licensed under the GNU General Public License, v2

"""List all packages that depend on a atom given query"""

__docformat__ = "epytext"

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

import sys
from getopt import gnu_getopt, GetoptError

import gentoolkit.pprinter as pp
from gentoolkit.dependencies import Dependencies
from gentoolkit.equery import format_options, mod_usage, CONFIG
from gentoolkit.helpers import get_cpvs, get_installed_cpvs
from gentoolkit.package import PackageFormatter, Package

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

QUERY_OPTS = {
    "include_masked": False,
    "only_direct": True,
    "max_depth": None,
    "package_format": None,
}

# =======
# Classes
# =======


class Printer:
    """Output L{gentoolkit.dependencies.Dependencies} objects for equery depends."""

    def __init__(self, verbose=True):
        self.verbose = verbose

        if verbose:
            self.print_fn = self.print_verbose
        else:
            self.print_fn = self.print_quiet

    def __call__(self, dep, dep_is_displayed=False):
        self.format_depend(dep, dep_is_displayed)

    @staticmethod
    def print_verbose(indent, cpv, use_conditional, depatom):
        """Verbosely prints a set of dep strings."""

        sep = " ? " if (depatom and use_conditional) else ""
        pp.uprint(indent + pp.cpv(cpv), "(" + use_conditional + sep + depatom + ")")

    @staticmethod
    def print_quiet(indent, cpv, use_conditional, depatom):
        """Quietly prints a subset set of dep strings."""

        pp.uprint(indent + cpv)

    @staticmethod
    def print_formated(pkg):
        """Print pkg as formatted output depending on CONFIG."""

        if pkg is None:
            return

        if CONFIG["verbose"]:
            print(
                PackageFormatter(
                    pkg, do_format=True, custom_format=QUERY_OPTS["package_format"]
                )
            )
        else:
            print(
                PackageFormatter(
                    pkg, do_format=False, custom_format=QUERY_OPTS["package_format"]
                )
            )

    def format_depend(self, dep, dep_is_displayed):
        """Format a dependency for printing for equery depends.

        @type dep: L{gentoolkit.dependencies.Dependencies}
        @param dep: the dependency to display
        """

        # Don't print blank lines
        if dep_is_displayed and not self.verbose:
            return

        depth = dep.depth
        indent = " " * depth
        mdep = dep.depatom
        use_conditional = ""

        if QUERY_OPTS["package_format"] != None:
            pkg = Package(str(dep.cpv))
            self.print_formated(pkg)
        else:
            if mdep.use_conditional:
                use_conditional = " & ".join(
                    pp.useflag(u) for u in mdep.use_conditional.split()
                )
            if mdep.operator == "=*":
                formatted_dep = "=%s*" % str(mdep.cpv)
            else:
                formatted_dep = mdep.operator + str(mdep.cpv)
            if mdep.slot:
                formatted_dep += pp.emph(":") + pp.slot(mdep.slot)
                if mdep.sub_slot:
                    formatted_dep += pp.slot("/") + pp.slot(mdep.sub_slot)
            if mdep.use:
                useflags = pp.useflag(",".join(mdep.use.tokens))
                formatted_dep += pp.emph("[") + useflags + pp.emph("]")

            if dep_is_displayed:
                indent = indent + " " * len(str(dep.cpv))
                self.print_fn(indent, "", use_conditional, formatted_dep)
            else:
                self.print_fn(indent, str(dep.cpv), use_conditional, formatted_dep)


# =========
# 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="depends"))
    print()
    print(pp.command("options"))
    print(
        format_options(
            (
                (" -h, --help", "display this help message"),
                (
                    " -a, --all-packages",
                    "include dependencies that are not installed (slow)",
                ),
                (" -D, --indirect", "search both direct and indirect dependencies"),
                (" -F, --format=TMPL", "specify a custom output format"),
                ("     --depth=N", "limit indirect dependency tree to specified depth"),
            )
        )
    )


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

    opts = (x[0] for x in module_opts)
    posargs = (x[1] for x in module_opts)
    for opt, posarg in zip(opts, posargs):
        if opt in ("-h", "--help"):
            print_help()
            sys.exit(0)
        elif opt in ("-a", "--all-packages"):
            QUERY_OPTS["include_masked"] = True
        elif opt in ("-D", "--indirect"):
            QUERY_OPTS["only_direct"] = False
        elif opt in ("-F", "--format"):
            QUERY_OPTS["package_format"] = posarg
        elif opt in ("--depth"):
            if posarg.isdigit():
                depth = int(posarg)
            else:
                err = "Module option --depth requires integer (got '%s')"
                sys.stdout.write(pp.error(err % posarg))
                print()
                print_help(with_description=False)
                sys.exit(2)
            QUERY_OPTS["max_depth"] = depth


def main(input_args):
    """Parse input and run the program"""
    short_opts = "hadDF:"  # -d, --direct was old option for default action
    long_opts = ("help", "all-packages", "direct", "indirect", "format", "depth=")

    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
    #

    printer = Printer(verbose=CONFIG["verbose"])

    first_run = True
    got_match = False
    for query in queries:
        if not first_run:
            print()

        pkg = Dependencies(query)
        if QUERY_OPTS["include_masked"]:
            pkggetter = get_cpvs
        else:
            pkggetter = get_installed_cpvs

        if CONFIG["verbose"]:
            print(" * These packages depend on %s:" % pp.emph(pkg.cpv))

        first_run = False

        last_seen = None
        for pkgdep in pkg.graph_reverse_depends(
            pkgset=sorted(pkggetter()),
            only_direct=QUERY_OPTS["only_direct"],
            max_depth=QUERY_OPTS["max_depth"],
        ):
            if last_seen is None or last_seen != pkgdep:
                seen = False
            else:
                seen = True
            printer(pkgdep, dep_is_displayed=seen)
            last_seen = pkgdep
        if last_seen is not None:
            got_match = True

    if got_match is None:
        sys.exit(1)


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