github.com/bazelbuild/rules_webtesting@v0.2.0/go/cmdhelper/cmd_helper.go (about) 1 // Copyright 2016 Google Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 // Package cmdhelper provides functions to make working os/exec Command easier. 16 package cmdhelper 17 18 import ( 19 "os" 20 "strings" 21 ) 22 23 // UpdateEnv takes an environment array, an env var name, and an environment 24 // var value and updates the current definition of the env var or adds a new 25 // environment variable definition. 26 func UpdateEnv(env []string, name, value string) []string { 27 prefix := name + "=" 28 29 for i := 0; i < len(env); { 30 if strings.HasPrefix(env[i], prefix) { 31 env = append(env[:i], env[i+1:]...) 32 } else { 33 i++ 34 } 35 } 36 37 return append(env, prefix+value) 38 } 39 40 // BulkUpdateEnv returns a new slice suitable for use with exec.Cmd.Env 41 // based on env but with environment variables for the keys in update 42 // added/changed to the values in update. 43 func BulkUpdateEnv(env []string, update map[string]string) []string { 44 for name, value := range update { 45 env = UpdateEnv(env, name, value) 46 } 47 return env 48 } 49 50 // IsTruthyEnv return true if name is set in the environment and has value other than 51 // 0 or false (case-insensitive). 52 func IsTruthyEnv(name string) bool { 53 value := os.Getenv(name) 54 return value != "" && value != "0" && strings.ToLower(value) != "false" 55 }