github.com/flavio/docker@v0.1.3-0.20170117145210-f63d1a6eec47/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 func getSecretsByNameOrIDPrefixes(ctx context.Context, client client.APIClient, terms []string) ([]swarm.Secret, error) { 15 args := filters.NewArgs() 16 for _, n := range terms { 17 args.Add("names", n) 18 args.Add("id", n) 19 } 20 21 return client.SecretList(ctx, types.SecretListOptions{ 22 Filters: args, 23 }) 24 } 25 26 func getCliRequestedSecretIDs(ctx context.Context, client client.APIClient, terms []string) ([]string, error) { 27 secrets, err := getSecretsByNameOrIDPrefixes(ctx, client, terms) 28 if err != nil { 29 return nil, err 30 } 31 32 if len(secrets) > 0 { 33 found := make(map[string]struct{}) 34 next: 35 for _, term := range terms { 36 // attempt to lookup secret by full ID 37 for _, s := range secrets { 38 if s.ID == term { 39 found[s.ID] = struct{}{} 40 continue next 41 } 42 } 43 // attempt to lookup secret by full name 44 for _, s := range secrets { 45 if s.Spec.Annotations.Name == term { 46 found[s.ID] = struct{}{} 47 continue next 48 } 49 } 50 // attempt to lookup secret by partial ID (prefix) 51 // return error if more than one matches found (ambiguous) 52 n := 0 53 for _, s := range secrets { 54 if strings.HasPrefix(s.ID, term) { 55 found[s.ID] = struct{}{} 56 n++ 57 } 58 } 59 if n > 1 { 60 return nil, fmt.Errorf("secret %s is ambiguous (%d matches found)", term, n) 61 } 62 } 63 64 // We already collected all the IDs found. 65 // Now we will remove duplicates by converting the map to slice 66 ids := []string{} 67 for id := range found { 68 ids = append(ids, id) 69 } 70 71 return ids, nil 72 } 73 74 return terms, nil 75 }