github.com/openshift/moby-moby@v1.13.2-0.20170601211448-f5ec1e2936dc/cli/command/secret/utils.go (about) 1 package secret 2 3 import ( 4 "fmt" 5 "strings" 6 7 "github.com/docker/docker/api/types" 8 "github.com/docker/docker/api/types/filters" 9 "github.com/docker/docker/api/types/swarm" 10 "github.com/docker/docker/client" 11 "golang.org/x/net/context" 12 ) 13 14 // GetSecretsByNameOrIDPrefixes returns secrets given a list of ids or names 15 func GetSecretsByNameOrIDPrefixes(ctx context.Context, client client.APIClient, terms []string) ([]swarm.Secret, error) { 16 args := filters.NewArgs() 17 for _, n := range terms { 18 args.Add("names", n) 19 args.Add("id", n) 20 } 21 22 return client.SecretList(ctx, types.SecretListOptions{ 23 Filters: args, 24 }) 25 } 26 27 func getCliRequestedSecretIDs(ctx context.Context, client client.APIClient, terms []string) ([]string, error) { 28 secrets, err := GetSecretsByNameOrIDPrefixes(ctx, client, terms) 29 if err != nil { 30 return nil, err 31 } 32 33 if len(secrets) > 0 { 34 found := make(map[string]struct{}) 35 next: 36 for _, term := range terms { 37 // attempt to lookup secret by full ID 38 for _, s := range secrets { 39 if s.ID == term { 40 found[s.ID] = struct{}{} 41 continue next 42 } 43 } 44 // attempt to lookup secret by full name 45 for _, s := range secrets { 46 if s.Spec.Annotations.Name == term { 47 found[s.ID] = struct{}{} 48 continue next 49 } 50 } 51 // attempt to lookup secret by partial ID (prefix) 52 // return error if more than one matches found (ambiguous) 53 n := 0 54 for _, s := range secrets { 55 if strings.HasPrefix(s.ID, term) { 56 found[s.ID] = struct{}{} 57 n++ 58 } 59 } 60 if n > 1 { 61 return nil, fmt.Errorf("secret %s is ambiguous (%d matches found)", term, n) 62 } 63 } 64 65 // We already collected all the IDs found. 66 // Now we will remove duplicates by converting the map to slice 67 ids := []string{} 68 for id := range found { 69 ids = append(ids, id) 70 } 71 72 return ids, nil 73 } 74 75 return terms, nil 76 }