-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
action.go
207 lines (184 loc) · 5.12 KB
/
action.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
package spec
import (
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/carapace-sh/carapace"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"gopkg.in/yaml.v3"
)
type (
// static or dynamic value (macro)
value string
action []value
)
func NewAction(s []string) action { // TODO rename
a := make(action, len(s))
for index, v := range s {
a[index] = value(v)
}
return a
}
func executable() string {
s, err := os.Executable()
if err != nil {
panic(err.Error()) // TODO handle error, eval symlink, how to handle "go test"
}
return filepath.Base(s)
}
// ActionMacro completes given macro
func ActionMacro(s string, a ...any) carapace.Action {
return carapace.ActionCallback(func(c carapace.Context) carapace.Action {
if len(a) > 0 {
s = fmt.Sprintf(s, a...)
}
r := regexp.MustCompile(`^\$(?P<macro>[^(]*)(\((?P<arg>.*)\))?$`)
matches := r.FindStringSubmatch(s)
if matches == nil {
return carapace.ActionMessage("malformed macro: %#v", s)
}
if strings.HasPrefix(matches[1], "_") && !strings.HasPrefix(matches[1], "_.") {
return carapace.ActionMessage(`"$_" deprecated: replace %#v with %#v`, "$"+matches[1], "$carapace."+strings.TrimPrefix(matches[1], "_"))
}
prefix := fmt.Sprintf("$%v.", executable())
switch {
case !strings.HasPrefix(matches[1], "_.") && strings.Contains(matches[1], ".") && !strings.HasPrefix(s, prefix):
splitted := strings.SplitN(strings.TrimPrefix(s, "$"), ".", 2)
args := []string{"_carapace", "macro"}
args = append(args, splitted[1])
args = append(args, c.Args...)
args = append(args, c.Value)
carapace.LOG.Printf("%#v", args)
return carapace.ActionExecCommand(splitted[0], args...)(func(output []byte) carapace.Action {
return carapace.ActionImport(output)
})
default:
if strings.HasPrefix(s, prefix) {
s = "$_." + strings.TrimPrefix(s, prefix)
}
m, err := macros.Lookup(s)
if err != nil {
return carapace.ActionMessage(err.Error())
}
return m.Parse(s)
}
})
}
// ActionSpec completes a spec
func ActionSpec(path string) carapace.Action {
return carapace.ActionCallback(func(c carapace.Context) carapace.Action {
abs, err := c.Abs(path)
if err != nil {
return carapace.ActionMessage(err.Error())
}
content, err := os.ReadFile(abs)
if err != nil {
return carapace.ActionMessage(err.Error())
}
var cmd Command
if err := yaml.Unmarshal(content, &cmd); err != nil {
return carapace.ActionMessage(err.Error())
}
cmdCobra, err := cmd.ToCobraE()
if err != nil {
return carapace.ActionMessage(err.Error())
}
return carapace.ActionExecute(cmdCobra)
})
}
// TODO experimentally public
func (a action) Parse(cmd *cobra.Command) carapace.Action {
return carapace.ActionCallback(func(c carapace.Context) carapace.Action {
// TODO yuck - where to set thes best?
for index, arg := range c.Args {
c.Setenv(fmt.Sprintf("C_ARG%v", index), arg)
}
c.Setenv("C_VALUE", c.Value)
cmd.Flags().VisitAll(func(f *pflag.Flag) { // VisitAll as Visit() skips changed persistent flags of parent commands
if f.Changed {
c.Setenv(fmt.Sprintf("C_FLAG_%v", strings.ToUpper(f.Name)), f.Value.String())
}
})
batch := carapace.Batch()
batchAction := carapace.ActionCallback(func(c carapace.Context) carapace.Action {
return batch.ToA()
})
for _, elem := range a {
elemSubst, err := c.Envsubst(string(elem))
if err != nil {
batch = append(batch, carapace.ActionMessage("%v: %#v", err.Error(), elem))
continue
}
splitted := strings.Split(elemSubst, " ||| ")
if strings.HasPrefix(splitted[0], "$") { // macro
switch strings.SplitN(splitted[0], "(", 2)[0] {
case // generic modifier applied to batch
"$chdir",
"$filter",
"$filterargs",
"$list",
"$multiparts",
"$nospace",
"$prefix",
"$retain",
"$shift",
"$split",
"$splitp",
"$suffix",
"$suppress",
"$style",
"$tag",
"$uniquelist",
"$usage":
batchAction = modifier{batchAction}.Parse(splitted[0])
if len(splitted) > 1 {
for _, m := range splitted[1:] {
batchAction = modifier{batchAction}.Parse(m)
}
}
default:
a := ActionMacro(splitted[0])
if len(splitted) > 1 {
for _, m := range splitted[1:] {
a = modifier{a}.Parse(m)
}
}
batch = append(batch, a)
}
} else {
a := parseValue(splitted[0])
if len(splitted) > 1 {
for _, m := range splitted[1:] {
a = modifier{a}.Parse(m)
}
}
batch = append(batch, a)
}
}
return batchAction.Invoke(c).ToA()
})
}
func parseValue(s string) carapace.Action {
splitted := strings.SplitN(s, "\t", 3)
switch len(splitted) {
case 1:
return carapace.ActionValues(splitted...)
case 2:
return carapace.ActionValuesDescribed(splitted...)
case 3:
return carapace.ActionStyledValuesDescribed(splitted...)
default:
return carapace.ActionValues("invalid value: %#v", s)
}
}
func findNamedMatches(regex *regexp.Regexp, str string) map[string]string {
match := regex.FindStringSubmatch(str)
results := map[string]string{}
for i, name := range match {
results[regex.SubexpNames()[i]] = name
}
return results
}