From 5d40725139768f844ae2d8a490cd910b13a89efb Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Sun, 25 May 2014 17:39:44 -0700 Subject: [PATCH] main: add main config --- config.go | 45 ++++++++++++++++++++++++++++++++++++++++++++ config_test.go | 28 +++++++++++++++++++++++++++ test-fixtures/config | 4 ++++ 3 files changed, 77 insertions(+) create mode 100644 config.go create mode 100644 config_test.go create mode 100644 test-fixtures/config diff --git a/config.go b/config.go new file mode 100644 index 000000000..a3764741f --- /dev/null +++ b/config.go @@ -0,0 +1,45 @@ +package main + +import ( + "github.com/mitchellh/go-libucl" +) + +// Config is the structure of the configuration for the Terraform CLI. +// +// This is not the configuration for Terraform itself. That is in the +// "config" package. +type Config struct { + Providers map[string]string +} + +// Put the parse flags we use for libucl in a constant so we can get +// equally behaving parsing everywhere. +const libuclParseFlags = libucl.ParserKeyLowercase + +// LoadConfig loads the CLI configuration from ".terraformrc" files. +func LoadConfig(path string) (*Config, error) { + var obj *libucl.Object + + // Parse the file and get the root object. + parser := libucl.NewParser(libuclParseFlags) + err := parser.AddFile(path) + if err == nil { + obj = parser.Object() + defer obj.Close() + } + defer parser.Close() + + // If there was an error parsing, return now. + if err != nil { + return nil, err + } + + // Build up the result + var result Config + + if err := obj.Decode(&result); err != nil { + return nil, err + } + + return &result, nil +} diff --git a/config_test.go b/config_test.go new file mode 100644 index 000000000..d27efc8d0 --- /dev/null +++ b/config_test.go @@ -0,0 +1,28 @@ +package main + +import ( + "path/filepath" + "reflect" + "testing" +) + +// This is the directory where our test fixtures are. +const fixtureDir = "./test-fixtures" + +func TestLoadConfig(t *testing.T) { + c, err := LoadConfig(filepath.Join(fixtureDir, "config")) + if err != nil { + t.Fatalf("err: %s", err) + } + + expected := &Config{ + Providers: map[string]string{ + "aws": "foo", + "do": "bar", + }, + } + + if !reflect.DeepEqual(c, expected) { + t.Fatalf("bad: %#v", c) + } +} diff --git a/test-fixtures/config b/test-fixtures/config new file mode 100644 index 000000000..bb597145d --- /dev/null +++ b/test-fixtures/config @@ -0,0 +1,4 @@ +providers { + "aws" = "foo" + "do" = "bar" +}