Skip to content

Commit

Permalink
cmd/testscript: allow -e flag to pass env value
Browse files Browse the repository at this point in the history
The -e flag for testscript currently allows the caller to specify that
environment variables are inherited from the current environment.

However this falls when the current environment does not have a value
set and you need to set a specific value. For example:

    GOBUILD=$(go env GOBUILD) testscript -e GOBUILD script.txt

Instead, allow -e to also specify a value:

    testscript -e GOBUILD=$(go env GOBUILD) script.txt

which feels more fluent/natural.
  • Loading branch information
myitcv committed Jan 19, 2021
1 parent 8b0b133 commit ce7213b
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 4 deletions.
2 changes: 1 addition & 1 deletion cmd/testscript/README.md
Expand Up @@ -3,7 +3,7 @@ The testscript command runs github.com/rogpeppe/go-internal/testscript scripts
in a fresh temporary work directory tree.
Usage:
testscript [-v] [-e VAR]... [-u] files...
testscript [-v] [-e VAR[=value]]... [-u] files...
The testscript command is designed to make it easy to create self-contained
reproductions of command sequences.
Expand Down
2 changes: 1 addition & 1 deletion cmd/testscript/help.go
Expand Up @@ -14,7 +14,7 @@ The testscript command runs github.com/rogpeppe/go-internal/testscript scripts
in a fresh temporary work directory tree.
Usage:
testscript [-v] [-e VAR]... [-u] files...
testscript [-v] [-e VAR[=value]]... [-u] files...
The testscript command is designed to make it easy to create self-contained
reproductions of command sequences.
Expand Down
14 changes: 12 additions & 2 deletions cmd/testscript/main.go
Expand Up @@ -273,11 +273,21 @@ func run(runDir, filename string, update bool, verbose bool, envVars []string) e
if len(envVars) > 0 {
addSetup(func(env *testscript.Env) error {
for _, v := range envVars {
if v == "WORK" {
varName := v
if i := strings.Index(v, "="); i >= 0 {
varName = v[:i]
} else {
v = fmt.Sprintf("%s=%s", v, os.Getenv(v))
}
switch varName {
case "":
// Nonense variable
continue
case "WORK":
// cannot override WORK
continue
}
env.Vars = append(env.Vars, v+"="+os.Getenv(v))
env.Vars = append(env.Vars, v)
}
return nil
})
Expand Down
19 changes: 19 additions & 0 deletions cmd/testscript/testdata/env_values.txt
@@ -0,0 +1,19 @@
# Test that passing env values, e.g. ENV1=val, works

unquote test.txt

env BLAH2=junk

testscript -e BLAH1=rubbish -e BLAH2 test.txt

-- test.txt --
>exec printf $BLAH1'\n'
>cmp stdout stdout1.txt
>
>exec printf $BLAH2'\n'
>cmp stdout stdout2.txt
>
>-- stdout1.txt --
>rubbish
>-- stdout2.txt --
>junk

0 comments on commit ce7213b

Please sign in to comment.