diff --git a/cmd/cmd.go b/cmd/cmd.go index ab0019c..e1ec34d 100644 --- a/cmd/cmd.go +++ b/cmd/cmd.go @@ -1,6 +1,7 @@ package main import ( + "bytes" "encoding/json" "flag" "fmt" @@ -94,10 +95,10 @@ func readConf() { } if node, ok := root["driver"].(string); ok { - driver = node + driver = subEnvVars(node) } if node, ok := root["source"].(string); ok { - source = node + source = subEnvVars(node) } } @@ -300,3 +301,51 @@ func copyFile(dst, src string) (int64, error) { defer df.Close() return io.Copy(df, sf) } + + +const ( + WAITING_FOR_START = 0 + WAITING_FOR_MUSTACHE = 1 + WAITING_FOR_END = 2 +) +func subEnvVars(in string) string { + state := WAITING_FOR_START + var collected *bytes.Buffer + + result := new(bytes.Buffer) + + for _, c := range in { + switch state { + + case WAITING_FOR_START: + switch c { + case '$': + state = WAITING_FOR_MUSTACHE + default: + result.WriteRune(c) + } + + case WAITING_FOR_MUSTACHE: + switch c { + case '{': + collected = new(bytes.Buffer) + state = WAITING_FOR_END + default: + result.WriteRune('$') + result.WriteRune(c) + state = WAITING_FOR_START + } + + case WAITING_FOR_END: + switch c { + case '}': + v := strings.ToUpper(collected.String()) + result.WriteString(os.Getenv(v)) + state = WAITING_FOR_START + default: + collected.WriteRune(c) + } + } + } + return result.String() +} \ No newline at end of file diff --git a/cmd/cmd_test.go b/cmd/cmd_test.go new file mode 100644 index 0000000..24fb471 --- /dev/null +++ b/cmd/cmd_test.go @@ -0,0 +1,27 @@ +package main + +import ( + "os" + "testing" +) + +func TestEnvVarReplacement(t *testing.T) { + if os.Setenv("FOO", "yakshaving") != nil { + t.Fatalf("can't set environment var for test (foo)") + } + if os.Setenv("BAR", "fleazil") != nil { + t.Fatalf("can't set environment var for test (bar)") + } + if subEnvVars("${foo}") != "yakshaving" { + t.Errorf("failed simple variable substitution") + } + if subEnvVars("${foo}x${bar}") != "yakshavingxfleazil" { + t.Errorf("failed variable substitution combined with concat test") + } + if subEnvVars("$$x${bar}") != "$$xfleazil" { + t.Errorf("failed variable substitution combined with concat test") + } + if subEnvVars("{$}x${bar}$foo") != "{$}xfleazil$foo" { + t.Errorf("failed variable substitution combined with concat test") + } +} \ No newline at end of file diff --git a/dialects_test.go b/dialects_test.go index eafe357..4bab1f0 100644 --- a/dialects_test.go +++ b/dialects_test.go @@ -16,7 +16,7 @@ import ( import ( _ "github.com/lib/pq" - _ "github.com/ziutek/mymysql/godrv" + //"github.com/ziutek/mymysql/godrv" ) var toRun = []dialectInfo{ diff --git a/util.go b/util.go index 7a66e0e..1c8200a 100644 --- a/util.go +++ b/util.go @@ -57,3 +57,4 @@ func columnsMarkersAndValuesForModel(dialect Dialect, model *Model, markerPos *i } return columns, markers, values } +