aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/getopt/small/completer.cpp
blob: 01169dc081591ee9ac3d734100e1456efce0fec2 (plain) (blame)
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
362
363
364
365
366
367
#include "completer.h"

#include "completion_generator.h"

#include <util/string/cast.h>
#include <util/generic/fwd.h>

using NLastGetopt::NEscaping::Q;
using NLastGetopt::NEscaping::QQ;
using NLastGetopt::NEscaping::C;
using NLastGetopt::NEscaping::CC;
using NLastGetopt::NEscaping::S;
using NLastGetopt::NEscaping::SS;
using NLastGetopt::NEscaping::B;
using NLastGetopt::NEscaping::BB;

namespace NLastGetopt::NComp {
#define L out.Line()
#define I auto Y_GENERATE_UNIQUE_ID(indent) = out.Indent()

    TCompleterManager::TCompleterManager(TStringBuf command)
        : Command_(command)
        , Id_(0)
    {
    }

    TStringBuf TCompleterManager::GetCompleterID(const ICompleter* completer) {
        return Queue_.emplace_back(TStringBuilder() << "_" << Command_ << "__completer_" << ++Id_, completer).first;
    }

    void TCompleterManager::GenerateZsh(TFormattedOutput& out) {
        while (!Queue_.empty()) {
            auto[name, completer] = Queue_.back();
            Queue_.pop_back();

            L << "(( $+functions[" << name << "] )) ||";
            L << name << "() {";
            {
                I;
                completer->GenerateZsh(out, *this);
            }
            L << "}";
            L;
        }
    }

    class TAlternativeCompleter: public ICompleter {
    public:
        TAlternativeCompleter(TVector<TAlternative>  alternatives)
            : Alternatives_(std::move(alternatives))
        {
        }

        void GenerateBash(TFormattedOutput& out) const override {
            for (auto& alternative: Alternatives_) {
                if (alternative.Completer != nullptr) {
                    alternative.Completer->GenerateBash(out);
                }
            }
        }

        TStringBuf GenerateZshAction(TCompleterManager& manager) const override {
            return manager.GetCompleterID(this);
        }

        void GenerateZsh(TFormattedOutput& out, TCompleterManager& manager) const override {
            // We should use '_alternative' here, but it doesn't process escape codes in group descriptions,
            // so we dispatch alternatives ourselves.

            L << "local expl action";

            size_t i = 0;
            for (auto& alternative: Alternatives_) {
                auto tag = "alt-" + ToString(++i);
                auto action = alternative.Completer ? alternative.Completer->GenerateZshAction(manager) : TStringBuf();

                L;

                if (action.empty()) {
                    L << "_message -e " << SS(tag) << " " << SS(alternative.Description);
                } else if (action.StartsWith("((") && action.EndsWith("))")) {
                    L << "action=" << action.substr(1, action.size() - 2);
                    L << "_describe -t " << SS(tag) << " " << SS(alternative.Description) << " action -M 'r:|[_-]=* r:|=*'";
                } else if (action.StartsWith("(") && action.EndsWith(")")) {
                    L << "action=" << action << "";
                    L << "_describe -t " << SS(tag) << " " << SS(alternative.Description) << " action -M 'r:|[_-]=* r:|=*'";
                } else if (action.StartsWith(' ')) {
                    L << action.substr(1);
                } else {
                    L << "_description " << SS(tag) << " expl " << SS(alternative.Description);
                    TStringBuf word, args;
                    action.Split(' ', word, args);
                    L << word << " \"${expl[@]}\" " << args;
                }
            }
        }

    private:
        TVector<TAlternative> Alternatives_;
    };

    ICompleterPtr Alternative(TVector<TAlternative> alternatives) {
        return MakeSimpleShared<TAlternativeCompleter>(std::move(alternatives));
    }

    class TSimpleCompleter: public ICompleter {
    public:
        TSimpleCompleter(TString bashCode, TString action)
            : BashCode(std::move(bashCode))
            , Action(std::move(action))
        {
        }

        void GenerateBash(TFormattedOutput& out) const override {
            if (BashCode) {
                L << BashCode;
            }
        }

        TStringBuf GenerateZshAction(TCompleterManager&) const override {
            return Action;
        }

        void GenerateZsh(TFormattedOutput&, TCompleterManager&) const override {
            Y_FAIL("unreachable");
        }

