github.com/reconquest/executil-go@v0.0.0-20181110204642-1f5c2d67813f/exit_error.go (about)

     1  package executil
     2  
     3  import (
     4  	"os/exec"
     5  	"syscall"
     6  
     7  	"golang.org/x/crypto/ssh"
     8  )
     9  
    10  func getWaitStatus(err error) *syscall.WaitStatus {
    11  	if err == nil {
    12  		return nil
    13  	}
    14  
    15  	if utilErr, ok := err.(*Error); ok {
    16  		err = utilErr.RunErr
    17  	}
    18  
    19  	if exitError, ok := err.(*exec.ExitError); ok {
    20  		if waitStatus, ok := exitError.Sys().(syscall.WaitStatus); ok {
    21  			return &waitStatus
    22  		}
    23  	}
    24  
    25  	return nil
    26  }
    27  
    28  // IsExitError check that the specified error is an error about exit status.
    29  func IsExitError(err error) bool {
    30  	if _, ok := err.(*ssh.ExitError); ok {
    31  		return true
    32  	}
    33  
    34  	return getWaitStatus(err) != nil
    35  }
    36  
    37  // GetExitStatus returns 0 if the specified error is not about of exit status.
    38  // Otherwise, will be returned actual exit status.
    39  func GetExitStatus(err error) int {
    40  	if exitError, ok := err.(*ssh.ExitError); ok {
    41  		return exitError.ExitStatus()
    42  	}
    43  
    44  	waitStatus := getWaitStatus(err)
    45  	if waitStatus == nil {
    46  		return 0
    47  	}
    48  
    49  	return waitStatus.ExitStatus()
    50  }