This repository has been archived by the owner on Oct 28, 2022. It is now read-only.
/
config.go
73 lines (54 loc) · 1.6 KB
/
config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package docker
import (
"encoding/base64"
"encoding/json"
"github.com/pkg/errors"
"io"
"io/ioutil"
"strings"
)
type DockerConfig struct {
Auths Auths `json:"auths"`
HttpHeaders map[string]string `json:"HttpHeaders,omitempty"`
}
type Auths map[string]RegistryEntry
type RegistryEntry struct {
Email string `json:"email,omitempty"`
Auth string `json:"auth,omitempty"`
}
type Credentials struct {
User string
Password string
}
func ReadConfig(reader io.Reader) (*DockerConfig, error) {
var cfg *DockerConfig
content, err := ioutil.ReadAll(reader)
if err != nil {
return nil, err
}
if err = json.Unmarshal(content, &cfg); err != nil {
return nil, errors.Wrap(err, "Failed to unmarshal Docker config json")
}
if len(cfg.Auths) > 0 {
return cfg, nil
}
if err := json.Unmarshal(content, &cfg.Auths); err != nil {
return nil, errors.Wrap(err, "Failed to unmarshal Docker config using older json format")
}
return cfg, nil
}
func (cfg DockerConfig) GetCredentials(address string) (*Credentials, error) {
regEntry, ok := cfg.Auths[address]
if !ok || regEntry.Auth == "" {
return nil, nil
}
auth, err := base64.StdEncoding.DecodeString(regEntry.Auth)
if err != nil {
return nil, errors.Wrapf(err, "Failed to base64 decode credentials from Docker config for server %s", address)
}
creds := strings.Split(string(auth), ":")
if len(creds) != 2 {
return nil, errors.Errorf("Failed to extract username and password from Docker config for server %s", address)
}
return &Credentials{User: strings.TrimSpace(creds[0]), Password: strings.TrimSpace(creds[1])}, nil
}