diff --git a/README.md b/README.md index 12c2e15..d4dcd95 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ directory that you want to watch. Here is a sample of a `.snag.yml` file: -```yml +```yaml script: - echo "hello world" - go test @@ -86,6 +86,16 @@ option form the snag file if it is defined to false. **NOTE**: using the `-c` flag will skip reading a snag file even if it exists in the current working directory. +### Environment Variables + +You can access your shell's environment variables by using `$$`. + +```yaml +script: + - echo $$MY_VAR + - rm -rf $$OUTPUT_DIR +``` + ## Caveats * Endless build loops diff --git a/builder.go b/builder.go index 2cedf24..a3b109f 100644 --- a/builder.go +++ b/builder.go @@ -42,6 +42,11 @@ func NewBuilder(c config) (*Bob, error) { cmds := make([][]string, len(c.Script)) for i, s := range c.Script { cmds[i] = strings.Split(s, " ") + + // check for environment variables inside script + if strings.Contains(s, "$$") { + replaceEnv(cmds[i]) + } } return &Bob{ @@ -54,6 +59,16 @@ func NewBuilder(c config) (*Bob, error) { }, nil } +func replaceEnv(cmds []string) { + for i, c := range cmds { + if !strings.HasPrefix(c, "$$") { + continue + } + + cmds[i] = os.Getenv(strings.TrimPrefix(c, "$$")) + } +} + func (b *Bob) Close() error { close(b.done) return b.w.Close() diff --git a/builder_test.go b/builder_test.go index 74267da..71400ae 100644 --- a/builder_test.go +++ b/builder_test.go @@ -1,6 +1,7 @@ package main import ( + "os" "testing" "github.com/stretchr/testify/assert" @@ -13,6 +14,19 @@ func TestNewBuilder(t *testing.T) { assert.NotNil(t, b) } +func TestNewBuilder_EnvScript(t *testing.T) { + testEnv := "foobar" + os.Setenv("TEST_ENV", testEnv) + b, err := NewBuilder(config{ + Script: []string{"echo $$TEST_ENV"}, + }) + assert.NoError(t, err) + assert.NotNil(t, b) + + require.Len(t, b.cmds, 1) + assert.Equal(t, testEnv, b.cmds[0][1]) +} + func TestClose(t *testing.T) { b, err := NewBuilder(config{}) require.NoError(t, err)