Skip to content
Snippets Groups Projects
Forked from GitLab.org / gitlab-runner
10402 commits behind, 7 commits ahead of the upstream repository.
auth_config.go 2.63 KiB
package docker_helpers

import (
	"fmt"
	"io"
	"os"
	"os/user"
	"path"
	"strings"

	"github.com/docker/docker/pkg/homedir"
	"github.com/fsouza/go-dockerclient"
)

// DefaultDockerRegistry is the name of the index
const DefaultDockerRegistry = "docker.io"

// SplitDockerImageName breaks a reposName into an index name and remote name
func SplitDockerImageName(reposName string) (string, string) {
	nameParts := strings.SplitN(reposName, "/", 2)
	var indexName, remoteName string
	if len(nameParts) == 1 || (!strings.Contains(nameParts[0], ".") &&
		!strings.Contains(nameParts[0], ":") && nameParts[0] != "localhost") {
		// This is a Docker Index repos (ex: samalba/hipache or ubuntu)
		// 'docker.io'
		indexName = DefaultDockerRegistry
		remoteName = reposName
	} else {
		indexName = nameParts[0]
		remoteName = nameParts[1]
	}

	if indexName == "index."+DefaultDockerRegistry {
		indexName = DefaultDockerRegistry
	}
	return indexName, remoteName
}

var HomeDirectory = homedir.Get()

func ReadDockerAuthConfigsFromHomeDir(userName string) (_ *docker.AuthConfigurations, err error) {
	var r io.ReadCloser

	homeDir := HomeDirectory
	if userName != "" {
		u, err := user.Lookup(userName)
		if err != nil {
			return nil, err
		}
		homeDir = u.HomeDir
	}
	if homeDir == "" {
		err = fmt.Errorf("Failed to get home directory")
		return
	}

	p := path.Join(homeDir, ".docker", "config.json")
	r, err = os.Open(p)
	if err != nil {
		p := path.Join(homeDir, ".dockercfg")
		r, err = os.Open(p)
		if os.IsNotExist(err) {
			// Ignore does not exist errors
			err = nil
		}
		if err != nil {
			return nil, err
		}
	}
	if r != nil {