github.com/goproxy0/go@v0.0.0-20171111080102-49cc0c489d2c/src/cmd/go/internal/base/env.go (about) 1 // Copyright 2017 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 package base 6 7 import "strings" 8 9 // EnvForDir returns a copy of the environment 10 // suitable for running in the given directory. 11 // The environment is the current process's environment 12 // but with an updated $PWD, so that an os.Getwd in the 13 // child will be faster. 14 func EnvForDir(dir string, base []string) []string { 15 // Internally we only use rooted paths, so dir is rooted. 16 // Even if dir is not rooted, no harm done. 17 return MergeEnvLists([]string{"PWD=" + dir}, base) 18 } 19 20 // MergeEnvLists merges the two environment lists such that 21 // variables with the same name in "in" replace those in "out". 22 // This always returns a newly allocated slice. 23 func MergeEnvLists(in, out []string) []string { 24 out = append([]string(nil), out...) 25 NextVar: 26 for _, inkv := range in { 27 k := strings.SplitAfterN(inkv, "=", 2)[0] 28 for i, outkv := range out { 29 if strings.HasPrefix(outkv, k) { 30 out[i] = inkv 31 continue NextVar 32 } 33 } 34 out = append(out, inkv) 35 } 36 return out 37 }