    private:
        TString BashCode;
        TString Action;
    };

    ICompleterPtr Choice(TVector<TChoice> choices) {
        auto bash = TStringBuilder() << "COMPREPLY+=( $(compgen -W '";
        TStringBuf sep = "";
        for (auto& choice : choices) {
            bash << sep << B(choice.Choice);
            sep = " ";
        }
        bash << "' -- ${cur}) )";

        auto action = TStringBuilder();
        action << "((";
        for (auto& choice: choices) {
            action << " " << SS(choice.Choice);
            if (choice.Description) {{
                action << ":" << SS(choice.Description);
            }}
        }
        action << "))";
        return MakeSimpleShared<TSimpleCompleter>(bash, action);
    }

    TString Compgen(TStringBuf flags) {
        return TStringBuilder() << "COMPREPLY+=( $(compgen " << flags << " -- ${cur}) )";
    }

    ICompleterPtr Default() {
        return MakeSimpleShared<TSimpleCompleter>("", "_default");
    }

    ICompleterPtr File(TString pattern) {
        if (pattern) {
            pattern = " -g " + SS(pattern);
        }
        return MakeSimpleShared<TSimpleCompleter>("", "_files" + pattern);
    }

    ICompleterPtr Directory() {
        return MakeSimpleShared<TSimpleCompleter>("", "_files -/");
    }

    ICompleterPtr Host() {
        return MakeSimpleShared<TSimpleCompleter>(Compgen("-A hostname"), "_hosts");
    }

    ICompleterPtr Pid() {
        return MakeSimpleShared<TSimpleCompleter>("", "_pids");
    }

    ICompleterPtr User() {
        return MakeSimpleShared<TSimpleCompleter>(Compgen("-A user"), "_users");
    }

    ICompleterPtr Group() {
        // For some reason, OSX freezes when trying to perform completion for groups.
        // You can try removing this ifdef and debugging it, but be prepared to force-shutdown your machine
        // (and possibly reinstall OSX if force-shutdown breaks anything).
#ifdef _darwin_
        return MakeSimpleShared<TSimpleCompleter>("", "");
#else
        return MakeSimpleShared<TSimpleCompleter>(Compgen("-A group"), "_groups");
#endif
    }

    ICompleterPtr Url() {
        return MakeSimpleShared<TSimpleCompleter>("", "_urls");
    }

    ICompleterPtr Tty() {
        return MakeSimpleShared<TSimpleCompleter>("", "_ttys");
    }

    ICompleterPtr NetInterface() {
        return MakeSimpleShared<TSimpleCompleter>("", "_net_interfaces");
    }

    ICompleterPtr TimeZone() {
        return MakeSimpleShared<TSimpleCompleter>("", "_time_zone");
    }

    ICompleterPtr Signal() {
        return MakeSimpleShared<TSimpleCompleter>(Compgen("-A signal"), "_signals");
    }

    ICompleterPtr Domain() {
        return MakeSimpleShared<TSimpleCompleter>("", "_domains");
    }

    namespace {
        TCustomCompleter* Head = nullptr;
        TStringBuf SpecialFlag = "---CUSTOM-COMPLETION---"; 
    }

    void TCustomCompleter::FireCustomCompleter(int argc, const char** argv) {
        if (!argc) {
            return;
        }

        for (int i = 1; i < argc - 4; ++i) {
            if (SpecialFlag == argv[i]) {
                auto name = TStringBuf(argv[i + 1]);
                auto curIdx = FromString<int>(argv[i + 2]);
                auto prefix = TStringBuf(argv[i + 3]);
                auto suffix = TStringBuf(argv[i + 4]);

                auto cur = TStringBuf();
                if (0 <= curIdx && curIdx < i) {
                    cur = TStringBuf(argv[curIdx]);
                }
                if (cur && !prefix && !suffix) {
                    prefix = cur;  // bash does not send prefix and suffix
                }

                auto head = Head;
                while (head) {
                    if (head->GetUniqueName() == name) {
                        head->GenerateCompletions(i, argv, curIdx, cur, prefix, suffix);
                    }
                    head = head->Next_;
                }

                exit(0);
            }
        }
    }

    void TCustomCompleter::RegisterCustomCompleter(TCustomCompleter* completer) noexcept {
        Y_VERIFY(completer);
        completer->Next_ = Head;
        Head = completer;
    }

