Repository navigation
Expand file tree
/
Copy pathgroup.go
More file actions
356 lines (296 loc) · 9.38 KB
/
Copy pathgroup.go
File metadata and controls
356 lines (296 loc) · 9.38 KB
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
// Copyright 2016 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"os"
"sort"
"strings"
"github.com/olekukonko/tablewriter"
"v.io/x/lib/cmdline"
)
var cmdMadbGroup = &cmdline.Command{
Children: []*cmdline.Command{
cmdMadbGroupAdd,
cmdMadbGroupClearAll,
cmdMadbGroupDelete,
cmdMadbGroupList,
cmdMadbGroupRemove,
cmdMadbGroupRename,
},
Name: "group",
DontInheritFlags: true,
Short: "Manage device groups",
Long: `
Manages device groups, each of which can have one or more device members. The
device groups can be used for specifying the target devices of other madb
commands.
`,
}
var cmdMadbGroupAdd = &cmdline.Command{
Runner: subCommandRunnerWithFilepath{runMadbGroupAdd, getDefaultConfigFilePath},
Name: "add",
Short: "Add members to a device group",
Long: `
Adds members to a device group. This command also creates the group, if the
group does not exist yet. The device group can be used when specifying devices
in any madb commands.
When creating a new device group with this command, the provided name must not
conflict with an existing device nickname (see: madb help name set).
A group can contain another device group, in which case all the members of the
other group will also be considered as members of the current group.
`,
ArgsName: "<group_name> <member1> [<member2> ...]",
ArgsLong: `
<group_name> is an alpha-numeric string with no special characters or spaces.
This name must not be an existing device nickname.
<member> is a member specifier, which can be one of device serial, qualifier,
device index (e.g., '@1', '@2'), device nickname, or another device group.
`,
}
func runMadbGroupAdd(env *cmdline.Env, args []string, filename string) error {
// Check if the arguments are valid.
if len(args) < 2 {
return env.UsageErrorf("There must be at least two arguments.")
}
groupName := args[0]
if !isValidName(groupName) {
return fmt.Errorf("Not a valid group name: %q", groupName)
}
cfg, err := readConfig(filename)
if err != nil {
return err
}
if isDeviceNickname(groupName, cfg) {
return fmt.Errorf("The group name %q conflicts with a device nickname.", groupName)
}
members := removeDuplicates(args[1:])
for _, member := range members {
if err := isValidDeviceSpecifier(member); err != nil {
return fmt.Errorf("Invalid member %q: %v", member, err)
}
}
oldMembers, ok := cfg.Groups[groupName]
if !ok {
oldMembers = []string{}
}
cfg.Groups[groupName] = removeDuplicates(append(oldMembers, members...))
return writeConfig(cfg, filename)
}
var cmdMadbGroupClearAll = &cmdline.Command{
Runner: subCommandRunnerWithFilepath{runMadbGroupClearAll, getDefaultConfigFilePath},
Name: "clear-all",
Short: "Clear all the existing device groups",
Long: `
Clears all the existing device groups.
`,
}
func runMadbGroupClearAll(env *cmdline.Env, args []string, filename string) error {
cfg, err := readConfig(filename)
if err != nil {
return err
}
// Reset the groups
cfg.Groups = make(map[string][]string)
return writeConfig(cfg, filename)
}
var cmdMadbGroupDelete = &cmdline.Command{
Runner: subCommandRunnerWithFilepath{runMadbGroupDelete, getDefaultConfigFilePath},
Name: "delete",
Short: "Delete an existing device group",
Long: `
Deletes an existing device group.
`,
ArgsName: "<group_name1> [<group_name2> ...]",
ArgsLong: `
<group_name> the name of an existing device group.
You can specify more than one group names.
`,
}
func runMadbGroupDelete(env *cmdline.Env, args []string, filename string) error {
// Check if the arguments are valid.
if len(args) < 1 {
return env.UsageErrorf("There must be at least one argument.")
}
cfg, err := readConfig(filename)
if err != nil {
return err
}
for _, groupName := range args {
if !isGroupName(groupName, cfg) {
return fmt.Errorf("Not an existing group name: %q", groupName)
}
}
// Delete the groups
for _, groupName := range args {
delete(cfg.Groups, groupName)
}
return writeConfig(cfg, filename)
}
var cmdMadbGroupList = &cmdline.Command{
Runner: subCommandRunnerWithFilepath{runMadbGroupList, getDefaultConfigFilePath},
Name: "list",
Short: "List all the existing device groups",
Long: `
Lists the name and members of all the existing device groups.
`,
}
func runMadbGroupList(env *cmdline.Env, args []string, filename string) error {
cfg, err := readConfig(filename)
if err != nil {
return err
}
tw := tablewriter.NewWriter(os.Stdout)
tw.SetHeader([]string{"Group Name", "Members"})
tw.SetHeaderAlignment(tablewriter.ALIGN_LEFT)
tw.SetAutoFormatHeaders(false)
tw.SetAlignment(tablewriter.ALIGN_LEFT)
data := make([][]string, 0, len(cfg.Groups))
for group, members := range cfg.Groups {
data = append(data, []string{group, strings.Join(members, " ")})
}
sort.Sort(byFirstElement(data))
for _, row := range data {
tw.Append(row)
}
tw.Render()
return nil
}
var cmdMadbGroupRemove = &cmdline.Command{
Runner: subCommandRunnerWithFilepath{runMadbGroupRemove, getDefaultConfigFilePath},
Name: "remove",
Short: "Remove members from a device group",
Long: `
Removes members from an existing device group. If there are no remaining members
after that, the group gets deleted.
`,
ArgsName: "<group_name> <member1> [<member2> ...]",
ArgsLong: `
<group_name> is an alpha-numeric string with no special characters or spaces.
This name must be an existing device group name.
<member> is a member specifier, which can be one of device serial, qualifier,
device index (e.g., '@1', '@2'), device nickname, or another device group.
`,
}
func runMadbGroupRemove(env *cmdline.Env, args []string, filename string) error {
// Check if the arguments are valid.
if len(args) < 2 {
return env.UsageErrorf("There must be at least two arguments.")
}
groupName := args[0]
if !isValidName(groupName) {
return fmt.Errorf("Not a valid group name: %q", groupName)
}
cfg, err := readConfig(filename)
if err != nil {
return err
}
if !isGroupName(groupName, cfg) {
return fmt.Errorf("Not an existing group name: %q", groupName)
}
members := removeDuplicates(args[1:])
oldMembers := cfg.Groups[groupName]
cfg.Groups[groupName] = subtractSlices(oldMembers, members)
if len(cfg.Groups[groupName]) == 0 {
delete(cfg.Groups, groupName)
}
return writeConfig(cfg, filename)
}
var cmdMadbGroupRename = &cmdline.Command{
Runner: subCommandRunnerWithFilepath{runMadbGroupRename, getDefaultConfigFilePath},
Name: "rename",
Short: "Rename an existing device group",
Long: `
Renames an existing device group.
`,
ArgsName: "<old_name> <new_name>",
ArgsLong: `
<old_name> is the name of an existing device group.
<new_name> is the new name for the existing group.
This must be an alpha-numeric string with no special characters or spaces,
and must not conflict with another existing device or group name.
`,
}
func runMadbGroupRename(env *cmdline.Env, args []string, filename string) error {
// Check if the arguments are valid.
if len(args) != 2 {
return env.UsageErrorf("There must be exactly two arguments.")
}
oldName, newName := args[0], args[1]
if !isValidName(oldName) {
return fmt.Errorf("Not a valid group name: %q", oldName)
}
if !isValidName(newName) {
return fmt.Errorf("Not a valid group name: %q", newName)
}
cfg, err := readConfig(filename)
if err != nil {
return err
}
if !isGroupName(oldName, cfg) {
return fmt.Errorf("Not an existing group name: %q", oldName)
}
if isNameInUse(newName, cfg) {
return fmt.Errorf("The provided name is already in use: %q", newName)
}
cfg.Groups[newName] = cfg.Groups[oldName]
delete(cfg.Groups, oldName)
return writeConfig(cfg, filename)
}
// removeDuplicates takes a string slice and removes all the duplicates.
func removeDuplicates(s []string) []string {
result := make([]string, 0, len(s))
used := map[string]bool{}
for _, elem := range s {
if !used[elem] {
result = append(result, elem)
used[elem] = true
}
}
return result
}
// subtractSlices takes two slices and returns a new slice formed by removing
// all the elements in s2 from s1.
func subtractSlices(s1, s2 []string) []string {
result := make([]string, 0, len(s1))
m := map[string]bool{}
for _, e2 := range s2 {
m[e2] = true
}
for _, e1 := range s1 {
if !m[e1] {
result = append(result, e1)
}
}
return result
}
// expandGroups takes a slice of device specifier tokens and returns a new slice
// where all the group name tokens are expanded to include all their members.
// The expansion process is transitive; if a group includes other groups, all
// the members of the other groups are also included in the returned slice. Each
// group is processed at most once, in order to avoid infinite loops.
func expandGroups(tokens []string, cfg *config) []string {
expanded := make([]string, 0, len(tokens))
queue := make([]string, len(tokens))
copy(queue, tokens)
visitedGroups := make(map[string]bool)
for len(queue) > 0 {
// Pop a token from the queue
token := queue[0]
queue = queue[1:]
if isGroupName(token, cfg) {
// If this group was already processed before, ignore and proceed
// to the next token to avoid infinite loops.
if visitedGroups[token] {
continue
}
visitedGroups[token] = true
// Otherwise, expand the group and add all the members to the queue.
queue = append(queue, cfg.Groups[token]...)
} else {
expanded = append(expanded, token)
}
}
return expanded
}