From 5abf200d6528a67032d67d3f50ffd7ce8b536dfa Mon Sep 17 00:00:00 2001 From: Austin Clements Date: Mon, 29 Aug 2022 17:30:12 -0400 Subject: [PATCH] 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 TryBot-Result: Gopher Robot Run-TryBot: Austin Clements Reviewed-by: Ian Lance Taylor --- src/cmd/dist/{exec.go => exec_118.go} | 2 ++ src/cmd/dist/exec_119.go | 42 +++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) rename src/cmd/dist/{exec.go => exec_118.go} (97%) create mode 100644 src/cmd/dist/exec_119.go diff --git a/src/cmd/dist/exec.go b/src/cmd/dist/exec_118.go similarity index 97% rename from src/cmd/dist/exec.go rename to src/cmd/dist/exec_118.go index 43f503cb6c8b1..8688f0a01f83c 100644 --- a/src/cmd/dist/exec.go +++ b/src/cmd/dist/exec_118.go @@ -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 index 0000000000000..ed3a101c9f67d --- /dev/null +++ b/src/cmd/dist/exec_119.go @@ -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 +}