-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.go
76 lines (67 loc) · 1.8 KB
/
utils.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
package secret
import (
"fmt"
"strings"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/client"
"golang.org/x/net/context"
)
// GetSecretsByNameOrIDPrefixes returns secrets given a list of ids or names
func GetSecretsByNameOrIDPrefixes(ctx context.Context, client client.APIClient, terms []string) ([]swarm.Secret, error) {
args := filters.NewArgs()
for _, n := range terms {
args.Add("names", n)
args.Add("id", n)
}
return client.SecretList(ctx, types.SecretListOptions{
Filters: args,
})
}
func getCliRequestedSecretIDs(ctx context.Context, client client.APIClient, terms []string) ([]string, error) {
secrets, err := GetSecretsByNameOrIDPrefixes(ctx, client, terms)
if err != nil {
return nil, err
}
if len(secrets) > 0 {
found := make(map[string]struct{})
next:
for _, term := range terms {
// attempt to lookup secret by full ID
for _, s := range secrets {
if s.ID == term {
found[s.ID] = struct{}{}
continue next
}
}
// attempt to lookup secret by full name
for _, s := range secrets {
if s.Spec.Annotations.Name == term {
found[s.ID] = struct{}{}
continue next
}
}
// attempt to lookup secret by partial ID (prefix)
// return error if more than one matches found (ambiguous)
n := 0
for _, s := range secrets {
if strings.HasPrefix(s.ID, term) {
found[s.ID] = struct{}{}
n++
}
}
if n > 1 {
return nil, fmt.Errorf("secret %s is ambiguous (%d matches found)", term, n)
}
}
// We already collected all the IDs found.
// Now we will remove duplicates by converting the map to slice
ids := []string{}
for id := range found {
ids = append(ids, id)
}
return ids, nil
}
return terms, nil
}