-
Notifications
You must be signed in to change notification settings - Fork 0
/
parseargs.go
299 lines (270 loc) · 9.57 KB
/
parseargs.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
/*
Copyright © 2022 ITRS Group
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package cmd
import (
"encoding/json"
"fmt"
"strings"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"github.com/itrs-group/cordial/tools/geneos/internal/geneos"
"github.com/itrs-group/cordial/tools/geneos/internal/instance"
)
// Annotation types for command behaviour
const (
AnnotationAliasFor = "aliasfor" // mapping alias
AnnotationComponent = "ct" // specific component name
AnnotationNames = "names" // json encoded array of instance names
AnnotationNeedsHome = "needshomedir" // "true" or "false"
AnnotationParams = "params" // json encoded array of parameters
AnnotationReplacedBy = "replacedby" // deprecated command alias
AnnotationWildcard = "wildcard" // "true", "false" or "explicit" (to match "all")
AnnotationExpand = "expand" // "true" or "false" - pass all names through a path.Match style lookup
)
// ParseArgs does the heavy lifting of sorting out non-flag command line
// ares for the various commands.
//
// given a list of args (after command has been seen), check if first
// arg is a component type and de-dup the names. A name of "all" will
// will override the rest and result in a lookup being done
//
// args with an '=' should be checked and only allowed if there are
// names?
//
// support glob style wildcards for instance names - allow through, let
// loopCommand* deal with them
//
// process command args in a standard way flags will have been handled
// by another function before this one any args with '=' are treated as
// parameters
//
// a bare argument with a '@' prefix means all instance of type on a
// host
func ParseArgs(command *cobra.Command, args []string) (err error) {
var wild bool
var ct *geneos.Component
var names, params []string
h := geneos.GetHost(Hostname)
if command.Annotations == nil {
command.Annotations = make(map[string]string)
}
annotations := command.Annotations
// args and params are JSON arrays, initialise
annotations[AnnotationNames] = "[]"
annotations[AnnotationParams] = "[]"
if len(args) == 0 && annotations[AnnotationWildcard] != "true" {
return nil
}
// shortcut - if the first non-component arg is "all" and the
// wildcard type is "explicit" then treat it as a wildcard, but only
// when given "all" as the first argument
if len(args) > 0 {
// first strip component if given and specified
if annotations[AnnotationComponent] == args[0] {
args = args[1:]
}
// now check first non component arg
if annotations[AnnotationWildcard] == "explicit" && args[0] == "all" {
annotations[AnnotationWildcard] = "true"
args = args[1:]
}
}
log.Debug().Msgf("rawargs: %s", args)
// filter in place - pull out all args containing '=' into params
// after rebuild this should only apply to 'import'
n := 0
for _, a := range args {
if strings.Contains(a, "=") {
params = append(params, a)
} else {
args[n] = a
n++
}
}
args = args[:n]
log.Debug().Msgf("rawargs %v, params %v, ct %s", args, params, annotations[AnnotationComponent])
jsonargs, _ := json.Marshal(params)
annotations[AnnotationParams] = string(jsonargs)
if annotations[AnnotationWildcard] != "true" {
if len(args) == 0 {
return nil
}
if ct = geneos.ParseComponent(args[0]); ct == nil {
jsonargs, _ := json.Marshal(args)
annotations[AnnotationNames] = string(jsonargs)
return
}
if annotations[AnnotationComponent] == "" {
annotations[AnnotationComponent] = args[0]
}
names = args[1:]
if annotations[AnnotationExpand] == "true" {
if newnames := instance.Match(h, ct, names...); len(newnames) > 0 {
names = newnames
}
}
} else {
defaultComponent := annotations[AnnotationComponent]
if defaultComponent == "" && len(args) > 0 {
defaultComponent = args[0]
}
if ct = geneos.ParseComponent(defaultComponent); ct == nil {
// first arg is not a known type, so treat the rest as instance names
names = args
if annotations[AnnotationExpand] == "true" {
log.Debug().Msgf("matching %v", names)
if newnames := instance.Match(h, ct, names...); len(newnames) > 0 {
names = newnames
}
}
} else {
if annotations[AnnotationComponent] == "" {
annotations[AnnotationComponent] = args[0]
names = args[1:]
} else {
names = args
}
if annotations[AnnotationExpand] == "true" {
if newnames := instance.Match(h, ct, names...); len(newnames) > 0 {
names = newnames
}
}
}
log.Debug().Msgf("args = %+v", names)
if len(names) == 0 || (len(names) == 1 && names[0] == "all") {
// no args also means all instances
wild = true
names = instance.Names(h, ct)
} else {
// expand each arg and save results to a new slice
// if local == "", then all instances on host (e.g. @host)
// if host == "all" (or none given), then check instance on all hosts
// @all is not valid - should be no arg
var nargs []string
for _, arg := range names {
// check if not valid first and leave unchanged, skip
if !(strings.HasPrefix(arg, "@") || instance.ValidName(arg)) {
log.Debug().Msgf("leaving unchanged: %s", arg)
nargs = append(nargs, arg)
continue
}
_, local, r := instance.SplitName(arg, h)
if !r.Exists() {
log.Debug().Msgf("%s - host not found", arg)
// we have tried to match something and it may result in an empty list
// so don't re-process
return fmt.Errorf("host %q not found", r)
}
log.Debug().Msgf("split %s into: %s %s", arg, local, r.String())
if local == "" {
// only a '@host' in arg
if r.Exists() {
rargs := instance.Names(r, ct)
nargs = append(nargs, rargs...)
wild = true
}
} else if r == geneos.ALL {
// no '@host' in arg
var matched bool
for _, rem := range geneos.AllHosts() {
wild = true
log.Debug().Msgf("checking host %s for %s", rem.String(), local)
name := local + "@" + rem.String()
for _, ct := range ct.OrList(geneos.RealComponents()...) {
if i, err := instance.Get(ct, name); err == nil && !i.Loaded().IsZero() {
nargs = append(nargs, name)
matched = true
}
}
}
if !matched && instance.ValidName(arg) {
// move the unknown unchanged - file or url - arg so it can later be pushed to params
// do not set 'wild' though?
log.Debug().Msgf("%s not found, saving to params", arg)
nargs = append(nargs, arg)
}
} else {
// save unchanged arg, may be param
nargs = append(nargs, arg)
// wild = true
}
}
names = nargs
}
}
log.Debug().Msgf("ct %s, args %v, params %v", ct, names, params)
m := make(map[string]bool, len(names))
var newnames []string
// traditional loop because we can't modify args in a loop to skip
for i := 0; i < len(names); i++ {
name := names[i]
// filter name here
if !wild && instance.ReservedName(name) {
log.Fatal().Msgf("%q is reserved name", name)
}
// move unknown args to params
if !instance.ValidName(name) {
params = append(params, name)
continue
}
// ignore duplicates (not params above)
if m[name] {
continue
}
newnames = append(newnames, name)
m[name] = true
}
names = newnames
jsonargs, _ = json.Marshal(names)
annotations[AnnotationNames] = string(jsonargs)
jsonparams, _ := json.Marshal(params)
annotations[AnnotationParams] = string(jsonparams)
if annotations[AnnotationWildcard] == "false" {
return
}
// if args is empty, find them all again. ct == None too?
if len(names) == 0 && (geneos.Root() != "" || len(geneos.RemoteHosts(false)) > 0) && !wild {
names = instance.Names(h, ct)
jsonargs, _ := json.Marshal(names)
annotations[AnnotationNames] = string(jsonargs)
}
log.Debug().Msgf("ct %s, args %v, params %v", ct, names, params)
return
}
// ParseTypeNames parses the ct, args and params set by ParseArgs in a
// Pre run and returns the ct and a slice of names. Parameters are
// ignored.
func ParseTypeNames(command *cobra.Command) (ct *geneos.Component, args []string) {
log.Debug().Msgf("%s %v", command.Annotations, ct)
ct = geneos.ParseComponent(command.Annotations[AnnotationComponent])
if err := json.Unmarshal([]byte(command.Annotations[AnnotationNames]), &args); err != nil {
log.Debug().Err(err).Msg("")
}
return
}
// ParseTypeNamesParams parses the ct, args and params set by ParseArgs
// in a Pre run and returns the ct and a slice of names and a slice of
// params.
func ParseTypeNamesParams(command *cobra.Command) (ct *geneos.Component, args, params []string) {
ct, args = ParseTypeNames(command)
if err := json.Unmarshal([]byte(command.Annotations[AnnotationParams]), ¶ms); err != nil {
log.Debug().Err(err).Msg("")
}
return
}