Skip to content

Commit

Permalink
parsing env vars in scripts
Browse files Browse the repository at this point in the history
The code looks for env vars to start with '2729' instead of just a single '$' no matter
the operating system.
  • Loading branch information
zabawaba99 committed Oct 19, 2015
1 parent 7b0de42 commit 6d9d56f
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
12 changes: 11 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
15 changes: 15 additions & 0 deletions builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{
Expand All @@ -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()
Expand Down
14 changes: 14 additions & 0 deletions builder_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"os"
"testing"

"github.com/stretchr/testify/assert"
Expand All @@ -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)
Expand Down

0 comments on commit 6d9d56f

Please # to comment.