Skip to content

Commit

Permalink
cmd/dist: simplify exec.Cmd helpers for Go 1.19
Browse files Browse the repository at this point in the history
When running on Go 1.19, we can further simplify some of the exec.Cmd
helpers due to API improvements. There's not much point in doing this
while the bootstrap is still 1.17, but this will queue up this
simplification in an obvious way for when we next upgrade the
bootstrap toolchain (#54265).

Updates #44505.

Change-Id: I2ebc3d5c584375ec862a1d48138ab134bd9b2366
Reviewed-on: https://go-review.googlesource.com/c/go/+/427958
Reviewed-by: Bryan Mills <[email protected]>
TryBot-Result: Gopher Robot <[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 d9f90df commit 5abf200
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/cmd/dist/exec.go → src/cmd/dist/exec_118.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

//go:build !go1.19

package main

import (
Expand Down
42 changes: 42 additions & 0 deletions src/cmd/dist/exec_119.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

//go:build go1.19

package main

import (
"os/exec"
"strings"
)

// setDir sets cmd.Dir to dir, and also adds PWD=dir to cmd's environment.
func setDir(cmd *exec.Cmd, dir string) {
cmd.Dir = dir
if cmd.Env != nil {
// os/exec won't set PWD automatically.
setEnv(cmd, "PWD", dir)
}
}

// setEnv sets cmd.Env so that key = value.
func setEnv(cmd *exec.Cmd, key, value string) {
cmd.Env = append(cmd.Environ(), key+"="+value)
}

// unsetEnv sets cmd.Env so that key is not present in the environment.
func unsetEnv(cmd *exec.Cmd, key string) {
cmd.Env = cmd.Environ()

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

0 comments on commit 5abf200

Please sign in to comment.