-
Notifications
You must be signed in to change notification settings - Fork 0
/
accounts.go
84 lines (74 loc) · 2.15 KB
/
accounts.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
74
75
76
77
78
79
80
81
82
83
84
// Copyright 2016 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package jujuclient
import (
"io/ioutil"
"os"
"strings"
"github.com/juju/errors"
"github.com/juju/utils"
"gopkg.in/juju/names.v2"
"gopkg.in/yaml.v2"
"github.com/juju/juju/juju/osenv"
)
// JujuAccountsPath is the location where accounts information is
// expected to be found.
func JujuAccountsPath() string {
return osenv.JujuXDGDataHomePath("accounts.yaml")
}
// ReadAccountsFile loads all accounts defined in a given file.
// If the file is not found, it is not an error.
func ReadAccountsFile(file string) (map[string]AccountDetails, error) {
data, err := ioutil.ReadFile(file)
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
accounts, err := ParseAccounts(data)
if err != nil {
return nil, err
}
if err := migrateLocalAccountUsers(accounts); err != nil {
return nil, err
}
return accounts, nil
}
func migrateLocalAccountUsers(accounts map[string]AccountDetails) error {
changes := false
for user, account := range accounts {
if !strings.HasSuffix(account.User, "@local") {
continue
}
tag := names.NewUserTag(account.User)
updated := account
updated.User = tag.Id()
accounts[user] = updated
changes = true
}
if changes {
return WriteAccountsFile(accounts)
}
return nil
}
// WriteAccountsFile marshals to YAML details of the given accounts
// and writes it to the accounts file.
func WriteAccountsFile(controllerAccounts map[string]AccountDetails) error {
data, err := yaml.Marshal(accountsCollection{controllerAccounts})
if err != nil {
return errors.Annotate(err, "cannot marshal accounts")
}
return utils.AtomicWriteFile(JujuAccountsPath(), data, os.FileMode(0600))
}
// ParseAccounts parses the given YAML bytes into accounts metadata.
func ParseAccounts(data []byte) (map[string]AccountDetails, error) {
var result accountsCollection
if err := yaml.Unmarshal(data, &result); err != nil {
return nil, errors.Annotate(err, "cannot unmarshal accounts")
}
return result.ControllerAccounts, nil
}
type accountsCollection struct {
ControllerAccounts map[string]AccountDetails `yaml:"controllers"`
}