Skip to content

Commit

Permalink
cmd/dist: simplify exec.Cmd helpers
Browse files Browse the repository at this point in the history
Now that the required Go bootstrap version is 1.17, we can simplify
some of the logic for working with exec.Cmd.Env as those APIs have
been simplified.

Updates #44505.

Change-Id: Ia62ab9830320c7daf65a15f2313471dfaba687b5
Reviewed-on: https://go-review.googlesource.com/c/go/+/427957
TryBot-Result: Gopher Robot <[email protected]>
Reviewed-by: Bryan Mills <[email protected]>
Run-TryBot: Austin Clements <[email protected]>
Reviewed-by: Ian Lance Taylor <[email protected]>
  • Loading branch information
aclements committed Sep 16, 2022
1 parent 88b51d2 commit d9f90df
Showing 1 changed file with 6 additions and 15 deletions.
21 changes: 6 additions & 15 deletions src/cmd/dist/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,23 +17,11 @@ func setDir(cmd *exec.Cmd, dir string) {
}

// setEnv sets cmd.Env so that key = value.
//
// It first removes any existing values for key, so it is safe to call
// even from within cmdbootstrap.
func setEnv(cmd *exec.Cmd, key, value string) {
kv := key + "=" + value
if cmd.Env == nil {
cmd.Env = os.Environ()
}

prefix := kv[:len(key)+1]
for i, entry := range cmd.Env {
if strings.HasPrefix(entry, prefix) {
cmd.Env[i] = kv
return
}
}

cmd.Env = append(cmd.Env, kv)
}

Expand All @@ -44,10 +32,13 @@ func unsetEnv(cmd *exec.Cmd, key string) {
}

prefix := key + "="
for i, entry := range cmd.Env {
newEnv := []string{}
for _, entry := range cmd.Env {
if strings.HasPrefix(entry, prefix) {
cmd.Env = append(cmd.Env[:i], cmd.Env[i+1:]...)
return
continue
}
newEnv = append(newEnv, entry)
// key may appear multiple times, so keep going.
}
cmd.Env = newEnv
}

0 comments on commit d9f90df

Please sign in to comment.