github.com/Aoi-hosizora/ahlib-more@v1.5.1-0.20230404072844-256112befaf6/xpflag/xpflag.go (about)

     1  package xpflag
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"github.com/spf13/pflag"
     7  	"io"
     8  	"os"
     9  )
    10  
    11  // _cmd is a global pflag.FlagSet.
    12  var _cmd = pflag.NewFlagSet(os.Args[0], pflag.ContinueOnError)
    13  
    14  func init() {
    15  	_cmd.Usage = func() { DefaultUsage(_cmd) }
    16  }
    17  
    18  // Cmd returns the global pflag.FlagSet. This should be used if want to use Parse, MustParse or PrintUsage.
    19  func Cmd() *pflag.FlagSet {
    20  	return _cmd
    21  }
    22  
    23  // DefaultUsage is the default usage function, which prints the default usage string to os.Stderr.
    24  func DefaultUsage(cmd *pflag.FlagSet) {
    25  	fmt.Fprintf(_osStderr, "Usage of %s:\n", os.Args[0])
    26  	fmt.Fprintf(_osStderr, "%s", cmd.FlagUsages())
    27  }
    28  
    29  // PrintUsage prints the default usage string to os.Stderr.
    30  func PrintUsage() {
    31  	if _cmd.Usage != nil {
    32  		_cmd.Usage()
    33  	}
    34  }
    35  
    36  // Parse parses flags passed to the program and returns error, note that this function never panic or exit the program.
    37  func Parse() error {
    38  	return _cmd.Parse(os.Args[1:]) // may return "pflag.ErrHelp"
    39  }
    40  
    41  // _osStderr always equals to os.Stderr except when testing.
    42  var _osStderr io.Writer = os.Stderr
    43  
    44  // _osExit always equals to os.Exit except when testing.
    45  var _osExit = os.Exit
    46  
    47  // MustParse parses flags passed to the program, prints error message and exits the program when failed to parse.
    48  func MustParse() {
    49  	err := Parse()
    50  	if err != nil {
    51  		if errors.Is(err, pflag.ErrHelp) {
    52  			_osExit(0)
    53  			return
    54  		}
    55  		fmt.Fprintf(_osStderr, "Error: %v\n", err)
    56  		fmt.Fprintf(_osStderr, "Run '%s --help' for usage.\n", os.Args[0])
    57  		_osExit(2)
    58  	}
    59  }