command: load configuration

This commit is contained in:
Mitchell Hashimoto 2015-03-30 10:25:24 -07:00
parent cb09c95824
commit e3593d8bdc
5 changed files with 97 additions and 0 deletions

3
command/command_test.go Normal file
View File

@ -0,0 +1,3 @@
package command
const FixturePath = "./test-fixtures"

View File

@ -1,5 +1,23 @@
package command
import (
"fmt"
"io/ioutil"
"os"
"github.com/hashicorp/hcl"
"github.com/mitchellh/go-homedir"
)
const (
// DefaultConfigPath is the default path to the configuration file
DefaultConfigPath = "~/.vault"
// ConfigPathEnv is the environment variable that can be used to
// override where the Vault configuration is.
ConfigPathEnv = "VAULT_CONFIG_PATH"
)
// Config is the CLI configuration for Vault that can be specified via
// a `$HOME/.vault` file which is HCL-formatted (therefore HCL or JSON).
type Config struct {
@ -9,3 +27,37 @@ type Config struct {
// the token on disk unencrypted.
TokenHelper string `hcl:"token_helper"`
}
// LoadConfig reads the configuration from the given path. If path is
// empty, then the default path will be used, or the environment variable
// if set.
func LoadConfig(path string) (*Config, error) {
if path == "" {
path = DefaultConfigPath
}
if v := os.Getenv(ConfigPathEnv); v != "" {
path = v
}
path, err := homedir.Expand(path)
if err != nil {
return nil, fmt.Errorf("Error expanding config path: %s", err)
}
contents, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
obj, err := hcl.Parse(string(contents))
if err != nil {
return nil, err
}
var config Config
if err := hcl.DecodeObject(&config, obj); err != nil {
return nil, err
}
return &config, nil
}

21
command/config_test.go Normal file
View File

@ -0,0 +1,21 @@
package command
import (
"path/filepath"
"reflect"
"testing"
)
func TestLoadConfig(t *testing.T) {
config, err := LoadConfig(filepath.Join(FixturePath, "config.hcl"))
if err != nil {
t.Fatalf("err: %s", err)
}
expected := &Config{
TokenHelper: "foo",
}
if !reflect.DeepEqual(expected, config) {
t.Fatalf("bad: %#v", config)
}
}

View File

@ -37,6 +37,10 @@ type Meta struct {
flagCACert string
flagCAPath string
flagInsecure bool
// These are internal and shouldn't be modified or access by anyone
// except Meta.
config *Config
}
// Client returns the API client to a Vault server given the configured
@ -75,6 +79,22 @@ func (m *Meta) Client() (*api.Client, error) {
return api.NewClient(config)
}
// Config loads the configuration and returns it. If the configuration
// is already loaded, it is returned.
func (m *Meta) Config() (*Config, error) {
if m.config != nil {
return m.config, nil
}
var err error
m.config, err = LoadConfig("")
if err != nil {
return nil, err
}
return m.config, nil
}
// FlagSet returns a FlagSet with the common flags that every
// command implements. The exact behavior of FlagSet can be configured
// using the flags as the second parameter, for example to disable

View File

@ -0,0 +1 @@
token_helper = "foo"