-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathdefaultActions.go
455 lines (413 loc) · 13.8 KB
/
defaultActions.go
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
package carapace
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"strings"
"github.com/rsteube/carapace/internal/common"
"github.com/rsteube/carapace/internal/config"
"github.com/rsteube/carapace/internal/export"
"github.com/rsteube/carapace/internal/man"
"github.com/rsteube/carapace/pkg/style"
"github.com/rsteube/carapace/third_party/github.com/acarl005/stripansi"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
// ActionCallback invokes a go function during completion.
func ActionCallback(callback CompletionCallback) Action {
return Action{callback: callback}
}
// ActionExecCommand executes an external command.
//
// carapace.ActionExecCommand("git", "remote")(func(output []byte) carapace.Action {
// lines := strings.Split(string(output), "\n")
// return carapace.ActionValues(lines[:len(lines)-1]...)
// })
func ActionExecCommand(name string, arg ...string) func(f func(output []byte) Action) Action {
return func(f func(output []byte) Action) Action {
return ActionExecCommandE(name, arg...)(func(output []byte, err error) Action {
if err != nil {
if exitErr, ok := err.(*exec.ExitError); ok {
if firstLine := strings.SplitN(string(exitErr.Stderr), "\n", 2)[0]; strings.TrimSpace(firstLine) != "" {
err = errors.New(firstLine)
}
}
return ActionMessage(err.Error())
}
return f(output)
})
}
}
// ActionExecCommandE is like ActionExecCommand but with custom error handling.
//
// carapace.ActionExecCommandE("supervisorctl", "--configuration", path, "status")(func(output []byte, err error) carapace.Action {
// if err != nil {
// const NOT_RUNNING = 3
// if exitErr, ok := err.(*exec.ExitError); !ok || exitErr.ExitCode() != NOT_RUNNING {
// return carapace.ActionMessage(err.Error())
// }
// }
// return carapace.ActionValues("success")
// })
func ActionExecCommandE(name string, arg ...string) func(f func(output []byte, err error) Action) Action {
return func(f func(output []byte, err error) Action) Action {
return ActionCallback(func(c Context) Action {
var stdout, stderr bytes.Buffer
cmd := c.Command(name, arg...)
cmd.Stdout = &stdout
cmd.Stderr = &stderr
LOG.Printf("executing %#v", cmd.String())
if err := cmd.Run(); err != nil {
if exitErr, ok := err.(*exec.ExitError); ok {
exitErr.Stderr = stderr.Bytes() // seems this needs to be set manually due to stdout being collected?
}
return f(stdout.Bytes(), err)
}
return f(stdout.Bytes(), nil)
})
}
}
// ActionImport parses the json output from export as Action
//
// carapace.Gen(rootCmd).PositionalAnyCompletion(
// carapace.ActionCallback(func(c carapace.Context) carapace.Action {
// args := []string{"_carapace", "export", ""}
// args = append(args, c.Args...)
// args = append(args, c.Value)
// return carapace.ActionExecCommand("command", args...)(func(output []byte) carapace.Action {
// return carapace.ActionImport(output)
// })
// }),
// )
func ActionImport(output []byte) Action {
return ActionCallback(func(c Context) Action {
var e export.Export
if err := json.Unmarshal(output, &e); err != nil {
return ActionMessage(err.Error())
}
return Action{
rawValues: e.Values,
meta: e.Meta,
}
})
}
// ActionExecute executes completion on an internal command
// TODO example.
func ActionExecute(cmd *cobra.Command) Action {
return ActionCallback(func(c Context) Action {
args := []string{"_carapace", "export", cmd.Name()}
args = append(args, c.Args...)
args = append(args, c.Value)
cmd.SetArgs(args)
Gen(cmd).PreInvoke(func(cmd *cobra.Command, flag *pflag.Flag, action Action) Action {
return ActionCallback(func(_c Context) Action {
_c.Env = c.Env
_c.Dir = c.Dir
return action.Invoke(_c).ToA()
})
})
var stdout, stderr bytes.Buffer
cmd.SetOut(&stdout)
cmd.SetErr(&stderr)
if err := cmd.Execute(); err != nil {
return ActionMessage(err.Error())
}
return ActionImport(stdout.Bytes())
})
}
// ActionDirectories completes directories.
func ActionDirectories() Action {
return ActionCallback(func(c Context) Action {
return actionPath([]string{""}, true).Invoke(c).ToMultiPartsA("/").StyleF(style.ForPath)
}).Tag("directories")
}
// ActionFiles completes files with optional suffix filtering.
func ActionFiles(suffix ...string) Action {
return ActionCallback(func(c Context) Action {
return actionPath(suffix, false).Invoke(c).ToMultiPartsA("/").StyleF(style.ForPath)
}).Tag("files")
}
// ActionValues completes arbitrary keywords (values).
func ActionValues(values ...string) Action {
return ActionCallback(func(c Context) Action {
vals := make([]common.RawValue, 0, len(values))
for _, val := range values {
vals = append(vals, common.RawValue{Value: val, Display: val})
}
return Action{rawValues: vals}
})
}
// ActionStyledValues is like ActionValues but also accepts a style.
func ActionStyledValues(values ...string) Action {
return ActionCallback(func(c Context) Action {
if length := len(values); length%2 != 0 {
return ActionMessage("invalid amount of arguments [ActionStyledValues]: %v", length)
}
vals := make([]common.RawValue, 0, len(values)/2)
for i := 0; i < len(values); i += 2 {
vals = append(vals, common.RawValue{Value: values[i], Display: values[i], Style: values[i+1]})
}
return Action{rawValues: vals}
})
}
// ActionValuesDescribed completes arbitrary key (values) with an additional description (value, description pairs).
func ActionValuesDescribed(values ...string) Action {
return ActionCallback(func(c Context) Action {
if length := len(values); length%2 != 0 {
return ActionMessage("invalid amount of arguments [ActionValuesDescribed]: %v", length)
}
vals := make([]common.RawValue, 0, len(values)/2)
for i := 0; i < len(values); i += 2 {
vals = append(vals, common.RawValue{Value: values[i], Display: values[i], Description: values[i+1]})
}
return Action{rawValues: vals}
})
}
// ActionStyledValuesDescribed is like ActionValues but also accepts a style.
func ActionStyledValuesDescribed(values ...string) Action {
return ActionCallback(func(c Context) Action {
if length := len(values); length%3 != 0 {
return ActionMessage("invalid amount of arguments [ActionStyledValuesDescribed]: %v", length)
}
vals := make([]common.RawValue, 0, len(values)/3)
for i := 0; i < len(values); i += 3 {
vals = append(vals, common.RawValue{Value: values[i], Display: values[i], Description: values[i+1], Style: values[i+2]})
}
return Action{rawValues: vals}
})
}
// ActionMessage displays a help messages in places where no completions can be generated.
func ActionMessage(msg string, args ...interface{}) Action {
return ActionCallback(func(c Context) Action {
if len(args) > 0 {
msg = fmt.Sprintf(msg, args...)
}
a := ActionValues()
a.meta.Messages.Add(stripansi.Strip(msg))
return a
})
}
// ActionMultiParts completes multiple parts of words separately where each part is separated by some char (Context.Value is set to the currently completed part during invocation).
func ActionMultiParts(divider string, callback func(c Context) Action) Action {
return ActionCallback(func(c Context) Action {
index := strings.LastIndex(c.Value, string(divider))
prefix := ""
if len(divider) == 0 {
prefix = c.Value
c.Value = ""
} else if index != -1 {
prefix = c.Value[0 : index+len(divider)]
c.Value = c.Value[index+len(divider):] // update Context.Value to only contain the currently completed part
}
parts := strings.Split(prefix, string(divider))
if len(parts) > 0 && len(divider) > 0 {
parts = parts[0 : len(parts)-1]
}
c.Parts = parts
nospace := '*'
if runes := []rune(divider); len(runes) > 0 {
nospace = runes[len(runes)-1]
}
return callback(c).Invoke(c).Prefix(prefix).ToA().NoSpace(nospace)
})
}
// ActionStyleConfig completes style configuration
//
// carapace.Value=blue
// carapace.Description=magenta
func ActionStyleConfig() Action {
return ActionMultiParts("=", func(c Context) Action {
switch len(c.Parts) {
case 0:
return ActionMultiParts(".", func(c Context) Action {
switch len(c.Parts) {
case 0:
return ActionValues(config.GetStyleConfigs()...).Invoke(c).Suffix(".").ToA()
case 1:
fields, err := config.GetStyleFields(c.Parts[0])
if err != nil {
return ActionMessage(err.Error())
}
batch := Batch()
for _, field := range fields {
batch = append(batch, ActionStyledValuesDescribed(field.Name, field.Description, field.Style).Tag(field.Tag))
}
return batch.Invoke(c).Merge().Suffix("=").ToA()
default:
return ActionValues()
}
})
case 1:
return ActionMultiParts(",", func(c Context) Action {
return ActionStyles(c.Parts...).Invoke(c).Filter(c.Parts).ToA().NoSpace()
})
default:
return ActionValues()
}
})
}
// Actionstyles completes styles
//
// blue
// bg-magenta
func ActionStyles(styles ...string) Action {
return ActionCallback(func(c Context) Action {
fg := false
bg := false
for _, s := range styles {
if strings.HasPrefix(s, "bg-") {
bg = true
}
if s == style.Black ||
s == style.Red ||
s == style.Green ||
s == style.Yellow ||
s == style.Blue ||
s == style.Magenta ||
s == style.Cyan ||
s == style.White ||
s == style.BrightBlack ||
s == style.BrightRed ||
s == style.BrightGreen ||
s == style.BrightYellow ||
s == style.BrightBlue ||
s == style.BrightMagenta ||
s == style.BrightCyan ||
s == style.BrightWhite ||
strings.HasPrefix(s, "#") ||
strings.HasPrefix(s, "color") ||
strings.HasPrefix(s, "fg-") {
fg = true
}
}
batch := Batch()
_s := func(s string) string {
return style.Of(append(styles, s)...)
}
if !fg {
batch = append(batch, ActionStyledValues(
style.Black, _s(style.Black),
style.Red, _s(style.Red),
style.Green, _s(style.Green),
style.Yellow, _s(style.Yellow),
style.Blue, _s(style.Blue),
style.Magenta, _s(style.Magenta),
style.Cyan, _s(style.Cyan),
style.White, _s(style.White),
style.BrightBlack, _s(style.BrightBlack),
style.BrightRed, _s(style.BrightRed),
style.BrightGreen, _s(style.BrightGreen),
style.BrightYellow, _s(style.BrightYellow),
style.BrightBlue, _s(style.BrightBlue),
style.BrightMagenta, _s(style.BrightMagenta),
style.BrightCyan, _s(style.BrightCyan),
style.BrightWhite, _s(style.BrightWhite),
))
if strings.HasPrefix(c.Value, "color") {
for i := 0; i <= 255; i++ {
batch = append(batch, ActionStyledValues(
fmt.Sprintf("color%v", i), _s(style.XTerm256Color(uint8(i))),
))
}
} else {
batch = append(batch, ActionStyledValues("color", style.Of(styles...)))
}
}
if !bg {
batch = append(batch, ActionStyledValues(
style.BgBlack, _s(style.BgBlack),
style.BgRed, _s(style.BgRed),
style.BgGreen, _s(style.BgGreen),
style.BgYellow, _s(style.BgYellow),
style.BgBlue, _s(style.BgBlue),
style.BgMagenta, _s(style.BgMagenta),
style.BgCyan, _s(style.BgCyan),
style.BgWhite, _s(style.BgWhite),
style.BgBrightBlack, _s(style.BgBrightBlack),
style.BgBrightRed, _s(style.BgBrightRed),
style.BgBrightGreen, _s(style.BgBrightGreen),
style.BgBrightYellow, _s(style.BgBrightYellow),
style.BgBrightBlue, _s(style.BgBrightBlue),
style.BgBrightMagenta, _s(style.BgBrightMagenta),
style.BgBrightCyan, _s(style.BgBrightCyan),
style.BgBrightWhite, _s(style.BgBrightWhite),
))
if strings.HasPrefix(c.Value, "bg-color") {
for i := 0; i <= 255; i++ {
batch = append(batch, ActionStyledValues(
fmt.Sprintf("bg-color%v", i), _s("bg-"+style.XTerm256Color(uint8(i))),
))
}
} else {
batch = append(batch, ActionStyledValues("bg-color", style.Of(styles...)))
}
}
batch = append(batch, ActionStyledValues(
style.Bold, _s(style.Bold),
style.Dim, _s(style.Dim),
style.Italic, _s(style.Italic),
style.Underlined, _s(style.Underlined),
style.Blink, _s(style.Blink),
style.Inverse, _s(style.Inverse),
))
return batch.ToA().NoSpace('r')
}).Tag("styles")
}
// ActionExecutables completes PATH executables
//
// nvim
// chmod
func ActionExecutables() Action {
return ActionCallback(func(c Context) Action {
// TODO allow additional descriptions to be registered somewhere for carapace-bin (key, value,...)
batch := Batch()
manDescriptions := man.Descriptions(c.Value)
dirs := strings.Split(os.Getenv("PATH"), string(os.PathListSeparator))
for i := len(dirs) - 1; i >= 0; i-- {
batch = append(batch, actionDirectoryExecutables(dirs[i], c.Value, manDescriptions))
}
return batch.ToA()
}).Tag("executables")
}
func actionDirectoryExecutables(dir string, prefix string, manDescriptions map[string]string) Action {
return ActionCallback(func(c Context) Action {
if files, err := os.ReadDir(dir); err == nil {
vals := make([]string, 0)
for _, f := range files {
if strings.HasPrefix(f.Name(), prefix) {
if info, err := f.Info(); err == nil && !f.IsDir() && isExecAny(info.Mode()) {
vals = append(vals, f.Name(), manDescriptions[f.Name()], style.ForPath(dir+"/"+f.Name(), c))
}
}
}
return ActionStyledValuesDescribed(vals...)
}
return ActionValues()
})
}
func isExecAny(mode os.FileMode) bool {
return mode&0o111 != 0
}
// ActionPositional completes positional arguments for given command ignoring `--` (dash).
// TODO: experimental - likely gives issues with preinvoke (does not have the full args)
//
// carapace.Gen(cmd).DashAnyCompletion(
// carapace.ActionPositional(cmd),
// )
func ActionPositional(cmd *cobra.Command) Action {
return ActionCallback(func(c Context) Action {
if cmd.ArgsLenAtDash() < 0 {
return ActionMessage("only allowed for dash arguments [ActionPositional]")
}
c.Args = cmd.Flags().Args()
entry := storage.get(cmd)
a := entry.positionalAny
if index := len(c.Args); index < len(entry.positional) {
a = entry.positional[len(c.Args)]
}
return a.Invoke(c).ToA()
})
}