Skip to content

Commit 5abf200

Browse files
committed
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>
1 parent d9f90df commit 5abf200

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

src/cmd/dist/exec.go renamed to src/cmd/dist/exec_118.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
// Use of this source code is governed by a BSD-style
33
// license that can be found in the LICENSE file.
44

5+
//go:build !go1.19
6+
57
package main
68

79
import (

src/cmd/dist/exec_119.go

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// Copyright 2022 The Go Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
5+
//go:build go1.19
6+
7+
package main
8+
9+
import (
10+
"os/exec"
11+
"strings"
12+
)
13+
14+
// setDir sets cmd.Dir to dir, and also adds PWD=dir to cmd's environment.
15+
func setDir(cmd *exec.Cmd, dir string) {
16+
cmd.Dir = dir
17+
if cmd.Env != nil {
18+
// os/exec won't set PWD automatically.
19+
setEnv(cmd, "PWD", dir)
20+
}
21+
}
22+
23+
// setEnv sets cmd.Env so that key = value.
24+
func setEnv(cmd *exec.Cmd, key, value string) {
25+
cmd.Env = append(cmd.Environ(), key+"="+value)
26+
}
27+
28+
// unsetEnv sets cmd.Env so that key is not present in the environment.
29+
func unsetEnv(cmd *exec.Cmd, key string) {
30+
cmd.Env = cmd.Environ()
31+
32+
prefix := key + "="
33+
newEnv := []string{}
34+
for _, entry := range cmd.Env {
35+
if strings.HasPrefix(entry, prefix) {
36+
continue
37+
}
38+
newEnv = append(newEnv, entry)
39+
// key may appear multiple times, so keep going.
40+
}
41+
cmd.Env = newEnv
42+
}

0 commit comments

Comments
 (0)