summaryrefslogtreecommitdiff
path: root/parse.go
diff options
context:
space:
mode:
authorduxinlong <[email protected]>2023-02-08 12:01:48 +0000
committerduxinlong <[email protected]>2023-02-08 12:01:48 +0000
commitefae1938fd6c8434532ca7527cd90752e558d377 (patch)
treec2db08470fe80424bf7b52fe082d837452b8bdf9 /parse.go
parentc0a8e20a0ac9e8a9dbb0e078b0befd8e28302e8b (diff)
feat: support more env than terminal
Change-Id: I7f35e90b8f19f4ea781832885d35e2f1e275207a
Diffstat (limited to 'parse.go')
-rw-r--r--parse.go31
1 files changed, 27 insertions, 4 deletions
diff --git a/parse.go b/parse.go
index b935fad..6d8b509 100644
--- a/parse.go
+++ b/parse.go
@@ -5,6 +5,7 @@ import (
"encoding/csv"
"errors"
"fmt"
+ "io"
"os"
"path/filepath"
"reflect"
@@ -119,6 +120,10 @@ type Config struct {
// StrictSubcommands intructs the library not to allow global commands after
// subcommand
StrictSubcommands bool
+
+ OsExit func(int)
+ Stdout io.Writer
+ Stderr io.Writer
}
// Parser represents a set of command line options with destination values
@@ -132,6 +137,10 @@ type Parser struct {
// the following field changes during processing of command line arguments
lastCmd *command
+
+ osExit func(int)
+ stdout io.Writer
+ stderr io.Writer
}
// Versioned is the interface that the destination struct should implement to
@@ -196,6 +205,20 @@ func NewParser(config Config, dests ...interface{}) (*Parser, error) {
p := Parser{
cmd: &command{name: name},
config: config,
+
+ osExit: osExit,
+ stdout: stdout,
+ stderr: stderr,
+ }
+
+ if config.OsExit != nil {
+ p.osExit = config.OsExit
+ }
+ if config.Stdout != nil {
+ p.stdout = config.Stdout
+ }
+ if config.Stderr != nil {
+ p.stderr = config.Stderr
}
// make a list of roots
@@ -483,11 +506,11 @@ func (p *Parser) MustParse(args []string) {
err := p.Parse(args)
switch {
case err == ErrHelp:
- p.writeHelpForSubcommand(stdout, p.lastCmd)
- osExit(0)
+ p.writeHelpForSubcommand(p.stdout, p.lastCmd)
+ p.osExit(0)
case err == ErrVersion:
- fmt.Fprintln(stdout, p.version)
- osExit(0)
+ fmt.Fprintln(p.stdout, p.version)
+ p.osExit(0)
case err != nil:
p.failWithSubcommand(err.Error(), p.lastCmd)
}