Source file src/cmd/dist/exec.go

     1  // Copyright 2022 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/exec"
     9  	"strings"
    10  )
    11  
    12  // setDir sets cmd.Dir to dir, and also adds PWD=dir to cmd's environment.
    13  func setDir(cmd *exec.Cmd, dir string) {
    14  	cmd.Dir = dir
    15  	if cmd.Env != nil {
    16  		// os/exec won't set PWD automatically.
    17  		setEnv(cmd, "PWD", dir)
    18  	}
    19  }
    20  
    21  // setEnv sets cmd.Env so that key = value.
    22  func setEnv(cmd *exec.Cmd, key, value string) {
    23  	cmd.Env = append(cmd.Environ(), key+"="+value)
    24  }
    25  
    26  // unsetEnv sets cmd.Env so that key is not present in the environment.
    27  func unsetEnv(cmd *exec.Cmd, key string) {
    28  	cmd.Env = cmd.Environ()
    29  
    30  	prefix := key + "="
    31  	newEnv := []string{}
    32  	for _, entry := range cmd.Env {
    33  		if strings.HasPrefix(entry, prefix) {
    34  			continue
    35  		}
    36  		newEnv = append(newEnv, entry)
    37  		// key may appear multiple times, so keep going.
    38  	}
    39  	cmd.Env = newEnv
    40  }
    41  

View as plain text