github.com/mutagen-io/mutagen@v0.18.0-rc1/pkg/process/errors.go (about)

     1  package process
     2  
     3  import (
     4  	"os/exec"
     5  	"strings"
     6  	"unicode/utf8"
     7  
     8  	"github.com/mutagen-io/mutagen/pkg/platform/terminal"
     9  )
    10  
    11  const (
    12  	// posixCommandNotFoundFragment is a fragment of the error output returned
    13  	// on some POSIX shells when a command is not found. The capitalization of
    14  	// the word "command" is inconsistent between shells, so only part of the
    15  	// word is used.
    16  	posixCommandNotFoundFragment = "ommand not found"
    17  	// windowsInvalidCommandFragment is a fragment of the error output returned
    18  	// on Windows systems when a command is not recognized.
    19  	windowsInvalidCommandFragment = "is not recognized as an internal or external command"
    20  	// windowsCommandNotFoundFragment is a fragment of the error output returned
    21  	// on Windows systems when a command cannot be found.
    22  	windowsCommandNotFoundFragment = "The system cannot find the path specified"
    23  )
    24  
    25  // OutputIsPOSIXCommandNotFound returns whether or not a process' error output
    26  // represents a command not found error on POSIX systems.
    27  func OutputIsPOSIXCommandNotFound(output string) bool {
    28  	return strings.Contains(output, posixCommandNotFoundFragment)
    29  }
    30  
    31  // OutputIsWindowsInvalidCommand returns whether or not a process' error output
    32  // represents an invalid command error on Windows.
    33  func OutputIsWindowsInvalidCommand(output string) bool {
    34  	return strings.Contains(output, windowsInvalidCommandFragment)
    35  }
    36  
    37  // OutputIsWindowsCommandNotFound returns whether or not a process' error output
    38  // represents a command not found error on Windows.
    39  func OutputIsWindowsCommandNotFound(output string) bool {
    40  	return strings.Contains(output, windowsCommandNotFoundFragment)
    41  }
    42  
    43  // ExtractExitErrorMessage is a utility function that will attempt to extract
    44  // the Stderr portion of the specified error, assuming it is an
    45  // os/exec.ExitError. If the error is not an os/exec.ExitError, or if the Stderr
    46  // field is not UTF-8 encoded, or if the message in Stderr is empty after
    47  // stripping surrounding white space, then an empty string is returned. This
    48  // function will perform control character neutralization on any returned value.
    49  func ExtractExitErrorMessage(err error) string {
    50  	if exitErr, ok := err.(*exec.ExitError); ok && utf8.Valid(exitErr.Stderr) {
    51  		return terminal.NeutralizeControlCharacters(strings.TrimSpace(string(exitErr.Stderr)))
    52  	}
    53  	return ""
    54  }