cmd/dist: simplify exec.Cmd helpers for Go 1.19

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 <bcmills@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Austin Clements <austin@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
This commit is contained in:
Austin Clements 2022-08-29 17:30:12 -04:00
parent d9f90df2b4
commit 5abf200d65
2 changed files with 44 additions and 0 deletions

View file

@ -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 (

42
src/cmd/dist/exec_119.go vendored Normal file
View file

@ -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
}