github.com/kaisenlinux/docker.io@v0.0.0-20230510090727-ea55db55fac7/swarmkit/cmd/swarmctl/secret/common.go (about)

     1  package secret
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	"github.com/docker/swarmkit/api"
     8  )
     9  
    10  func getSecret(ctx context.Context, c api.ControlClient, input string) (*api.Secret, error) {
    11  	// not sure what it is, match by name or id prefix
    12  	resp, err := c.ListSecrets(ctx,
    13  		&api.ListSecretsRequest{
    14  			Filters: &api.ListSecretsRequest_Filters{
    15  				Names:      []string{input},
    16  				IDPrefixes: []string{input},
    17  			},
    18  		},
    19  	)
    20  	if err != nil {
    21  		return nil, err
    22  	}
    23  
    24  	switch len(resp.Secrets) {
    25  	case 0:
    26  		return nil, fmt.Errorf("secret %s not found", input)
    27  	case 1:
    28  		return resp.Secrets[0], nil
    29  	default:
    30  		// ok, multiple matches.  Prefer exact ID over exact name.  If no exact matches, return an error
    31  		for _, s := range resp.Secrets {
    32  			if s.ID == input {
    33  				return s, nil
    34  			}
    35  		}
    36  		for _, s := range resp.Secrets {
    37  			if s.Spec.Annotations.Name == input {
    38  				return s, nil
    39  			}
    40  		}
    41  		return nil, fmt.Errorf("secret %s is ambiguous (%d matches found)", input, len(resp.Secrets))
    42  	}
    43  }