aboutsummaryrefslogtreecommitdiff
path: root/src/clients/cave/cmd_search.cc
blob: 9b87f89a7389940c59c65db570143abae0bad3e6 (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
359
360
361
/* vim: set sw=4 sts=4 et foldmethod=syntax : */

/*
 * Copyright (c) 2010, 2011, 2013 Ciaran McCreesh
 *
 * This file is part of the Paludis package manager. Paludis is free software;
 * you can redistribute it and/or modify it under the terms of the GNU General
 * Public License version 2, as published by the Free Software Foundation.
 *
 * Paludis is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "cmd_search.hh"
#include "cmd_search_cmdline.hh"
#include "cmd_find_candidates.hh"
#include "cmd_match.hh"
#include "cmd_show.hh"

#include <paludis/args/args.hh>
#include <paludis/args/do_help.hh>

#include <paludis/name.hh>
#include <paludis/environment.hh>
#include <paludis/repository.hh>
#include <paludis/user_dep_spec.hh>
#include <paludis/filter.hh>
#include <paludis/generator.hh>
#include <paludis/filtered_generator.hh>
#include <paludis/selection.hh>
#include <paludis/package_id.hh>
#include <paludis/metadata_key.hh>
#include <paludis/action.hh>
#include <paludis/mask.hh>
#include <paludis/choice.hh>
#include <paludis/notifier_callback.hh>

#include <paludis/util/set.hh>
#include <paludis/util/wrapped_forward_iterator.hh>
#include <paludis/util/indirect_iterator-impl.hh>
#include <paludis/util/wrapped_output_iterator.hh>
#include <paludis/util/iterator_funcs.hh>
#include <paludis/util/make_null_shared_ptr.hh>
#include <paludis/util/stringify.hh>

#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <mutex>
#include <set>
#include <map>
#include <unistd.h>

#include "command_command_line.hh"

using namespace paludis;
using namespace cave;
using std::cout;
using std::endl;

namespace
{
    struct SearchCommandLine :
        CaveCommandCommandLine
    {
        virtual std::string app_name() const
        {
            return "cave search";
        }

        virtual std::string app_synopsis() const
        {
            return "Search for packages with particular characteristics.";
        }

        virtual std::string app_description() const
        {
            return "Searches for packages with particular characteristics.";
        }

        SearchCommandLineCandidateOptions search_options;
        SearchCommandLineMatchOptions match_options;
        SearchCommandLineIndexOptions index_options;

        SearchCommandLine() :
            search_options(this),
            match_options(this),
            index_options(this)
        {
            add_usage_line("[ --name | --description | --key HOMEPAGE ] pattern ...");
            add_note("'cave search' should only be used when a complex metadata search is required. To see "
                    "information about a known package, use 'cave show' instead.");
        }
    };

    struct SearchStep
    {
        std::string stage;

        SearchStep(const std::string & s) :
            stage(s)
        {
        }
    };

    void found_match(
            const std::shared_ptr<Environment> & env,
            const std::shared_ptr<Set<QualifiedPackageName> > & result,
            const PackageDepSpec & spec)
    {
        const std::shared_ptr<const PackageID> id(*((*env)[selection::RequireExactlyOne(
                        generator::Matches(spec, make_null_shared_ptr(), { }))])->begin());
        result->insert(id->name());
    }

    void found_candidate(
            const std::shared_ptr<Environment> & env,
            MatchCommand & match_command,
            const SearchCommandLineMatchOptions & match_options,
            const PackageDepSpec & spec,
            const std::shared_ptr<const Set<std::string> > & patterns,
            const std::function<void (const PackageDepSpec &)> & success
            )
    {
        if (match_command.run_hosted(env, match_options, patterns, spec))
            success(spec);
    }

    struct DisplayCallback
    {
        mutable std::mutex mutex;
        mutable std::map<std::string, int> metadata;
        mutable int steps;
        mutable std::string stage;
        mutable unsigned width;

        bool output;

        DisplayCallback() :
            steps(0),
            stage("Searching"),
            width(stage.length() + 2),
            output(::isatty(1))
        {
            if (output)
                cout << stage << ": " << std::flush;
        }

        ~DisplayCallback()
        {
            if (output)
                cout << endl << endl;
        }

        void update() const
        {
            if (! output)
                return;

            std::string s;
            s.append(stringify(steps));

            if (! metadata.empty())
            {
                std::multimap<int, std::string> biggest;
                for (std::map<std::string, int>::const_iterator i(metadata.begin()), i_end(metadata.end()) ;
                        i != i_end ; ++i)
                    biggest.insert(std::make_pair(i->second, i->first));

                int t(0), n(0);
                std::string ss;
                for (std::multimap<int, std::string>::const_reverse_iterator i(biggest.rbegin()), i_end(biggest.rend()) ;
                        i != i_end ; ++i)
                {
                    ++n;

                    if (n == 4)
                        ss.append(", ...");

                    if (n < 4)
                    {
                        if (! ss.empty())
                            ss.append(", ");

                        ss.append(stringify(i->first) + " " + i->second);
                    }

                    t += i->first;
                }

                if (! s.empty())
                    s.append(", ");
                s.append(stringify(t) + " metadata (" + ss + ") ");
            }

            s = stage + ": " + s;
            std::cout << std::string(width, '\010') << s;

            if (width > s.length())
                std::cout
                    << std::string(width - s.length(), ' ')
                    << std::string(width - s.length(), '\010');

            width = s.length();
            std::cout << std::flush;
        }

        void operator() (const NotifierCallbackEvent & event) const
        {
            event.accept(*this);
        }

        void operator() (const SearchStep & s) const
        {
            if (! output)
                return;

            std::unique_lock<std::mutex> lock(mutex);
            ++steps;
            stage = s.stage;
            update();
        }

        void visit(const NotifierCallbackGeneratingMetadataEvent & e) const
        {
            if (! output)
                return;

            std::unique_lock<std::mutex> lock(mutex);
            ++metadata.insert(std::make_pair(stringify(e.repository()), 0)).first->second;
            update();
        }

        void visit(const NotifierCallbackResolverStepEvent &) const
        {
        }

        void visit(const NotifierCallbackResolverStageEvent &) const
        {
        }

        void visit(const NotifierCallbackLinkageStepEvent &) const
        {
        }
    };

    void step(DisplayCallback & display_callback, const std::string & s)
    {
        display_callback(SearchStep(s));
    }
}

int
SearchCommand::run(
        const std::shared_ptr<Environment> & env,
        const std::shared_ptr<const Sequence<std::string > > & args
        )
{
    SearchCommandLine cmdline;
    cmdline.run(args, "CAVE", "CAVE_SEARCH_OPTIONS", "CAVE_SEARCH_CMDLINE");

    if (cmdline.a_help.specified())
    {
        cout << cmdline;
        return EXIT_SUCCESS;
    }

    if (cmdline.begin_parameters() == cmdline.end_parameters())
        throw args::DoHelp("search requires at least one parameter");

    int retcode(0);

    const std::shared_ptr<Sequence<std::string> > show_args(std::make_shared<Sequence<std::string>>());

    std::string name_description_substring_hint;
    do
    {
        /* cmd_match.cc has similar logic too */
        if (cmdline.match_options.a_key.specified())
            break;

        if ((cmdline.match_options.a_type.argument() != "text") && (cmdline.match_options.a_type.argument() != "exact"))
            break;

        if (cmdline.match_options.a_not.specified())
            break;

        if ((! cmdline.match_options.a_and.specified()) && (1 != capped_distance(cmdline.begin_parameters(), cmdline.end_parameters(), 2)))
            break;

        name_description_substring_hint = *cmdline.begin_parameters();
    } while (false);

    {
        DisplayCallback display_callback;
        ScopedNotifierCallback display_callback_holder(env.get(),
                NotifierCallbackFunction(std::cref(display_callback)));

        const std::shared_ptr<Set<std::string> > patterns(std::make_shared<Set<std::string>>());
        std::copy(cmdline.begin_parameters(), cmdline.end_parameters(), patterns->inserter());

        FindCandidatesCommand find_candidates_command;
        MatchCommand match_command;

        std::shared_ptr<Set<QualifiedPackageName> > matches(std::make_shared<Set<QualifiedPackageName>>());
        retcode |= find_candidates_command.run_hosted(env, cmdline.search_options, cmdline.match_options,
                cmdline.index_options, name_description_substring_hint, std::bind(
                    &found_candidate, env, std::ref(match_command), std::cref(cmdline.match_options),
                    std::placeholders::_1, patterns, std::function<void (const PackageDepSpec &)>(std::bind(
                            &found_match, env, std::ref(matches), std::placeholders::_1
                            ))),
                std::bind(&step, std::ref(display_callback), std::placeholders::_1)
                );

        for (Set<QualifiedPackageName>::ConstIterator p(matches->begin()), p_end(matches->end()) ;
                p != p_end ; ++p)
            show_args->push_back(stringify(*p));
    }

    if (show_args->empty())
        return EXIT_FAILURE;

    if (! cmdline.search_options.a_all_versions.specified())
        show_args->push_back("--one-version");

    show_args->push_back("--significant-keys-only");
    for (args::StringSetArg::ConstIterator k(cmdline.match_options.a_key.begin_args()), k_end(cmdline.match_options.a_key.end_args()) ;
            k != k_end ; ++k)
    {
        show_args->push_back("--key");
        show_args->push_back(*k);
    }

    /* also in cmd_match.cc */
    bool default_names_and_descriptions((! cmdline.match_options.a_name.specified()) &&
            (! cmdline.match_options.a_description.specified()) && (! cmdline.match_options.a_key.specified()));
    if (default_names_and_descriptions || cmdline.match_options.a_description.specified())
        show_args->push_back("--description-keys");

    ShowCommand show_command;
    return show_command.run(env, show_args) | retcode;
}

std::shared_ptr<args::ArgsHandler>
SearchCommand::make_doc_cmdline()
{
    return std::make_shared<SearchCommandLine>();
}

CommandImportance
SearchCommand::importance() const
{
    return ci_core;
}