github.com/antevens/oras@v0.8.1/pkg/auth/docker/client.go (about)

     1  package docker
     2  
     3  import (
     4  	"os"
     5  
     6  	"github.com/deislabs/oras/pkg/auth"
     7  
     8  	"github.com/docker/cli/cli/config"
     9  	"github.com/docker/cli/cli/config/configfile"
    10  	"github.com/docker/cli/cli/config/credentials"
    11  	"github.com/pkg/errors"
    12  )
    13  
    14  // Client provides authentication operations for docker registries.
    15  type Client struct {
    16  	configs []*configfile.ConfigFile
    17  }
    18  
    19  // NewClient creates a new auth client based on provided config paths.
    20  // If config path is not provided, the default path is used.
    21  // Credentials are read from the first config and fall backs to next.
    22  // All changes will only be written to the first config file.
    23  func NewClient(configPaths ...string) (auth.Client, error) {
    24  	var configs []*configfile.ConfigFile
    25  	for _, path := range configPaths {
    26  		cfg, err := loadConfigFile(path)
    27  		if err != nil {
    28  			return nil, errors.Wrap(err, path)
    29  		}
    30  		configs = append(configs, cfg)
    31  	}
    32  	if len(configs) == 0 {
    33  		cfg, err := config.Load(config.Dir())
    34  		if err != nil {
    35  			return nil, err
    36  		}
    37  		if !cfg.ContainsAuth() {
    38  			cfg.CredentialsStore = credentials.DetectDefaultStore(cfg.CredentialsStore)
    39  		}
    40  		configs = []*configfile.ConfigFile{cfg}
    41  	}
    42  
    43  	return &Client{
    44  		configs: configs,
    45  	}, nil
    46  }
    47  
    48  func (c *Client) primaryCredentialsStore(hostname string) credentials.Store {
    49  	return c.configs[0].GetCredentialsStore(hostname)
    50  }
    51  
    52  // loadConfigFile reads the configuration files from the given path.
    53  func loadConfigFile(path string) (*configfile.ConfigFile, error) {
    54  	cfg := configfile.New(path)
    55  	if _, err := os.Stat(path); err == nil {
    56  		file, err := os.Open(path)
    57  		if err != nil {
    58  			return nil, err
    59  		}
    60  		defer file.Close()
    61  		if err := cfg.LoadFromReader(file); err != nil {
    62  			return nil, err
    63  		}
    64  	} else if !os.IsNotExist(err) {
    65  		return nil, err
    66  	}
    67  	if !cfg.ContainsAuth() {
    68  		cfg.CredentialsStore = credentials.DetectDefaultStore(cfg.CredentialsStore)
    69  	}
    70  	return cfg, nil
    71  }