From cd5cecfe896d84b661817d7a1d3ff9503fca958d Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Wed, 8 May 2013 20:37:07 -0700 Subject: [PATCH] app: support merging configs --- config.go | 27 +++++++++++++++++++++++++++ config_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/config.go b/config.go index 4899a3037..80579adb9 100644 --- a/config.go +++ b/config.go @@ -20,6 +20,33 @@ type config struct { Commands map[string]string } +// Merge the configurations. Anything in the "new" configuration takes +// precedence over the "old" configuration. +func mergeConfig(a, b *config) *config { + configs := []*config{a, b} + result := newConfig() + + for _, config := range configs { + for k, v := range config.Builders { + result.Builders[k] = v + } + + for k, v := range config.Commands { + result.Commands[k] = v + } + } + + return result +} + +// Creates and initializes a new config struct. +func newConfig() *config { + result := new(config) + result.Builders = make(map[string]string) + result.Commands = make(map[string]string) + return result +} + // Parses a configuration file and returns a proper configuration // struct. func parseConfig(data string) (result *config, err error) { diff --git a/config_test.go b/config_test.go index a9bf6cb82..53e0b9d4a 100644 --- a/config_test.go +++ b/config_test.go @@ -5,6 +5,31 @@ import ( "testing" ) +func TestConfig_MergeConfig(t *testing.T) { + assert := asserts.NewTestingAsserts(t, true) + + aString := ` + [commands] + a = "1" + b = "1" + ` + + bString := ` + [commands] + a = "1" + b = "2" + c = "3" + ` + + a, _ := parseConfig(aString) + b, _ := parseConfig(bString) + result := mergeConfig(a, b) + + assert.Equal(result.Commands["a"], "1", "a should be 1") + assert.Equal(result.Commands["b"], "2", "a should be 2") + assert.Equal(result.Commands["c"], "3", "a should be 3") +} + func TestConfig_ParseConfig_Bad(t *testing.T) { assert := asserts.NewTestingAsserts(t, true)