...
Run Format

Source file src/os/exec/exec.go

Documentation: os/exec

     1  // Copyright 2009 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 exec runs external commands. It wraps os.StartProcess to make it
     6  // easier to remap stdin and stdout, connect I/O with pipes, and do other
     7  // adjustments.
     8  //
     9  // Unlike the "system" library call from C and other languages, the
    10  // os/exec package intentionally does not invoke the system shell and
    11  // does not expand any glob patterns or handle other expansions,
    12  // pipelines, or redirections typically done by shells. The package
    13  // behaves more like C's "exec" family of functions. To expand glob
    14  // patterns, either call the shell directly, taking care to escape any
    15  // dangerous input, or use the path/filepath package's Glob function.
    16  // To expand environment variables, use package os's ExpandEnv.
    17  //
    18  // Note that the examples in this package assume a Unix system.
    19  // They may not run on Windows, and they do not run in the Go Playground
    20  // used by golang.org and godoc.org.
    21  package exec
    22  
    23  import (
    24  	"bytes"
    25  	"context"
    26  	"errors"
    27  	"io"
    28  	"os"
    29  	"path/filepath"
    30  	"runtime"
    31  	"strconv"
    32  	"strings"
    33  	"sync"
    34  	"syscall"
    35  )
    36  
    37  // Error is returned by LookPath when it fails to classify a file as an
    38  // executable.
    39  type Error struct {
    40  	// Name is the file name for which the error occurred.
    41  	Name string
    42  	// Err is the underlying error.
    43  	Err error
    44  }
    45  
    46  func (e *Error) Error() string {
    47  	return "exec: " + strconv.Quote(e.Name) + ": " + e.Err.Error()
    48  }
    49  
    50  // Cmd represents an external command being prepared or run.
    51  //
    52  // A Cmd cannot be reused after calling its Run, Output or CombinedOutput
    53  // methods.
    54  type Cmd struct {
    55  	// Path is the path of the command to run.
    56  	//
    57  	// This is the only field that must be set to a non-zero
    58  	// value. If Path is relative, it is evaluated relative
    59  	// to Dir.
    60  	Path string
    61  
    62  	// Args holds command line arguments, including the command as Args[0].
    63  	// If the Args field is empty or nil, Run uses {Path}.
    64  	//
    65  	// In typical use, both Path and Args are set by calling Command.
    66  	Args []string
    67  
    68  	// Env specifies the environment of the process.
    69  	// Each entry is of the form "key=value".
    70  	// If Env is nil, the new process uses the current process's
    71  	// environment.
    72  	// If Env contains duplicate environment keys, only the last
    73  	// value in the slice for each duplicate key is used.
    74  	Env []string
    75  
    76  	// Dir specifies the working directory of the command.
    77  	// If Dir is the empty string, Run runs the command in the
    78  	// calling process's current directory.
    79  	Dir string
    80  
    81  	// Stdin specifies the process's standard input.
    82  	//
    83  	// If Stdin is nil, the process reads from the null device (os.DevNull).
    84  	//
    85  	// If Stdin is an *os.File, the process's standard input is connected
    86  	// directly to that file.
    87  	//
    88  	// Otherwise, during the execution of the command a separate
    89  	// goroutine reads from Stdin and delivers that data to the command
    90  	// over a pipe. In this case, Wait does not complete until the goroutine
    91  	// stops copying, either because it has reached the end of Stdin
    92  	// (EOF or a read error) or because writing to the pipe returned an error.
    93  	Stdin io.Reader
    94  
    95  	// Stdout and Stderr specify the process's standard output and error.
    96  	//
    97  	// If either is nil, Run connects the corresponding file descriptor
    98  	// to the null device (os.DevNull).
    99  	//
   100  	// If either is an *os.File, the corresponding output from the process
   101  	// is connected directly to that file.
   102  	//
   103  	// Otherwise, during the execution of the command a separate goroutine
   104  	// reads from the process over a pipe and delivers that data to the
   105  	// corresponding Writer. In this case, Wait does not complete until the
   106  	// goroutine reaches EOF or encounters an error.
   107  	//
   108  	// If Stdout and Stderr are the same writer, and have a type that can
   109  	// be compared with ==, at most one goroutine at a time will call Write.
   110  	Stdout io.Writer
   111  	Stderr io.Writer
   112  
   113  	// ExtraFiles specifies additional open files to be inherited by the
   114  	// new process. It does not include standard input, standard output, or
   115  	// standard error. If non-nil, entry i becomes file descriptor 3+i.
   116  	//
   117  	// ExtraFiles is not supported on Windows.
   118  	ExtraFiles []*os.File
   119  
   120  	// SysProcAttr holds optional, operating system-specific attributes.
   121  	// Run passes it to os.StartProcess as the os.ProcAttr's Sys field.
   122  	SysProcAttr *syscall.SysProcAttr
   123  
   124  	// Process is the underlying process, once started.
   125  	Process *os.Process
   126  
   127  	// ProcessState contains information about an exited process,
   128  	// available after a call to Wait or Run.
   129  	ProcessState *os.ProcessState
   130  
   131  	ctx             context.Context // nil means none
   132  	lookPathErr     error           // LookPath error, if any.
   133  	finished        bool            // when Wait was called
   134  	childFiles      []*os.File
   135  	closeAfterStart []io.Closer
   136  	closeAfterWait  []io.Closer
   137  	goroutine       []func() error
   138  	errch           chan error // one send per goroutine
   139  	waitDone        chan struct{}
   140  }
   141  
   142  // Command returns the Cmd struct to execute the named program with
   143  // the given arguments.
   144  //
   145  // It sets only the Path and Args in the returned structure.
   146  //
   147  // If name contains no path separators, Command uses LookPath to
   148  // resolve name to a complete path if possible. Otherwise it uses name
   149  // directly as Path.
   150  //
   151  // The returned Cmd's Args field is constructed from the command name
   152  // followed by the elements of arg, so arg should not include the
   153  // command name itself. For example, Command("echo", "hello").
   154  // Args[0] is always name, not the possibly resolved Path.
   155  func Command(name string, arg ...string) *Cmd {
   156  	cmd := &Cmd{
   157  		Path: name,
   158  		Args: append([]string{name}, arg...),
   159  	}
   160  	if filepath.Base(name) == name {
   161  		if lp, err := LookPath(name); err != nil {
   162  			cmd.lookPathErr = err
   163  		} else {
   164  			cmd.Path = lp
   165  		}
   166  	}
   167  	return cmd
   168  }
   169  
   170  // CommandContext is like Command but includes a context.
   171  //
   172  // The provided context is used to kill the process (by calling
   173  // os.Process.Kill) if the context becomes done before the command
   174  // completes on its own.
   175  func CommandContext(ctx context.Context, name string, arg ...string) *Cmd {
   176  	if ctx == nil {
   177  		panic("nil Context")
   178  	}
   179  	cmd := Command(name, arg...)
   180  	cmd.ctx = ctx
   181  	return cmd
   182  }
   183  
   184  // interfaceEqual protects against panics from doing equality tests on
   185  // two interfaces with non-comparable underlying types.
   186  func interfaceEqual(a, b interface{}) bool {
   187  	defer func() {
   188  		recover()
   189  	}()
   190  	return a == b
   191  }
   192  
   193  func (c *Cmd) envv() []string {
   194  	if c.Env != nil {
   195  		return c.Env
   196  	}
   197  	return os.Environ()
   198  }
   199  
   200  func (c *Cmd) argv() []string {
   201  	if len(c.Args) > 0 {
   202  		return c.Args
   203  	}
   204  	return []string{c.Path}
   205  }
   206  
   207  // skipStdinCopyError optionally specifies a function which reports
   208  // whether the provided stdin copy error should be ignored.
   209  // It is non-nil everywhere but Plan 9, which lacks EPIPE. See exec_posix.go.
   210  var skipStdinCopyError func(error) bool
   211  
   212  func (c *Cmd) stdin() (f *os.File, err error) {
   213  	if c.Stdin == nil {
   214  		f, err = os.Open(os.DevNull)
   215  		if err != nil {
   216  			return
   217  		}
   218  		c.closeAfterStart = append(c.closeAfterStart, f)
   219  		return
   220  	}
   221  
   222  	if f, ok := c.Stdin.(*os.File); ok {
   223  		return f, nil
   224  	}
   225  
   226  	pr, pw, err := os.Pipe()
   227  	if err != nil {
   228  		return
   229  	}
   230  
   231  	c.closeAfterStart = append(c.closeAfterStart, pr)
   232  	c.closeAfterWait = append(c.closeAfterWait, pw)
   233  	c.goroutine = append(c.goroutine, func() error {
   234  		_, err := io.Copy(pw, c.Stdin)
   235  		if skip := skipStdinCopyError; skip != nil && skip(err) {
   236  			err = nil
   237  		}
   238  		if err1 := pw.Close(); err == nil {
   239  			err = err1
   240  		}
   241  		return err
   242  	})
   243  	return pr, nil
   244  }
   245  
   246  func (c *Cmd) stdout() (f *os.File, err error) {
   247  	return c.writerDescriptor(c.Stdout)
   248  }
   249  
   250  func (c *Cmd) stderr() (f *os.File, err error) {
   251  	if c.Stderr != nil && interfaceEqual(c.Stderr, c.Stdout) {
   252  		return c.childFiles[1], nil
   253  	}
   254  	return c.writerDescriptor(c.Stderr)
   255  }
   256  
   257  func (c *Cmd) writerDescriptor(w io.Writer) (f *os.File, err error) {
   258  	if w == nil {
   259  		f, err = os.OpenFile(os.DevNull, os.O_WRONLY, 0)
   260  		if err != nil {
   261  			return
   262  		}
   263  		c.closeAfterStart = append(c.closeAfterStart, f)
   264  		return
   265  	}
   266  
   267  	if f, ok := w.(*os.File); ok {
   268  		return f, nil
   269  	}
   270  
   271  	pr, pw, err := os.Pipe()
   272  	if err != nil {
   273  		return
   274  	}
   275  
   276  	c.closeAfterStart = append(c.closeAfterStart, pw)
   277  	c.closeAfterWait = append(c.closeAfterWait, pr)
   278  	c.goroutine = append(c.goroutine, func() error {
   279  		_, err := io.Copy(w, pr)
   280  		pr.Close() // in case io.Copy stopped due to write error
   281  		return err
   282  	})
   283  	return pw, nil
   284  }
   285  
   286  func (c *Cmd) closeDescriptors(closers []io.Closer) {
   287  	for _, fd := range closers {
   288  		fd.Close()
   289  	}
   290  }
   291  
   292  // Run starts the specified command and waits for it to complete.
   293  //
   294  // The returned error is nil if the command runs, has no problems
   295  // copying stdin, stdout, and stderr, and exits with a zero exit
   296  // status.
   297  //
   298  // If the command starts but does not complete successfully, the error is of
   299  // type *ExitError. Other error types may be returned for other situations.
   300  //
   301  // If the calling goroutine has locked the operating system thread
   302  // with runtime.LockOSThread and modified any inheritable OS-level
   303  // thread state (for example, Linux or Plan 9 name spaces), the new
   304  // process will inherit the caller's thread state.
   305  func (c *Cmd) Run() error {
   306  	if err := c.Start(); err != nil {
   307  		return err
   308  	}
   309  	return c.Wait()
   310  }
   311  
   312  // lookExtensions finds windows executable by its dir and path.
   313  // It uses LookPath to try appropriate extensions.
   314  // lookExtensions does not search PATH, instead it converts `prog` into `.\prog`.
   315  func lookExtensions(path, dir string) (string, error) {
   316  	if filepath.Base(path) == path {
   317  		path = filepath.Join(".", path)
   318  	}
   319  	if dir == "" {
   320  		return LookPath(path)
   321  	}
   322  	if filepath.VolumeName(path) != "" {
   323  		return LookPath(path)
   324  	}
   325  	if len(path) > 1 && os.IsPathSeparator(path[0]) {
   326  		return LookPath(path)
   327  	}
   328  	dirandpath := filepath.Join(dir, path)
   329  	// We assume that LookPath will only add file extension.
   330  	lp, err := LookPath(dirandpath)
   331  	if err != nil {
   332  		return "", err
   333  	}
   334  	ext := strings.TrimPrefix(lp, dirandpath)
   335  	return path + ext, nil
   336  }
   337  
   338  // Start starts the specified command but does not wait for it to complete.
   339  //
   340  // The Wait method will return the exit code and release associated resources
   341  // once the command exits.
   342  func (c *Cmd) Start() error {
   343  	if c.lookPathErr != nil {
   344  		c.closeDescriptors(c.closeAfterStart)
   345  		c.closeDescriptors(c.closeAfterWait)
   346  		return c.lookPathErr
   347  	}
   348  	if runtime.GOOS == "windows" {
   349  		lp, err := lookExtensions(c.Path, c.Dir)
   350  		if err != nil {
   351  			c.closeDescriptors(c.closeAfterStart)
   352  			c.closeDescriptors(c.closeAfterWait)
   353  			return err
   354  		}
   355  		c.Path = lp
   356  	}
   357  	if c.Process != nil {
   358  		return errors.New("exec: already started")
   359  	}
   360  	if c.ctx != nil {
   361  		select {
   362  		case <-c.ctx.Done():
   363  			c.closeDescriptors(c.closeAfterStart)
   364  			c.closeDescriptors(c.closeAfterWait)
   365  			return c.ctx.Err()
   366  		default:
   367  		}
   368  	}
   369  
   370  	type F func(*Cmd) (*os.File, error)
   371  	for _, setupFd := range []F{(*Cmd).stdin, (*Cmd).stdout, (*Cmd).stderr} {
   372  		fd, err := setupFd(c)
   373  		if err != nil {
   374  			c.closeDescriptors(c.closeAfterStart)
   375  			c.closeDescriptors(c.closeAfterWait)
   376  			return err
   377  		}
   378  		c.childFiles = append(c.childFiles, fd)
   379  	}
   380  	c.childFiles = append(c.childFiles, c.ExtraFiles...)
   381  
   382  	var err error
   383  	c.Process, err = os.StartProcess(c.Path, c.argv(), &os.ProcAttr{
   384  		Dir:   c.Dir,
   385  		Files: c.childFiles,
   386  		Env:   dedupEnv(c.envv()),
   387  		Sys:   c.SysProcAttr,
   388  	})
   389  	if err != nil {
   390  		c.closeDescriptors(c.closeAfterStart)
   391  		c.closeDescriptors(c.closeAfterWait)
   392  		return err
   393  	}
   394  
   395  	c.closeDescriptors(c.closeAfterStart)
   396  
   397  	c.errch = make(chan error, len(c.goroutine))
   398  	for _, fn := range c.goroutine {
   399  		go func(fn func() error) {
   400  			c.errch <- fn()
   401  		}(fn)
   402  	}
   403  
   404  	if c.ctx != nil {
   405  		c.waitDone = make(chan struct{})
   406  		go func() {
   407  			select {
   408  			case <-c.ctx.Done():
   409  				c.Process.Kill()
   410  			case <-c.waitDone:
   411  			}
   412  		}()
   413  	}
   414  
   415  	return nil
   416  }
   417  
   418  // An ExitError reports an unsuccessful exit by a command.
   419  type ExitError struct {
   420  	*os.ProcessState
   421  
   422  	// Stderr holds a subset of the standard error output from the
   423  	// Cmd.Output method if standard error was not otherwise being
   424  	// collected.
   425  	//
   426  	// If the error output is long, Stderr may contain only a prefix
   427  	// and suffix of the output, with the middle replaced with
   428  	// text about the number of omitted bytes.
   429  	//
   430  	// Stderr is provided for debugging, for inclusion in error messages.
   431  	// Users with other needs should redirect Cmd.Stderr as needed.
   432  	Stderr []byte
   433  }
   434  
   435  func (e *ExitError) Error() string {
   436  	return e.ProcessState.String()
   437  }
   438  
   439  // Wait waits for the command to exit and waits for any copying to
   440  // stdin or copying from stdout or stderr to complete.
   441  //
   442  // The command must have been started by Start.
   443  //
   444  // The returned error is nil if the command runs, has no problems
   445  // copying stdin, stdout, and stderr, and exits with a zero exit
   446  // status.
   447  //
   448  // If the command fails to run or doesn't complete successfully, the
   449  // error is of type *ExitError. Other error types may be
   450  // returned for I/O problems.
   451  //
   452  // If any of c.Stdin, c.Stdout or c.Stderr are not an *os.File, Wait also waits
   453  // for the respective I/O loop copying to or from the process to complete.
   454  //
   455  // Wait releases any resources associated with the Cmd.
   456  func (c *Cmd) Wait() error {
   457  	if c.Process == nil {
   458  		return errors.New("exec: not started")
   459  	}
   460  	if c.finished {
   461  		return errors.New("exec: Wait was already called")
   462  	}
   463  	c.finished = true
   464  
   465  	state, err := c.Process.Wait()
   466  	if c.waitDone != nil {
   467  		close(c.waitDone)
   468  	}
   469  	c.ProcessState = state
   470  
   471  	var copyError error
   472  	for range c.goroutine {
   473  		if err := <-c.errch; err != nil && copyError == nil {
   474  			copyError = err
   475  		}
   476  	}
   477  
   478  	c.closeDescriptors(c.closeAfterWait)
   479  
   480  	if err != nil {
   481  		return err
   482  	} else if !state.Success() {
   483  		return &ExitError{ProcessState: state}
   484  	}
   485  
   486  	return copyError
   487  }
   488  
   489  // Output runs the command and returns its standard output.
   490  // Any returned error will usually be of type *ExitError.
   491  // If c.Stderr was nil, Output populates ExitError.Stderr.
   492  func (c *Cmd) Output() ([]byte, error) {
   493  	if c.Stdout != nil {
   494  		return nil, errors.New("exec: Stdout already set")
   495  	}
   496  	var stdout bytes.Buffer
   497  	c.Stdout = &stdout
   498  
   499  	captureErr := c.Stderr == nil
   500  	if captureErr {
   501  		c.Stderr = &prefixSuffixSaver{N: 32 << 10}
   502  	}
   503  
   504  	err := c.Run()
   505  	if err != nil && captureErr {
   506  		if ee, ok := err.(*ExitError); ok {
   507  			ee.Stderr = c.Stderr.(*prefixSuffixSaver).Bytes()
   508  		}
   509  	}
   510  	return stdout.Bytes(), err
   511  }
   512  
   513  // CombinedOutput runs the command and returns its combined standard
   514  // output and standard error.
   515  func (c *Cmd) CombinedOutput() ([]byte, error) {
   516  	if c.Stdout != nil {
   517  		return nil, errors.New("exec: Stdout already set")
   518  	}
   519  	if c.Stderr != nil {
   520  		return nil, errors.New("exec: Stderr already set")
   521  	}
   522  	var b bytes.Buffer
   523  	c.Stdout = &b
   524  	c.Stderr = &b
   525  	err := c.Run()
   526  	return b.Bytes(), err
   527  }
   528  
   529  // StdinPipe returns a pipe that will be connected to the command's
   530  // standard input when the command starts.
   531  // The pipe will be closed automatically after Wait sees the command exit.
   532  // A caller need only call Close to force the pipe to close sooner.
   533  // For example, if the command being run will not exit until standard input
   534  // is closed, the caller must close the pipe.
   535  func (c *Cmd) StdinPipe() (io.WriteCloser, error) {
   536  	if c.Stdin != nil {
   537  		return nil, errors.New("exec: Stdin already set")
   538  	}
   539  	if c.Process != nil {
   540  		return nil, errors.New("exec: StdinPipe after process started")
   541  	}
   542  	pr, pw, err := os.Pipe()
   543  	if err != nil {
   544  		return nil, err
   545  	}
   546  	c.Stdin = pr
   547  	c.closeAfterStart = append(c.closeAfterStart, pr)
   548  	wc := &closeOnce{File: pw}
   549  	c.closeAfterWait = append(c.closeAfterWait, wc)
   550  	return wc, nil
   551  }
   552  
   553  type closeOnce struct {
   554  	*os.File
   555  
   556  	once sync.Once
   557  	err  error
   558  }
   559  
   560  func (c *closeOnce) Close() error {
   561  	c.once.Do(c.close)
   562  	return c.err
   563  }
   564  
   565  func (c *closeOnce) close() {
   566  	c.err = c.File.Close()
   567  }
   568  
   569  // StdoutPipe returns a pipe that will be connected to the command's
   570  // standard output when the command starts.
   571  //
   572  // Wait will close the pipe after seeing the command exit, so most callers
   573  // need not close the pipe themselves; however, an implication is that
   574  // it is incorrect to call Wait before all reads from the pipe have completed.
   575  // For the same reason, it is incorrect to call Run when using StdoutPipe.
   576  // See the example for idiomatic usage.
   577  func (c *Cmd) StdoutPipe() (io.ReadCloser, error) {
   578  	if c.Stdout != nil {
   579  		return nil, errors.New("exec: Stdout already set")
   580  	}
   581  	if c.Process != nil {
   582  		return nil, errors.New("exec: StdoutPipe after process started")
   583  	}
   584  	pr, pw, err := os.Pipe()
   585  	if err != nil {
   586  		return nil, err
   587  	}
   588  	c.Stdout = pw
   589  	c.closeAfterStart = append(c.closeAfterStart, pw)
   590  	c.closeAfterWait = append(c.closeAfterWait, pr)
   591  	return pr, nil
   592  }
   593  
   594  // StderrPipe returns a pipe that will be connected to the command's
   595  // standard error when the command starts.
   596  //
   597  // Wait will close the pipe after seeing the command exit, so most callers
   598  // need not close the pipe themselves; however, an implication is that
   599  // it is incorrect to call Wait before all reads from the pipe have completed.
   600  // For the same reason, it is incorrect to use Run when using StderrPipe.
   601  // See the StdoutPipe example for idiomatic usage.
   602  func (c *Cmd) StderrPipe() (io.ReadCloser, error) {
   603  	if c.Stderr != nil {
   604  		return nil, errors.New("exec: Stderr already set")
   605  	}
   606  	if c.Process != nil {
   607  		return nil, errors.New("exec: StderrPipe after process started")
   608  	}
   609  	pr, pw, err := os.Pipe()
   610  	if err != nil {
   611  		return nil, err
   612  	}
   613  	c.Stderr = pw
   614  	c.closeAfterStart = append(c.closeAfterStart, pw)
   615  	c.closeAfterWait = append(c.closeAfterWait, pr)
   616  	return pr, nil
   617  }
   618  
   619  // prefixSuffixSaver is an io.Writer which retains the first N bytes
   620  // and the last N bytes written to it. The Bytes() methods reconstructs
   621  // it with a pretty error message.
   622  type prefixSuffixSaver struct {
   623  	N         int // max size of prefix or suffix
   624  	prefix    []byte
   625  	suffix    []byte // ring buffer once len(suffix) == N
   626  	suffixOff int    // offset to write into suffix
   627  	skipped   int64
   628  
   629  	// TODO(bradfitz): we could keep one large []byte and use part of it for
   630  	// the prefix, reserve space for the '... Omitting N bytes ...' message,
   631  	// then the ring buffer suffix, and just rearrange the ring buffer
   632  	// suffix when Bytes() is called, but it doesn't seem worth it for
   633  	// now just for error messages. It's only ~64KB anyway.
   634  }
   635  
   636  func (w *prefixSuffixSaver) Write(p []byte) (n int, err error) {
   637  	lenp := len(p)
   638  	p = w.fill(&w.prefix, p)
   639  
   640  	// Only keep the last w.N bytes of suffix data.
   641  	if overage := len(p) - w.N; overage > 0 {
   642  		p = p[overage:]
   643  		w.skipped += int64(overage)
   644  	}
   645  	p = w.fill(&w.suffix, p)
   646  
   647  	// w.suffix is full now if p is non-empty. Overwrite it in a circle.
   648  	for len(p) > 0 { // 0, 1, or 2 iterations.
   649  		n := copy(w.suffix[w.suffixOff:], p)
   650  		p = p[n:]
   651  		w.skipped += int64(n)
   652  		w.suffixOff += n
   653  		if w.suffixOff == w.N {
   654  			w.suffixOff = 0
   655  		}
   656  	}
   657  	return lenp, nil
   658  }
   659  
   660  // fill appends up to len(p) bytes of p to *dst, such that *dst does not
   661  // grow larger than w.N. It returns the un-appended suffix of p.
   662  func (w *prefixSuffixSaver) fill(dst *[]byte, p []byte) (pRemain []byte) {
   663  	if remain := w.N - len(*dst); remain > 0 {
   664  		add := minInt(len(p), remain)
   665  		*dst = append(*dst, p[:add]...)
   666  		p = p[add:]
   667  	}
   668  	return p
   669  }
   670  
   671  func (w *prefixSuffixSaver) Bytes() []byte {
   672  	if w.suffix == nil {
   673  		return w.prefix
   674  	}
   675  	if w.skipped == 0 {
   676  		return append(w.prefix, w.suffix...)
   677  	}
   678  	var buf bytes.Buffer
   679  	buf.Grow(len(w.prefix) + len(w.suffix) + 50)
   680  	buf.Write(w.prefix)
   681  	buf.WriteString("\n... omitting ")
   682  	buf.WriteString(strconv.FormatInt(w.skipped, 10))
   683  	buf.WriteString(" bytes ...\n")
   684  	buf.Write(w.suffix[w.suffixOff:])
   685  	buf.Write(w.suffix[:w.suffixOff])
   686  	return buf.Bytes()
   687  }
   688  
   689  func minInt(a, b int) int {
   690  	if a < b {
   691  		return a
   692  	}
   693  	return b
   694  }
   695  
   696  // dedupEnv returns a copy of env with any duplicates removed, in favor of
   697  // later values.
   698  // Items not of the normal environment "key=value" form are preserved unchanged.
   699  func dedupEnv(env []string) []string {
   700  	return dedupEnvCase(runtime.GOOS == "windows", env)
   701  }
   702  
   703  // dedupEnvCase is dedupEnv with a case option for testing.
   704  // If caseInsensitive is true, the case of keys is ignored.
   705  func dedupEnvCase(caseInsensitive bool, env []string) []string {
   706  	out := make([]string, 0, len(env))
   707  	saw := map[string]int{} // key => index into out
   708  	for _, kv := range env {
   709  		eq := strings.Index(kv, "=")
   710  		if eq < 0 {
   711  			out = append(out, kv)
   712  			continue
   713  		}
   714  		k := kv[:eq]
   715  		if caseInsensitive {
   716  			k = strings.ToLower(k)
   717  		}
   718  		if dupIdx, isDup := saw[k]; isDup {
   719  			out[dupIdx] = kv
   720  			continue
   721  		}
   722  		saw[k] = len(out)
   723  		out = append(out, kv)
   724  	}
   725  	return out
   726  }
   727  

View as plain text