|
| 1 | +package content |
| 2 | + |
| 3 | +import ( |
| 4 | + "os" |
| 5 | + "os/user" |
| 6 | + "path/filepath" |
| 7 | +) |
| 8 | + |
| 9 | +// currentUser is a seam so tests can simulate a running UID with no passwd |
| 10 | +// entry (where user.Current() returns an error). |
| 11 | +var currentUser = user.Current |
| 12 | + |
| 13 | +// SetDefaultDockerConfig defaults the DOCKER_CONFIG environment variable to the |
| 14 | +// directory where `hauler login` (crane -> docker/cli) writes credentials, so |
| 15 | +// that go-containerregistry's authn.DefaultKeychain -- used to resolve registry |
| 16 | +// credentials during `hauler store copy registry://`, `add`, and `sync` -- can |
| 17 | +// find them even when $HOME is unset. |
| 18 | +// |
| 19 | +// It replicates docker/cli's config.Dir()/getHomeDir() resolution using only the |
| 20 | +// standard library (no docker/cli dependency): DOCKER_CONFIG if already set, |
| 21 | +// otherwise <home>/.docker, where home is os.UserHomeDir() ($HOME on Unix, |
| 22 | +// %USERPROFILE% on Windows) with an /etc/passwd fallback via os/user.Current() |
| 23 | +// when $HOME is empty -- exactly the passwd fallback `hauler login` uses. |
| 24 | +// |
| 25 | +// When no home directory can be resolved at all ($HOME empty AND |
| 26 | +// user.Current() fails or returns an empty HomeDir), this mirrors docker/cli's |
| 27 | +// own config.Dir(), which computes filepath.Join(getHomeDir(), ".docker"): with |
| 28 | +// getHomeDir() == "", that join collapses to the relative path ".docker". So |
| 29 | +// DOCKER_CONFIG is defaulted to the relative path ".docker" in that case too, |
| 30 | +// keeping `hauler login`'s (relative) write and the keychain's (relative) read |
| 31 | +// in agreement as long as both run from the same working directory. |
| 32 | +// |
| 33 | +// The only remaining no-op case is when DOCKER_CONFIG is already explicitly |
| 34 | +// set (an explicit value always wins). Setting DOCKER_CONFIG does not disable |
| 35 | +// DefaultKeychain's $REGISTRY_AUTH_FILE / Podman auth.json fallbacks: those |
| 36 | +// still apply when no config.json exists at the set path. |
| 37 | +// |
| 38 | +// Returns the directory it set and true, or "" and false if it made no change. |
| 39 | +func SetDefaultDockerConfig() (string, bool) { |
| 40 | + if os.Getenv("DOCKER_CONFIG") != "" { |
| 41 | + return "", false |
| 42 | + } |
| 43 | + |
| 44 | + home, err := os.UserHomeDir() |
| 45 | + if err != nil || home == "" { |
| 46 | + if u, uerr := currentUser(); uerr == nil { |
| 47 | + home = u.HomeDir |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + dir := filepath.Join(home, ".docker") |
| 52 | + os.Setenv("DOCKER_CONFIG", dir) |
| 53 | + return dir, true |
| 54 | +} |
0 commit comments