github.com/makyo/juju@v0.0.0-20160425123129-2608902037e9/jujuclient/accounts.go (about)

     1  // Copyright 2016 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package jujuclient
     5  
     6  import (
     7  	"io/ioutil"
     8  	"os"
     9  
    10  	"github.com/juju/errors"
    11  	"github.com/juju/utils"
    12  	"gopkg.in/yaml.v2"
    13  
    14  	"github.com/juju/juju/juju/osenv"
    15  )
    16  
    17  // JujuAccountsPath is the location where accounts information is
    18  // expected to be found.
    19  func JujuAccountsPath() string {
    20  	return osenv.JujuXDGDataHomePath("accounts.yaml")
    21  }
    22  
    23  // ReadAccountsFile loads all accounts defined in a given file.
    24  // If the file is not found, it is not an error.
    25  func ReadAccountsFile(file string) (map[string]*ControllerAccounts, error) {
    26  	data, err := ioutil.ReadFile(file)
    27  	if err != nil {
    28  		if os.IsNotExist(err) {
    29  			return nil, nil
    30  		}
    31  		return nil, err
    32  	}
    33  	accounts, err := ParseAccounts(data)
    34  	if err != nil {
    35  		return nil, err
    36  	}
    37  	return accounts, nil
    38  }
    39  
    40  // WriteAccountsFile marshals to YAML details of the given accounts
    41  // and writes it to the accounts file.
    42  func WriteAccountsFile(controllerAccounts map[string]*ControllerAccounts) error {
    43  	data, err := yaml.Marshal(accountsCollection{controllerAccounts})
    44  	if err != nil {
    45  		return errors.Annotate(err, "cannot marshal accounts")
    46  	}
    47  	return utils.AtomicWriteFile(JujuAccountsPath(), data, os.FileMode(0600))
    48  }
    49  
    50  // ParseAccounts parses the given YAML bytes into accounts metadata.
    51  func ParseAccounts(data []byte) (map[string]*ControllerAccounts, error) {
    52  	var result accountsCollection
    53  	err := yaml.Unmarshal(data, &result)
    54  	if err != nil {
    55  		return nil, errors.Annotate(err, "cannot unmarshal accounts")
    56  	}
    57  	return result.ControllerAccounts, nil
    58  }
    59  
    60  type accountsCollection struct {
    61  	ControllerAccounts map[string]*ControllerAccounts `yaml:"controllers"`
    62  }
    63  
    64  // ControllerAccounts stores per-controller account information.
    65  type ControllerAccounts struct {
    66  	// Accounts is the collection of accounts for the controller.
    67  	Accounts map[string]AccountDetails `yaml:"accounts"`
    68  
    69  	// CurrentAccount is the name of the active account for the controller.
    70  	CurrentAccount string `yaml:"current-account,omitempty"`
    71  }