github.com/jenkins-x/jx/v2@v2.1.155/cmd/codegen/util/cli.go (about)

     1  package util
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"strings"
     7  )
     8  
     9  const (
    10  	// DefaultErrorExitCode is the default exit code in case of an error
    11  	DefaultErrorExitCode = 1
    12  )
    13  
    14  var (
    15  	fatalErrHandler = fatal
    16  	// ErrExit can be used to exit with a non 0 exit code without any error message
    17  	ErrExit = fmt.Errorf("exit")
    18  )
    19  
    20  // InvalidOptionf returns an error that shows the invalid option.
    21  func InvalidOptionf(option string, value interface{}, message string, a ...interface{}) error {
    22  	text := fmt.Sprintf(message, a...)
    23  	return fmt.Errorf("invalid option: --%s %v\n%s", option, value, text)
    24  }
    25  
    26  // MissingOption reports a missing command line option using the full name expression.
    27  func MissingOption(name string) error {
    28  	return fmt.Errorf("missing option: --%s", name)
    29  }
    30  
    31  // CheckErr prints a user friendly error to STDERR and exits with a non-zero exit code.
    32  func CheckErr(err error) {
    33  	checkErr(err, fatalErrHandler)
    34  }
    35  
    36  // checkErr formats a given error as a string and calls the passed handleErr func.
    37  func checkErr(err error, handleErr func(string, int)) {
    38  	switch {
    39  	case err == nil:
    40  		return
    41  	case err == ErrExit:
    42  		handleErr("", DefaultErrorExitCode)
    43  		return
    44  	default:
    45  		handleErr(err.Error(), DefaultErrorExitCode)
    46  	}
    47  }
    48  
    49  func fatal(msg string, code int) {
    50  	if len(msg) > 0 {
    51  		// add newline if needed
    52  		if !strings.HasSuffix(msg, "\n") {
    53  			msg += "\n"
    54  		}
    55  		fmt.Fprint(os.Stderr, msg)
    56  	}
    57  	os.Exit(code)
    58  }