File size: 10,437 Bytes
71687cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
"""CLI implementation for `conda search`.

Query channels for packages matching the provided package spec.
"""

from __future__ import annotations

from argparse import SUPPRESS
from collections import defaultdict
from datetime import datetime, timezone
from typing import TYPE_CHECKING

from .helpers import _ValidatePackages

if TYPE_CHECKING:
    from argparse import ArgumentParser, Namespace, _SubParsersAction

    from ..models.records import PackageRecord


def configure_parser(sub_parsers: _SubParsersAction, **kwargs) -> ArgumentParser:
    from ..auxlib.ish import dals
    from ..common.constants import NULL
    from .helpers import (
        add_parser_channels,
        add_parser_json,
        add_parser_known,
        add_parser_networking,
    )

    summary = "Search for packages and display associated information using the MatchSpec format."
    description = dals(
        f"""
        {summary}

        MatchSpec is a query language for conda packages.
        """
    )
    epilog = dals(
        """
        Examples:

        Search for a specific package named 'scikit-learn'::

            conda search scikit-learn

        Search for packages containing 'scikit' in the package name::

            conda search *scikit*

        Note that your shell may expand '*' before handing the command over to conda.
        Therefore, it is sometimes necessary to use single or double quotes around the query::

            conda search '*scikit'
            conda search "*scikit*"

        Search for packages for 64-bit Linux (by default, packages for your current
        platform are shown)::

            conda search numpy[subdir=linux-64]

        Search for a specific version of a package::

            conda search 'numpy>=1.12'

        Search for a package on a specific channel::

            conda search conda-forge::numpy
            conda search 'numpy[channel=conda-forge, subdir=osx-64]'
        """
    )

    p = sub_parsers.add_parser(
        "search",
        help=summary,
        description=description,
        epilog=epilog,
        **kwargs,
    )
    p.add_argument(
        "--envs",
        action="store_true",
        help="Search all of the current user's environments. If run as Administrator "
        "(on Windows) or UID 0 (on unix), search all known environments on the system.",
    )
    p.add_argument(
        "-i",
        "--info",
        action="store_true",
        help="Provide detailed information about each package.",
    )
    p.add_argument(
        "--subdir",
        "--platform",
        action="store",
        dest="subdir",
        help="Search the given subdir. Should be formatted like 'osx-64', 'linux-32', "
        "'win-64', and so on. The default is to search the current platform.",
        default=NULL,
    )
    p.add_argument(
        "--skip-flexible-search",
        action="store_true",
        help="Do not perform flexible search if initial search fails.",
    )
    p.add_argument(
        "match_spec",
        default="*",
        nargs="?",
        action=_ValidatePackages,
        help=SUPPRESS,
    )
    p.add_argument(
        "--canonical",
        action="store_true",
        help=SUPPRESS,
    )
    p.add_argument(
        "-f",
        "--full-name",
        action="store_true",
        help=SUPPRESS,
    )
    p.add_argument(
        "--names-only",
        action="store_true",
        help=SUPPRESS,
    )
    add_parser_known(p)
    p.add_argument(
        "-o",
        "--outdated",
        action="store_true",
        help=SUPPRESS,
    )
    p.add_argument(
        "--spec",
        action="store_true",
        help=SUPPRESS,
    )
    p.add_argument(
        "--reverse-dependency",
        action="store_true",
        # help="Perform a reverse dependency search. Use 'conda search package --info' "
        #      "to see the dependencies of a package.",
        help=SUPPRESS,  # TODO: re-enable once we have --reverse-dependency working again
    )

    add_parser_channels(p)
    add_parser_networking(p)
    add_parser_json(p)
    p.set_defaults(func="conda.cli.main_search.execute")

    return p