    void TCustomCompleter::AddCompletion(TStringBuf completion) {
        Cout << completion << Endl;  // this was easy =)
        // TODO: support option descriptions and messages
    }

    void TMultipartCustomCompleter::GenerateCompletions(int argc, const char** argv, int curIdx, TStringBuf cur, TStringBuf prefix, TStringBuf suffix) {
        auto root = TStringBuf();
        if (prefix.Contains(Sep_)) {
            auto tmp = TStringBuf();
            prefix.RSplit(Sep_, root, tmp);
        }

        if (root) {
            Cout << root << Sep_ << Endl;
        } else {
            Cout << Endl;
        }

        Cout << Sep_ << Endl;

        GenerateCompletionParts(argc, argv, curIdx, cur, prefix, suffix, root);
    }

    class TLaunchSelf: public ICompleter {
    public:
        TLaunchSelf(TCustomCompleter* completer)
            : Completer_(completer)
        {
        }

        void GenerateBash(TFormattedOutput& out) const override {
            L << "IFS=$'\\n'";
            L << "COMPREPLY+=( $(compgen -W \"$(${words[@]} " << SpecialFlag << " " << Completer_->GetUniqueName() << " \"${cword}\" \"\" \"\" 2> /dev/null)\" -- ${cur}) )";
            L << "IFS=$' \\t\\n'";
        }

        TStringBuf GenerateZshAction(TCompleterManager& manager) const override {
            return manager.GetCompleterID(this);
        }

        void GenerateZsh(TFormattedOutput& out, TCompleterManager&) const override {
            L << "compadd ${@} ${expl[@]} -- \"${(@f)$(${words_orig[@]} " << SpecialFlag << " " << Completer_->GetUniqueName() << " \"${current_orig}\" \"${prefix_orig}\" \"${suffix_orig}\" 2> /dev/null)}\"";
        }

    private:
        TCustomCompleter* Completer_;
    };

    ICompleterPtr LaunchSelf(TCustomCompleter& completer) {
        return MakeSimpleShared<TLaunchSelf>(&completer);
    }

    class TLaunchSelfMultiPart: public ICompleter {
    public:
        TLaunchSelfMultiPart(TCustomCompleter* completer)
            : Completer_(completer)
        {
        }

        void GenerateBash(TFormattedOutput& out) const override {
            L << "IFS=$'\\n'";
            L << "items=( $(${words[@]} " << SpecialFlag << " " << Completer_->GetUniqueName() << " \"${cword}\" \"\" \"\" 2> /dev/null) )";
            L << "candidates=$(compgen -W \"${items[*]:1}\" -- \"$cur\")";
            L << "COMPREPLY+=( $candidates )";
            L << "[[ $candidates == *\"${items[1]}\" ]] && need_space=\"\"";
            L << "IFS=$' \\t\\n'";
        }

        TStringBuf GenerateZshAction(TCompleterManager& manager) const override {
            return manager.GetCompleterID(this);
        }

        void GenerateZsh(TFormattedOutput& out, TCompleterManager&) const override {
            L << "local items=( \"${(@f)$(${words_orig[@]} " << SpecialFlag << " " << Completer_->GetUniqueName() << " \"${current_orig}\" \"${prefix_orig}\" \"${suffix_orig}\" 2> /dev/null)}\" )";
            L;
            L << "local rempat=${items[1]}";
            L << "shift items";
            L;
            L << "local sep=${items[1]}";
            L << "shift items";
            L;
            L << "local files=( ${items:#*\"${sep}\"} )";
            L << "local filenames=( ${files#\"${rempat}\"} )";
            L << "local dirs=( ${(M)items:#*\"${sep}\"} )";
            L << "local dirnames=( ${dirs#\"${rempat}\"} )";
            L;
            L << "local need_suf";
            L << "compset -S \"${sep}*\" || need_suf=\"1\"";
            L;
            L << "compadd ${@} ${expl[@]} -d filenames -- ${(q)files}";
            L << "compadd ${@} ${expl[@]} ${need_suf:+-S\"${sep}\"} -q -d dirnames -- ${(q)dirs%\"${sep}\"}";
        }

    private:
        TCustomCompleter* Completer_;
    };

    ICompleterPtr LaunchSelfMultiPart(TCustomCompleter& completer) {
        return MakeSimpleShared<TLaunchSelfMultiPart>(&completer);
    }

#undef I
#undef L
}