github.1git.de/docker/cli@v26.1.3+incompatible/cli/command/registry/logout.go (about)

     1  package registry
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	"github.com/docker/cli/cli"
     8  	"github.com/docker/cli/cli/command"
     9  	"github.com/docker/docker/registry"
    10  	"github.com/spf13/cobra"
    11  )
    12  
    13  // NewLogoutCommand creates a new `docker logout` command
    14  func NewLogoutCommand(dockerCli command.Cli) *cobra.Command {
    15  	cmd := &cobra.Command{
    16  		Use:   "logout [SERVER]",
    17  		Short: "Log out from a registry",
    18  		Long:  "Log out from a registry.\nIf no server is specified, the default is defined by the daemon.",
    19  		Args:  cli.RequiresMaxArgs(1),
    20  		RunE: func(cmd *cobra.Command, args []string) error {
    21  			var serverAddress string
    22  			if len(args) > 0 {
    23  				serverAddress = args[0]
    24  			}
    25  			return runLogout(cmd.Context(), dockerCli, serverAddress)
    26  		},
    27  		Annotations: map[string]string{
    28  			"category-top": "9",
    29  		},
    30  		// TODO (thaJeztah) add completion for registries we have authentication stored for
    31  	}
    32  
    33  	return cmd
    34  }
    35  
    36  func runLogout(_ context.Context, dockerCli command.Cli, serverAddress string) error {
    37  	var isDefaultRegistry bool
    38  
    39  	if serverAddress == "" {
    40  		serverAddress = registry.IndexServer
    41  		isDefaultRegistry = true
    42  	}
    43  
    44  	var (
    45  		regsToLogout    = []string{serverAddress}
    46  		hostnameAddress = serverAddress
    47  	)
    48  	if !isDefaultRegistry {
    49  		hostnameAddress = registry.ConvertToHostname(serverAddress)
    50  		// the tries below are kept for backward compatibility where a user could have
    51  		// saved the registry in one of the following format.
    52  		regsToLogout = append(regsToLogout, hostnameAddress, "http://"+hostnameAddress, "https://"+hostnameAddress)
    53  	}
    54  
    55  	fmt.Fprintf(dockerCli.Out(), "Removing login credentials for %s\n", hostnameAddress)
    56  	errs := make(map[string]error)
    57  	for _, r := range regsToLogout {
    58  		if err := dockerCli.ConfigFile().GetCredentialsStore(r).Erase(r); err != nil {
    59  			errs[r] = err
    60  		}
    61  	}
    62  
    63  	// if at least one removal succeeded, report success. Otherwise report errors
    64  	if len(errs) == len(regsToLogout) {
    65  		fmt.Fprintln(dockerCli.Err(), "WARNING: could not erase credentials:")
    66  		for k, v := range errs {
    67  			fmt.Fprintf(dockerCli.Err(), "%s: %s\n", k, v)
    68  		}
    69  	}
    70  
    71  	return nil
    72  }