]> Cypherpunks repositories - gostls13.git/commitdiff
cmd/dist: simplify exec.Cmd helpers for Go 1.19
authorAustin Clements <austin@google.com>
Mon, 29 Aug 2022 21:30:12 +0000 (17:30 -0400)
committerAustin Clements <austin@google.com>
Fri, 16 Sep 2022 15:08:37 +0000 (15:08 +0000)
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>
src/cmd/dist/exec_118.go [moved from src/cmd/dist/exec.go with 97% similarity]
src/cmd/dist/exec_119.go [new file with mode: 0644]

similarity index 97%
rename from src/cmd/dist/exec.go
rename to src/cmd/dist/exec_118.go
index 43f503cb6c8b1f1d62acae7dd7f6646be118ae4d..8688f0a01f83c0de4b33b2be1a894c12f8d3e19c 100644 (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 (
diff --git a/src/cmd/dist/exec_119.go b/src/cmd/dist/exec_119.go
new file mode 100644 (file)
index 0000000..ed3a101
--- /dev/null
@@ -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
+}