def execute(args: Namespace, parser: ArgumentParser) -> int:
    """
    Implements `conda search` commands.

    `conda search <spec>` searches channels for packages.
    `conda search <spec> --envs` searches environments for packages.

    """
    from ..base.context import context
    from ..cli.common import stdout_json
    from ..core.envs_manager import query_all_prefixes
    from ..core.subdir_data import SubdirData
    from ..models.match_spec import MatchSpec
    from ..models.records import PackageRecord
    from ..models.version import VersionOrder
    from ..reporters import get_spinner

    spec = MatchSpec(args.match_spec)
    if spec.get_exact_value("subdir"):
        subdirs = (spec.get_exact_value("subdir"),)
    else:
        subdirs = context.subdirs

    if args.envs:
        with get_spinner(f"Searching environments for {spec}"):
            prefix_matches = query_all_prefixes(spec)
            ordered_result = tuple(
                {
                    "location": prefix,
                    "package_records": tuple(
                        sorted(
                            (
                                PackageRecord.from_objects(prefix_rec)
                                for prefix_rec in prefix_recs
                            ),
                            key=lambda prec: prec._pkey,
                        )
                    ),
                }
                for prefix, prefix_recs in prefix_matches
            )
        if context.json:
            stdout_json(ordered_result)
        elif args.info:
            for pkg_group in ordered_result:
                for prec in pkg_group["package_records"]:
                    pretty_record(prec)
        else:
            builder = [
                "# %-13s %15s %15s  %-20s %-20s"
                % (
                    "Name",
                    "Version",
                    "Build",
                    "Channel",
                    "Location",
                )
            ]
            for pkg_group in ordered_result:
                for prec in pkg_group["package_records"]:
                    builder.append(
                        "%-15s %15s %15s  %-20s %-20s"
                        % (
                            prec.name,
                            prec.version,
                            prec.build,
                            prec.channel.name,
                            pkg_group["location"],
                        )
                    )
            print("\n".join(builder))
        return 0

    with get_spinner("Loading channels"):
        spec_channel = spec.get_exact_value("channel")
        channel_urls = (spec_channel,) if spec_channel else context.channels

        matches = sorted(
            SubdirData.query_all(spec, channel_urls, subdirs),
            key=lambda rec: (rec.name, VersionOrder(rec.version), rec.build),
        )
    if not matches and not args.skip_flexible_search and spec.get_exact_value("name"):
        flex_spec = MatchSpec(spec, name=f"*{spec.name}*")
        if not context.json:
            print(f"No match found for: {spec}. Search: {flex_spec}")
        matches = sorted(
            SubdirData.query_all(flex_spec, channel_urls, subdirs),
            key=lambda rec: (rec.name, VersionOrder(rec.version), rec.build),
        )

    if not matches:
        from ..exceptions import PackagesNotFoundError
        from ..models.channel import all_channel_urls

        raise PackagesNotFoundError([spec], all_channel_urls(context.channels, subdirs))

    if context.json:
        json_obj = defaultdict(list)
        for match in matches:
            json_obj[match.name].append(match)
        stdout_json(json_obj)

    elif args.info:
        for record in matches:
            pretty_record(record)

    else:
        builder = [
            "# %-18s %15s %15s  %-20s"
            % (
                "Name",
                "Version",
                "Build",
                "Channel",
            )
        ]
        for record in matches:
            builder.append(
                "%-20s %15s %15s  %-20s"
                % (
                    record.name,
                    record.version,
                    record.build,
                    record.channel.name,
                )
            )
        print("\n".join(builder))
    return 0


def _pretty_record_format(record: PackageRecord) -> str:
    """
    Format a `PackageRecord` for `pretty_record()`
    """

    from ..common.io import dashlist
    from ..utils import human_bytes

    def push_line(display_name, attr_name):
        value = getattr(record, attr_name, None)
        if value is not None:
            builder.append("%-12s: %s" % (display_name, value))

    builder = []
    builder.append(f"{record.name} {record.version} {record.build}")
    builder.append("-" * len(builder[0]))

    push_line("file name", "fn")
    push_line("name", "name")
    push_line("version", "version")
    push_line("build", "build")
    push_line("build number", "build_number")
    size = getattr(record, "size", None)
    if size is not None:
        builder.append("%-12s: %s" % ("size", human_bytes(size)))
    push_line("license", "license")
    push_line("subdir", "subdir")
    push_line("url", "url")
    push_line("md5", "md5")
    if record.timestamp and isinstance(record.timestamp, (int, float)):
        date_str = datetime.fromtimestamp(record.timestamp, timezone.utc).strftime(
            "%Y-%m-%d %H:%M:%S %Z"
        )
        builder.append("%-12s: %s" % ("timestamp", date_str))
    if record.track_features:
        builder.append(
            "%-12s: %s" % ("track_features", dashlist(record.track_features))
        )
    if record.constrains:
        builder.append("%-12s: %s" % ("constraints", dashlist(record.constrains)))
    builder.append(
        "%-12s: %s"
        % ("dependencies", dashlist(record.depends) if record.depends else "[]")
    )
    builder.append("\n")
    return "\n".join(builder)


def pretty_record(record: PackageRecord, print=print) -> None:
    """
    Pretty prints a `PackageRecord`.

    :param record:  The `PackageRecord` object to print.
    """
    print(_pretty_record_format(record))