Source file src/cmd/dist/exec.go

     1  // Copyright 2021 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 main
     6  
     7  import (
     8  	"os"
     9  	"os/exec"
    10  	"strings"
    11  )
    12  
    13  // setDir sets cmd.Dir to dir, and also adds PWD=dir to cmd's environment.
    14  func setDir(cmd *exec.Cmd, dir string) {
    15  	cmd.Dir = dir
    16  	setEnv(cmd, "PWD", dir)
    17  }
    18  
    19  // setEnv sets cmd.Env so that key = value.
    20  //
    21  // It first removes any existing values for key, so it is safe to call
    22  // even from within cmdbootstrap.
    23  func setEnv(cmd *exec.Cmd, key, value string) {
    24  	kv := key + "=" + value
    25  	if cmd.Env == nil {
    26  		cmd.Env = os.Environ()
    27  	}
    28  
    29  	prefix := kv[:len(key)+1]
    30  	for i, entry := range cmd.Env {
    31  		if strings.HasPrefix(entry, prefix) {
    32  			cmd.Env[i] = kv
    33  			return
    34  		}
    35  	}
    36  
    37  	cmd.Env = append(cmd.Env, kv)
    38  }
    39  
    40  // unsetEnv sets cmd.Env so that key is not present in the environment.
    41  func unsetEnv(cmd *exec.Cmd, key string) {
    42  	if cmd.Env == nil {
    43  		cmd.Env = os.Environ()
    44  	}
    45  
    46  	prefix := key + "="
    47  	for i, entry := range cmd.Env {
    48  		if strings.HasPrefix(entry, prefix) {
    49  			cmd.Env = append(cmd.Env[:i], cmd.Env[i+1:]...)
    50  			return
    51  		}
    52  	}
    53  }
    54  

View as plain text