Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

parsing env vars in scripts #46

Merged
merged 1 commit into from
Oct 24, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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