go-extargsparse: github.com/jeppeter/go-extargsparse Index | Examples | Files | Directories

package extargsparse

import "github.com/jeppeter/go-extargsparse"

Index

Examples

Package Files

const.go funccall.go helpsize.go key.go logutil.go namespaceex.go optchk.go options.go parse_state.go parser.go parser_compat.go util.go writer.go

Constants

const (
    OPT_PROG             = "prog"
    OPT_USAGE            = "usage"
    OPT_DESCRIPTION      = "description"
    OPT_EPILOG           = "epilog"
    OPT_VERSION          = "version"
    OPT_ERROR_HANDLER    = "errorhandler"
    OPT_HELP_HANDLER     = "helphandler"
    OPT_LONG_PREFIX      = "longprefix"
    OPT_SHORT_PREFIX     = "shortprefix"
    OPT_NO_HELP_OPTION   = "nohelpoption"
    OPT_NO_JSON_OPTION   = "nojsonoption"
    OPT_HELP_LONG        = "helplong"
    OPT_HELP_SHORT       = "helpshort"
    OPT_JSON_LONG        = "jsonlong"
    OPT_CMD_PREFIX_ADDED = "cmdprefixadded"
    OPT_PARSE_ALL        = "parseall"
    OPT_SCREEN_WIDTH     = "screenwidth"
    OPT_FLAG_NO_CHANGE   = "flagnochange"
    OPT_VAR_UPPER_CASE   = "varuppercase"
    OPT_FUNC_UPPER_CASE  = "funcuppercase"
)

constant for the options used

OPT_PROG used for program name
OPT_USAGE used for help information
OPT_DESCRIPTION for description in help
OPT_EPILOG for help epilog
OPT_VERSION for version set
OPT_ERROR_HANDLER for error handler ,now is reserved
OPT_HELP_HANDLER for help option ,default is ""; "nohelp" for no help information print out
OPT_LONG_PREFIX for long prefix ,default is "--"
OPT_SHORT_PREFIX for short prefix, default is "-"
OPT_NO_HELP_OPTION for no help flag inserted into the opts default false
OPT_NO_JSON_OPTION for no json flag inserted into the opts default false
OPT_HELP_LONG for help flag flagname default "help"
OPT_HELP_SHORT for help flag shortflag default "h"
OPT_JSON_LONG for json flag flagname default "json"
OPT_CMD_PREFIX_ADDED for cmd and subcommand to add before flag , default true
OPT_PARSE_ALL for parse all ,and it will enable subargs or args before the flags , default true
OPT_SCREEN_WIDTH for print help screen width ,default 80
OPT_FLAG_NO_CHANGE for flag will change when to varname flagname and longopt default true
OPT_VAR_UPPER_CASE used in the extargsparse.ExtArgsOptions for variable for first character uppercase default is true
OPT_FUNC_UPPER_CASE used in the function for first character uppercase default is true
const (
    COMMAND_SET              = 10
    SUB_COMMAND_JSON_SET     = 20
    COMMAND_JSON_SET         = 30
    ENVIRONMENT_SET          = 40
    ENV_SUB_COMMAND_JSON_SET = 50
    ENV_COMMAND_JSON_SET     = 60
    DEFAULT_SET              = 70
)

constant for the priority in the NewExtArgsParse

COMMAND_SET for the command line input
SUB_COMMAND_JSON_SET  for the jsonfile specified in the subcommand
COMMAND_JSON_SET for the jsonfile specified in the top
ENVIRONMENT_SET  environment variable set
ENV_SUB_COMMAND_JSON_SET for the jsonfile specified by the evironment for subcommand
ENV_COMMAND_JSON_SET for the jsonfile specified by the environment for top
DEFAULT_SET  default value set by the json string
default priority is in the int order [COMMAND_SET,SUB_COMMAND_JSON_SET,COMMAND_JSON_SET,ENVIRONMENT_SET,ENV_SUB_COMMAND_JSON_SET,ENV_COMMAND_JSON_SET,DEFAULT_SET]
const (
    EXTARGSPARSE_VERSION = "0.0.2"
)

type ExtArgsOptions Uses

type ExtArgsOptions struct {
    // contains filtered or unexported fields
}

func NewExtArgsOptions Uses

func NewExtArgsOptions(s string) (p *ExtArgsOptions, err error)

NewExtArgsOptions for create new options for *ExtArgsParse

s is the json file ,
key                  default value
OPT_PROG:                ""
OPT_USAGE:               ""
OPT_DESCRIPTION:         ""
OPT_EPILOG:              ""
OPT_VERSION:             "0.0.1"
OPT_ERROR_HANDLER:       "exit"
OPT_HELP_HANDLER:        nil
OPT_LONG_PREFIX:         "--"
OPT_SHORT_PREFIX:        "-"
OPT_NO_HELP_OPTION:      false
OPT_NO_JSON_OPTION:      false
OPT_HELP_LONG:           "help"
OPT_HELP_SHORT:          "h"
OPT_JSON_LONG:           "json"
OPT_CMD_PREFIX_ADDED:    true
OPT_PARSE_ALL:           true
OPT_SCREEN_WIDTH:        80
OPT_FLAG_NO_CHANGE:      false
OPT_VAR_UPPER_CASE:      true
OPT_FUNC_UPPER_CASE:     true

Code:

var options *extargsparse.ExtArgsOptions
var err error
var confstr = fmt.Sprintf(`{
		"%s" : 90.0		
		}`, extargsparse.OPT_SCREEN_WIDTH)
options, err = extargsparse.NewExtArgsOptions(confstr)
if err == nil {
    fmt.Fprintf(os.Stdout, "screenwidth=%d\n", options.GetInt(extargsparse.OPT_SCREEN_WIDTH)) // screenwidth=90
}
return

func (*ExtArgsOptions) Format Uses

func (p *ExtArgsOptions) Format() string

Format to give the value in the string format split by ; it is by debug used

func (*ExtArgsOptions) GetBool Uses

func (p *ExtArgsOptions) GetBool(k string) bool

get the value of key ,if it is not set or not bool type it will return false

func (*ExtArgsOptions) GetInt Uses

func (p *ExtArgsOptions) GetInt(k string) int

get the value of key ,if it is not set or not int type it will return 0

func (*ExtArgsOptions) GetString Uses

func (p *ExtArgsOptions) GetString(k string) string

get the value of key , if it is not set or not string type it will return ""

func (*ExtArgsOptions) GetValue Uses

func (p *ExtArgsOptions) GetValue(k string) interface{}

get the value of key ,if not set return nil, otherwise return the interface{}

it gives the caller to check the type

func (*ExtArgsOptions) SetValue Uses

func (p *ExtArgsOptions) SetValue(k string, v interface{}) error

to set the value of k and v

it almost the direct but one case with float in the type of no small part ,it will return int set

Code:

var options *extargsparse.ExtArgsOptions
var err error
options, err = extargsparse.NewExtArgsOptions(`{}`)
if err == nil {
    options.SetValue(extargsparse.OPT_SCREEN_WIDTH, float64(100.0))
    fmt.Fprintf(os.Stdout, "screenwidth=%d\n", options.GetInt(extargsparse.OPT_SCREEN_WIDTH)) //screenwidth=100
}
return

type ExtArgsParse Uses

type ExtArgsParse struct {
    // contains filtered or unexported fields
}

func NewExtArgsParse Uses

func NewExtArgsParse(options *ExtArgsOptions, priority interface{}) (self *ExtArgsParse, err error)

NewExtArgsParse create the parser to parse command line

options is the options created by NewExtArgsOptions
priority is can be either nil or []int{}   value only can be [COMMAND_SET,SUB_COMMAND_JSON_SET,COMMAND_JSON_SET,ENVIRONMENT_SET,ENV_SUB_COMMAND_JSON_SET,ENV_COMMAND_JSON_SET,DEFAULT_SET]

Code:

var parser *extargsparse.ExtArgsParse
var err error
var loads = `{}`
parser, err = extargsparse.NewExtArgsParse(nil, nil)
if err == nil {
    parser.LoadCommandLineString(loads)
    parser.ParseCommandLine([]string{"-h"}, nil)
    /*
    	Output:
    	cmd 0.0.1  [OPTIONS] [args...]'

    	[OPTIONS]
    	    --json     json  json input file to get the value set
    	    --help|-h        to display this help information
    */
}

Output:

			cmd 0.0.1  [OPTIONS] [args...]'

			[OPTIONS]
			    --json     json  json input file to get the value set
			    --help|-h        to display this help information

Code:

var err error
var loads = `        {
        "verbose|v" : "+",
        "$port|p" : {
            "value" : 3000,
            "type" : "int",
            "nargs" : 1 ,
            "helpinfo" : "port to connect"
        },
        "dep" : {
            "list|l" : [],
            "string|s" : "s_var",
            "$" : "+"
        }
    }`
var confstr = fmt.Sprintf(`        {
        "%s" : true,
        "%s" : true
    }`, extargsparse.OPT_NO_JSON_OPTION, extargsparse.OPT_NO_HELP_OPTION)
var options *extargsparse.ExtArgsOptions
var parser *extargsparse.ExtArgsParse
var args *extargsparse.NameSpaceEx
var jsonfile string
var depjsonfile string
var depstrval string = `newval`
var depliststr string = `["depenv1","depenv2"]`
var f *os.File

f, _ = ioutil.TempFile("", "jsonfile")
jsonfile = f.Name()
f.Close()
ioutil.WriteFile(jsonfile, []byte(`{"dep":{"list" : ["jsonval1","jsonval2"],"string" : "jsonstring"},"port":6000,"verbose":3}`), 0600)
defer os.RemoveAll(jsonfile)

f, _ = ioutil.TempFile("", "jsonfile")
depjsonfile = f.Name()
f.Close()
ioutil.WriteFile(depjsonfile, []byte(`{"list":["depjson1","depjson2"]}`), 0600)
defer os.RemoveAll(depjsonfile)

os.Setenv("EXTARGSPARSE_JSONFILE", jsonfile)
os.Setenv("DEP_JSONFILE", depjsonfile)

options, err = extargsparse.NewExtArgsOptions(confstr)
if err == nil {
    parser, err = extargsparse.NewExtArgsParse(options, []int{extargsparse.ENV_COMMAND_JSON_SET, extargsparse.ENVIRONMENT_SET, extargsparse.ENV_SUB_COMMAND_JSON_SET})
    if err == nil {
        err = parser.LoadCommandLineString(loads)
        if err == nil {
            os.Setenv("DEP_STRING", depstrval)
            os.Setenv("DEP_LIST", depliststr)
            args, err = parser.ParseCommandLine([]string{"-p", "9000", "dep", "--dep-string", "ee", "ww"}, nil)
            fmt.Fprintf(os.Stdout, "verbose=%d\n", args.GetInt("verbose"))          // verbose=0
            fmt.Fprintf(os.Stdout, "port=%d\n", args.GetInt("port"))                // port=9000
            fmt.Fprintf(os.Stdout, "subcommand=%s\n", args.GetString("subcommand")) // subcommand=dep
            fmt.Fprintf(os.Stdout, "dep_list=%v\n", args.GetArray("dep_list"))      //dep_list=[depenv1 depenv2]
            fmt.Fprintf(os.Stdout, "dep_string=%s\n", args.GetString("dep_string")) // dep_string=ee
            fmt.Fprintf(os.Stdout, "subnargs=%v\n", args.GetArray("subnargs"))      // subnargs=ww
        }
    }
}
return

Code:

var parser *extargsparse.ExtArgsParse
var options *extargsparse.ExtArgsOptions
var confstr = fmt.Sprintf(`{"%s" : true}`, extargsparse.OPT_NO_HELP_OPTION)
var err error
var loads = `{}`
options, err = extargsparse.NewExtArgsOptions(confstr)
if err == nil {
    parser, err = extargsparse.NewExtArgsParse(options, nil)
    if err == nil {
        parser.LoadCommandLineString(loads)
        // simplest the parser without help option
    }
}
return

func (*ExtArgsParse) GetCmdKey Uses

func (self *ExtArgsParse) GetCmdKey(cmdname string) (*ExtKeyParse, error)

GetCmdKey will get the command keycls for this ,it can be for parse and expand the coding

Code:

var err error
var loads = `        {
        "float1|f" : 3.633 ,
        "float2" : 6422.22,
        "float3" : 44463.23,
        "verbose|v" : "+",
        "dep" : {
            "float3" : 3332.233
        },
        "rdep" : {
            "ip" : {
                "float4" : 3377.33,
                "float6" : 33.22,
                "float7" : 0.333
            }
        }

    }`
var confstr = fmt.Sprintf(`        {
        "%s" : true,
        "%s" : true
    }`, extargsparse.OPT_NO_JSON_OPTION, extargsparse.OPT_NO_HELP_OPTION)
var options *extargsparse.ExtArgsOptions
var parser *extargsparse.ExtArgsParse
var keycls *extargsparse.ExtKeyParse
options, err = extargsparse.NewExtArgsOptions(confstr)
if err == nil {
    parser, err = extargsparse.NewExtArgsParse(options, nil)
    if err == nil {
        err = parser.LoadCommandLineString(loads)
        if err == nil {
            keycls, err = parser.GetCmdKey("")
            if err == nil {
                fmt.Fprintf(os.Stdout, "cmdname=%s\n", keycls.CmdName()) // cmdname=main
                keycls, err = parser.GetCmdKey("dep")
                if err == nil {
                    fmt.Fprintf(os.Stdout, "cmdname=%s\n", keycls.CmdName()) // cmdname=dep
                    keycls, err = parser.GetCmdKey("rdep.ip")
                    if err == nil {
                        fmt.Fprintf(os.Stdout, "cmdname=%s\n", keycls.CmdName()) // cmdname=ip  it is the subcommand of subcommand rdep
                    }
                }
            }
        }
    }
}
return

func (*ExtArgsParse) GetCmdOpts Uses

func (self *ExtArgsParse) GetCmdOpts(cmdname string) ([]*ExtKeyParse, error)

GetCmdOpts return the cmdopts for all the ExtKeyParse for current command

cmdname is the top or the subcommand

Code:

var loads = `        {
        "verbose|v" : "+",
        "+http" : {
            "url|u" : "http://www.google.com",
            "visual_mode|V": false
        },
        "$port|p" : {
            "value" : 3000,
            "type" : "int",
            "nargs" : 1 ,
            "helpinfo" : "port to connect"
        },
        "dep" : {
            "list|l!attr=cc;optfunc=list_opt_func!" : [],
            "string|s" : "s_var",
            "$" : "+",
            "ip" : {
                "verbose" : "+",
                "list" : [],
                "cc" : []
            }
        },
        "rdep" : {
            "ip" : {
                "verbose" : "+",
                "list" : [],
                "cc" : []
            }
        }
    }`
var err error
var parser *extargsparse.ExtArgsParse
var options *extargsparse.ExtArgsOptions
var opts []*extargsparse.ExtKeyParse
var flag *extargsparse.ExtKeyParse
var i int
options, err = extargsparse.NewExtArgsOptions(fmt.Sprintf(`{"%s" : "cmd1"}`, extargsparse.OPT_PROG))
if err == nil {
    parser, err = extargsparse.NewExtArgsParse(options, nil)
    if err == nil {
        err = parser.LoadCommandLineString(fmt.Sprintf("%s", loads))
        if err == nil {
            opts, err = parser.GetCmdOpts("")
            if err == nil {
                fmt.Fprintf(os.Stdout, "main cmd opts:\n")
                for i, flag = range opts {
                    if flag.TypeName() == "args" {
                        fmt.Fprintf(os.Stdout, "[%d].type=args\n", i)
                    } else {
                        fmt.Fprintf(os.Stdout, "[%d].Longopt=%s;.Shortopt=%s;Optdest=%s;attr=%s\n", i, flag.Longopt(), flag.Shortopt(), flag.Optdest(), flag.Attr(""))
                    }
                }
                opts, err = parser.GetCmdOpts("dep")
                if err == nil {
                    fmt.Fprintf(os.Stdout, "dep cmd opts:\n")
                    for i, flag = range opts {
                        if flag.TypeName() == "args" {
                            fmt.Fprintf(os.Stdout, "[%d].type=args\n", i)
                        } else {
                            fmt.Fprintf(os.Stdout, "[%d].Longopt=%s;.Shortopt=%s;Optdest=%s;attr=%s\n", i, flag.Longopt(), flag.Shortopt(), flag.Optdest(), flag.Attr(""))
                        }
                    }

                    opts, err = parser.GetCmdOpts("rdep.ip")
                    if err == nil {
                        fmt.Fprintf(os.Stdout, "rdep.ip cmd opts:\n")
                        for i, flag = range opts {
                            if flag.TypeName() == "args" {
                                fmt.Fprintf(os.Stdout, "[%d].type=args\n", i)
                            } else {
                                fmt.Fprintf(os.Stdout, "[%d].Longopt=%s;.Shortopt=%s;Optdest=%s;attr=%s\n", i, flag.Longopt(), flag.Shortopt(), flag.Optdest(), flag.Attr(""))
                            }
                            /*
                            	Output:
                            	main cmd opts:
                            	[0].type=args
                            	[1].Longopt=--help;.Shortopt=-h;Optdest=help;attr=
                            	[2].Longopt=--json;.Shortopt=;Optdest=json;attr=
                            	[3].Longopt=--port;.Shortopt=-p;Optdest=port;attr=
                            	[4].Longopt=--http-url;.Shortopt=-u;Optdest=http_url;attr=
                            	[5].Longopt=--verbose;.Shortopt=-v;Optdest=verbose;attr=
                            	[6].Longopt=--http-visual-mode;.Shortopt=-V;Optdest=http_visual_mode;attr=
                            	dep cmd opts:
                            	[0].type=args
                            	[1].Longopt=--help;.Shortopt=-h;Optdest=help;attr=
                            	[2].Longopt=--dep-json;.Shortopt=;Optdest=dep_json;attr=
                            	[3].Longopt=--dep-list;.Shortopt=-l;Optdest=dep_list;attr=[attr]=[cc]
                            	[optfunc]=[list_opt_func]

                            	[4].Longopt=--dep-string;.Shortopt=-s;Optdest=dep_string;attr=
                            	rdep.ip cmd opts:
                            	[0].type=args
                            	[1].Longopt=--rdep-ip-cc;.Shortopt=;Optdest=rdep_ip_cc;attr=
                            	[2].Longopt=--help;.Shortopt=-h;Optdest=help;attr=
                            	[3].Longopt=--rdep-ip-json;.Shortopt=;Optdest=rdep_ip_json;attr=
                            	[4].Longopt=--rdep-ip-list;.Shortopt=;Optdest=rdep_ip_list;attr=
                            	[5].Longopt=--rdep-ip-verbose;.Shortopt=;Optdest=rdep_ip_verbose;attr=
                            */
                        }
                    }
                }
            }
        }
    }
}

return

Output:

									main cmd opts:
									[0].type=args
									[1].Longopt=--help;.Shortopt=-h;Optdest=help;attr=
									[2].Longopt=--json;.Shortopt=;Optdest=json;attr=
									[3].Longopt=--port;.Shortopt=-p;Optdest=port;attr=
									[4].Longopt=--http-url;.Shortopt=-u;Optdest=http_url;attr=
									[5].Longopt=--verbose;.Shortopt=-v;Optdest=verbose;attr=
									[6].Longopt=--http-visual-mode;.Shortopt=-V;Optdest=http_visual_mode;attr=
									dep cmd opts:
									[0].type=args
									[1].Longopt=--help;.Shortopt=-h;Optdest=help;attr=
									[2].Longopt=--dep-json;.Shortopt=;Optdest=dep_json;attr=
									[3].Longopt=--dep-list;.Shortopt=-l;Optdest=dep_list;attr=[attr]=[cc]
									[optfunc]=[list_opt_func]

									[4].Longopt=--dep-string;.Shortopt=-s;Optdest=dep_string;attr=
									rdep.ip cmd opts:
									[0].type=args
									[1].Longopt=--rdep-ip-cc;.Shortopt=;Optdest=rdep_ip_cc;attr=
									[2].Longopt=--help;.Shortopt=-h;Optdest=help;attr=
									[3].Longopt=--rdep-ip-json;.Shortopt=;Optdest=rdep_ip_json;attr=
									[4].Longopt=--rdep-ip-list;.Shortopt=;Optdest=rdep_ip_list;attr=
									[5].Longopt=--rdep-ip-verbose;.Shortopt=;Optdest=rdep_ip_verbose;attr=

func (*ExtArgsParse) GetSubCommands Uses

func (self *ExtArgsParse) GetSubCommands(name string) ([]string, error)

GetSubCommands to get the sub command for the job

Code:

var loads = `        {
        "dep" : {
            "ip" : {
            	"$" : "*"
            },
            "mip" : {
            	"$" : "*"
            }
        },
        "rdep" : {
            "ip" : {
            },
            "rmip" : {                	
            }
        }
    }`
var err error
var parser *extargsparse.ExtArgsParse
var options *extargsparse.ExtArgsOptions
var subcmds []string
options, err = extargsparse.NewExtArgsOptions(fmt.Sprintf(`{"%s" : "cmd1"}`, extargsparse.OPT_PROG))
if err == nil {
    parser, err = extargsparse.NewExtArgsParse(options, nil)
    if err == nil {
        err = parser.LoadCommandLineString(fmt.Sprintf("%s", loads))
        if err == nil {
            subcmds, err = parser.GetSubCommands("")
            if err == nil {
                fmt.Fprintf(os.Stdout, "main cmd subcmds:%v\n", subcmds)
                subcmds, err = parser.GetSubCommands("dep")
                if err == nil {
                    fmt.Fprintf(os.Stdout, "dep cmd subcmds:%v\n", subcmds)
                    subcmds, err = parser.GetSubCommands("rdep.ip")
                    if err == nil {
                        fmt.Fprintf(os.Stdout, "rdep.ip cmd subcmds:%v\n", subcmds)
                        /*
                        	Output:
                        	main cmd subcmds:[dep rdep]
                        	dep cmd subcmds:[ip mip]
                        	rdep.ip cmd subcmds:[]
                        */
                    }
                }
            }
        }
    }
}

return

Output:

								main cmd subcmds:[dep rdep]
								dep cmd subcmds:[ip mip]
								rdep.ip cmd subcmds:[]

func (*ExtArgsParse) LoadCommandLineString Uses

func (self *ExtArgsParse) LoadCommandLineString(s string) error

LoadCommandLineString load the json directive string

this string used as simple json file
"verbose|v"  : "+"             to specified the longopt verbose shortopt v and increment handle
"verbose|v##verbose mode##" : "+"  to add help information between ##(help information)##
"verbose|v!optparse=opt_func;opthelp=help_func!##verbose mode##" : "+" to specified with options now is support optparse and opthelp
opthelp : function return help information
optparse : function parse input ,more example see https://github.com/jeppeter/go-extargsparse/tree/master/example

func (*ExtArgsParse) ParseCommandLine Uses

func (self *ExtArgsParse) ParseCommandLine(params interface{}, Context interface{}) (ns *NameSpaceEx, err error)

ParseCommandLine parse the command line

params can be nil ,for the default os.Args[1:] or []string{} type
Context is the user defined parameter ,it will used in the callback function like
func sub_handler(ns *NameSpaceEx,ostruct {},Context interface{}) error

func (*ExtArgsParse) ParseCommandLineEx Uses

func (self *ExtArgsParse) ParseCommandLineEx(params interface{}, Context interface{}, ostruct interface{}, mode interface{}) (ns *NameSpaceEx, err error)

ParseCommandLineEx parse the command line

params can be nil ,for the default os.Args[1:] or []string{} type
Context is the user defined parameter ,it will used in the callback function like
ostruct is the used defined struct of NameSpaceEx ,the rule is in the https://github.com/jeppeter/go-extargsparse/blob/master/README.md
mode is the reserved for otheruse ,just put nil
more example see https://github.com/jeppeter/go-extargsparse/tree/master/example

func (*ExtArgsParse) PrintHelp Uses

func (self *ExtArgsParse) PrintHelp(out IoWriter, cmdname string) error

PrintHelp to call print out

out is the IoWriter interface , if use os.File call NewFileWriter(f *os.File) *FileIoWriter to get
cmdname is the cmd to display help information
example see https://github.com/jeppeter/go-extargsparse/blob/master/example/helpfunc/helpstr1.go

type ExtKeyParse Uses

type ExtKeyParse struct {
    // contains filtered or unexported fields
}

func (*ExtKeyParse) Attr Uses

func (self *ExtKeyParse) Attr(k string) string

Attr function

extension attribute for keycls ,it is more
example see https://github.com/jeppeter/go-extargsparse/blob/master/example/getopt/attrset1.go
no used options is : opthelp and optparse

func (*ExtKeyParse) CmdName Uses

func (self *ExtKeyParse) CmdName() string

CmdName is the command name

Code:

var loads = `{
		"dep" : {

		},
		"rdep": {

		}
	}`
var err error
var parser *extargsparse.ExtArgsParse
var options *extargsparse.ExtArgsOptions
var flag *extargsparse.ExtKeyParse
options, err = extargsparse.NewExtArgsOptions(fmt.Sprintf(`{}`))
if err == nil {
    parser, err = extargsparse.NewExtArgsParse(options, nil)
    if err == nil {
        err = parser.LoadCommandLineString(fmt.Sprintf("%s", loads))
        if err == nil {
            flag, _ = parser.GetCmdKey("")
            fmt.Fprintf(os.Stdout, "cmdname=%s\n", flag.CmdName())
            flag, _ = parser.GetCmdKey("dep")
            fmt.Fprintf(os.Stdout, "cmdname=%s\n", flag.CmdName())
            flag, _ = parser.GetCmdKey("rdep")
            fmt.Fprintf(os.Stdout, "cmdname=%s\n", flag.CmdName())
            /*
            	Output:
            	cmdname=main
            	cmdname=dep
            	cmdname=ip
            */

        }
    }
}

Output:

					cmdname=main
					cmdname=dep
					cmdname=ip

func (*ExtKeyParse) Equal Uses

func (self *ExtKeyParse) Equal(other *ExtKeyParse) bool

compare the ExtKeyParse ,it only for all the things are equaled

func (*ExtKeyParse) FlagName Uses

func (self *ExtKeyParse) FlagName() string

FlagName for the flag

Code:

var loads = `{
		"verbose|v" : "+",
		"dep" : {
			"cc|c" : ""
		},
		"rdep": {
			"dd|C" : ""
		}
	}`
var err error
var parser *extargsparse.ExtArgsParse
var options *extargsparse.ExtArgsOptions
var flag *extargsparse.ExtKeyParse
var opts []*extargsparse.ExtKeyParse
var finded bool
options, err = extargsparse.NewExtArgsOptions(fmt.Sprintf(`{}`))
if err == nil {
    parser, err = extargsparse.NewExtArgsParse(options, nil)
    if err == nil {
        err = parser.LoadCommandLineString(fmt.Sprintf("%s", loads))
        if err == nil {
            opts, _ = parser.GetCmdOpts("")
            for _, flag = range opts {
                if flag.FlagName() == "verbose" {
                    fmt.Fprintf(os.Stdout, "flagname=%s\n", flag.FlagName())
                }
            }

            opts, _ = parser.GetCmdOpts("dep")
            for _, flag = range opts {
                if flag.FlagName() == "cc" {
                    fmt.Fprintf(os.Stdout, "flagname=%s\n", flag.FlagName())
                }
            }
            opts, _ = parser.GetCmdOpts("rdep")
            for _, flag = range opts {
                if flag.FlagName() == "dd" {
                    fmt.Fprintf(os.Stdout, "flagname=%s\n", flag.FlagName())
                }
            }

            opts, _ = parser.GetCmdOpts("rdep")
            finded = false
            for _, flag = range opts {
                if flag.FlagName() == "cc" {
                    fmt.Fprintf(os.Stdout, "flagname=%s\n", flag.FlagName())
                    finded = true
                }
            }

            if !finded {
                fmt.Fprintf(os.Stdout, "can not found cc for rdep cmd\n")
            }

        }
    }
}
/*
	Output:
	flagname=verbose
	flagname=cc
	flagname=dd
	can not found cc for rdep cmd
*/

Output:

		flagname=verbose
		flagname=cc
		flagname=dd
		can not found cc for rdep cmd

func (*ExtKeyParse) Format Uses

func (self *ExtKeyParse) Format() string

Format is the debug function for output as string

func (*ExtKeyParse) Function Uses

func (self *ExtKeyParse) Function() string

Function is the function return for command

Code:

var loads = `{
		"verbose|v" : "+",
		"dep<dep_handler>" : {
			"cc|c" : ""
		},
		"rdep<rdep_handler>": {
			"dd|C" : ""
		}
	}`
var err error
var parser *extargsparse.ExtArgsParse
var options *extargsparse.ExtArgsOptions
var flag *extargsparse.ExtKeyParse
options, err = extargsparse.NewExtArgsOptions(fmt.Sprintf(`{}`))
if err == nil {
    parser, err = extargsparse.NewExtArgsParse(options, nil)
    if err == nil {
        err = parser.LoadCommandLineString(fmt.Sprintf("%s", loads))
        if err == nil {
            flag, _ = parser.GetCmdKey("")
            fmt.Fprintf(os.Stdout, "main funcion:%s\n", flag.Function())

            flag, _ = parser.GetCmdKey("dep")
            fmt.Fprintf(os.Stdout, "dep funcion:%s\n", flag.Function())

            flag, _ = parser.GetCmdKey("rdep")
            fmt.Fprintf(os.Stdout, "rdep funcion:%s\n", flag.Function())
        }
    }
}
/*
	Notice:
		if options not set fmt.Sprintf(`{"%s" : false}`,extargsparse.OPT_FUNC_UPPER_CASE)
		the real function is Dep_handler and Rdep_handler
	Output:
		main funcion:
		dep funcion:dep_handler
		rdep funcion:rdep_handler
*/

func (*ExtKeyParse) HelpInfo Uses

func (self *ExtKeyParse) HelpInfo() string

Code:

var loads = `{
		"verbose|v##we used verbose##" : "+",
		"$##this is args help##" : "*",
		"dep##dep help set##" : {
			"cc|c##cc sss##" : "",
			"$##this is dep subnargs help##" : "*"
		},
		"rdep##can not set rdep help##": {
			"dd|C##capital C##" : "",
			"$##this is rdep subnargs help##" : "*"
		}
	}`
var err error
var parser *extargsparse.ExtArgsParse
var options *extargsparse.ExtArgsOptions
var flag *extargsparse.ExtKeyParse
var opts []*extargsparse.ExtKeyParse
options, err = extargsparse.NewExtArgsOptions(fmt.Sprintf(`{}`))
if err == nil {
    parser, err = extargsparse.NewExtArgsParse(options, nil)
    if err == nil {
        err = parser.LoadCommandLineString(fmt.Sprintf("%s", loads))
        if err == nil {
            flag, _ = parser.GetCmdKey("")
            fmt.Fprintf(os.Stdout, "main helpinfo:%s\n", flag.HelpInfo())

            flag, _ = parser.GetCmdKey("dep")
            fmt.Fprintf(os.Stdout, "dep helpinfo:%s\n", flag.HelpInfo())

            flag, _ = parser.GetCmdKey("rdep")
            fmt.Fprintf(os.Stdout, "rdep helpinfo:%s\n", flag.HelpInfo())

            opts, _ = parser.GetCmdOpts("")
            for _, flag = range opts {
                if flag.TypeName() == "args" {
                    fmt.Fprintf(os.Stdout, "main.args.HelpInfo=%s\n", flag.HelpInfo())
                } else if flag.FlagName() == "verbose" {
                    fmt.Fprintf(os.Stdout, "verbose.HelpInfo=%s\n", flag.HelpInfo())
                }
            }
            opts, _ = parser.GetCmdOpts("dep")
            for _, flag = range opts {
                if flag.TypeName() == "args" {
                    fmt.Fprintf(os.Stdout, "dep.subnargs.HelpInfo=%s\n", flag.HelpInfo())
                } else if flag.FlagName() == "cc" {
                    fmt.Fprintf(os.Stdout, "dep.cc.HelpInfo=%s\n", flag.HelpInfo())
                }
            }
            opts, _ = parser.GetCmdOpts("rdep")
            for _, flag = range opts {
                if flag.TypeName() == "args" {
                    fmt.Fprintf(os.Stdout, "rdep.subnargs.HelpInfo=%s\n", flag.HelpInfo())
                } else if flag.FlagName() == "dd" {
                    fmt.Fprintf(os.Stdout, "rdep.dd.HelpInfo=%s\n", flag.HelpInfo())
                }
            }

        }
    }
}
/*
	Notice:
		HelpInfo is part of between ##(information)##
	Output:
		main helpinfo:
		dep helpinfo:dep help set
		rdep helpinfo:can not set rdep help
		main.args.HelpInfo=this is args help
		verbose.HelpInfo=we used verbose
		dep.subnargs.HelpInfo=this is dep subnargs help
		dep.cc.HelpInfo=cc sss
		rdep.subnargs.HelpInfo=this is rdep subnargs help
		rdep.dd.HelpInfo=capital C
*/

func (*ExtKeyParse) IsCmd Uses

func (self *ExtKeyParse) IsCmd() bool

IsCmd return whether this ExtKeyParse is cmd mode

func (*ExtKeyParse) IsFlag Uses

func (self *ExtKeyParse) IsFlag() bool

IsFlag return whether this ExtKeyParse is flag mode

func (*ExtKeyParse) LongPrefix Uses

func (self *ExtKeyParse) LongPrefix() string

LongPrefix this return the longprefix default is -- which setted by OPT_LONGPREFIX in NewExtArgsOptions json string

func (*ExtKeyParse) Longopt Uses

func (self *ExtKeyParse) Longopt() string

Longopt long option in the flag , this determined by flagname,command,prefix,longprefix

Code:

var loads = `{
		"verbose|v" : "+",
		"dep<dep_handler>" : {
			"cc|c" : ""
		},
		"rdep<rdep_handler>": {
			"dd|C" : ""
		}
	}`
var confstr string
var parser *extargsparse.ExtArgsParse
var options *extargsparse.ExtArgsOptions
var flag *extargsparse.ExtKeyParse
var opts []*extargsparse.ExtKeyParse
confstr = `{}`
options, _ = extargsparse.NewExtArgsOptions(confstr)
parser, _ = extargsparse.NewExtArgsParse(options, nil)
parser.LoadCommandLineString(fmt.Sprintf("%s", loads))
opts, _ = parser.GetCmdOpts("")
for _, flag = range opts {
    if flag.TypeName() == "count" && flag.FlagName() == "verbose" {
        fmt.Fprintf(os.Stdout, "longprefix=%s\n", flag.LongPrefix())
        fmt.Fprintf(os.Stdout, "longopt=%s\n", flag.Longopt())
        fmt.Fprintf(os.Stdout, "shortopt=%s\n", flag.Shortopt())
    }
}

confstr = fmt.Sprintf(`{ "%s" : "++", "%s" : "+"}`, extargsparse.OPT_LONG_PREFIX, extargsparse.OPT_SHORT_PREFIX)
options, _ = extargsparse.NewExtArgsOptions(confstr)
parser, _ = extargsparse.NewExtArgsParse(options, nil)
parser.LoadCommandLineString(fmt.Sprintf("%s", loads))
opts, _ = parser.GetCmdOpts("")
for _, flag = range opts {
    if flag.TypeName() == "count" && flag.FlagName() == "verbose" {
        fmt.Fprintf(os.Stdout, "longprefix=%s\n", flag.LongPrefix())
        fmt.Fprintf(os.Stdout, "longopt=%s\n", flag.Longopt())
        fmt.Fprintf(os.Stdout, "shortopt=%s\n", flag.Shortopt())
    }
}

/*
	Output:
		longprefix=--
		longopt=--verbose
		shortopt=-v
		longprefix=++
		longopt=++verbose
		shortopt=+v
*/

Output:

			longprefix=--
			longopt=--verbose
			shortopt=-v
			longprefix=++
			longopt=++verbose
			shortopt=+v

func (*ExtKeyParse) Nargs Uses

func (self *ExtKeyParse) Nargs() interface{}

Nargs return string or int ,determined by whether it is args or simple flag

if it is args type ,it will give the string or int value
if it is simple flag ,it will give the int value ,default is
       typename               number
       count                  0
       int                    1
       float                  1
       list                   1
       string                 1
       help                   0
       jsonfile               1
       bool                   0

Code:

var loads = `{
		"verbose|v" : "+",
		"dep<dep_handler>" : {
			"cc|c" : "",
			"$" : "+"
		},
		"rdep<rdep_handler>": {
			"dd|C" : "",
			"$" : "?"
		},
		"$port" : {
			"nargs" : 1,
			"type" : "int",
			"value" : 9000
		}
	}`
var confstr string
var parser *extargsparse.ExtArgsParse
var options *extargsparse.ExtArgsOptions
var flag *extargsparse.ExtKeyParse
var opts []*extargsparse.ExtKeyParse
confstr = `{}`
options, _ = extargsparse.NewExtArgsOptions(confstr)
parser, _ = extargsparse.NewExtArgsParse(options, nil)
parser.LoadCommandLineString(fmt.Sprintf("%s", loads))
opts, _ = parser.GetCmdOpts("")
for _, flag = range opts {
    if flag.TypeName() == "args" {
        fmt.Fprintf(os.Stdout, "args.nargs=%v\n", flag.Nargs())
    } else if flag.FlagName() == "port" {
        fmt.Fprintf(os.Stdout, "port.nargs=%d\n", flag.Nargs().(int))
    }
}

opts, _ = parser.GetCmdOpts("dep")
for _, flag = range opts {
    if flag.TypeName() == "args" {
        fmt.Fprintf(os.Stdout, "dep.args.nargs=%v\n", flag.Nargs())
    }
}
opts, _ = parser.GetCmdOpts("rdep")
for _, flag = range opts {
    if flag.TypeName() == "args" {
        fmt.Fprintf(os.Stdout, "rdep.args.nargs=%v\n", flag.Nargs())
    }
}
/*
	Output:
		args.nargs=*
		port.nargs=1
		dep.args.nargs=+
		rdep.args.nargs=?
*/

Output:

			args.nargs=*
			port.nargs=1
			dep.args.nargs=+
			rdep.args.nargs=?

func (*ExtKeyParse) Optdest Uses

func (self *ExtKeyParse) Optdest() string

func (*ExtKeyParse) Prefix Uses

func (self *ExtKeyParse) Prefix() string

func (*ExtKeyParse) ShortFlag Uses

func (self *ExtKeyParse) ShortFlag() string

func (*ExtKeyParse) ShortPrefix Uses

func (self *ExtKeyParse) ShortPrefix() string

ShortPrefix this return the shortprefix default is - set by OPT_SHORTPREFIX

func (*ExtKeyParse) Shortopt Uses

func (self *ExtKeyParse) Shortopt() string

Shortopt short option in the flag , this determined by shortflag,shortprefix

func (*ExtKeyParse) TypeName Uses

func (self *ExtKeyParse) TypeName() string

TypeName type of the flag

value can be 9 ,and only 6 set by user
typename            value type
bool                false/true
int                 int
float               float64
list                []string
string              string
count               int (only added by one with each)
help                inner define ,for help display
jsonfile            inner define ,for json set value
args                []string (with no other parameters)

func (*ExtKeyParse) Value Uses

func (self *ExtKeyParse) Value() interface{}

Value default value for the flag , it is defined at the value of json

func (*ExtKeyParse) VarName Uses

func (self *ExtKeyParse) VarName() string

VarName variable name this is used for the Struct defined

example see https://github.com/jeppeter/go-extargsparse/blob/master/example/getopt/varname1.go

type FileIoWriter Uses

type FileIoWriter struct {
    IoWriter
    // contains filtered or unexported fields
}

func NewFileWriter Uses

func NewFileWriter(f *os.File) *FileIoWriter

it is called by PrintHelp

example see https://github.com/jeppeter/go-extargsparse/blob/master/example/helpfunc/filehelp.go

func (*FileIoWriter) Write Uses

func (self *FileIoWriter) Write(data []byte) (int, error)

func (*FileIoWriter) WriteString Uses

func (self *FileIoWriter) WriteString(s string) (int, error)

type IoWriter Uses

type IoWriter interface {
    Write(data []byte) (int, error)
    WriteString(s string) (int, error)
}

IoWriter is the interface for PrintHelp

extended example see https://github.com/jeppeter/go-extargsparse/blob/master/example/helpfunc/helpstr1.go

type NameSpaceEx Uses

type NameSpaceEx struct {
    // contains filtered or unexported fields
}

NameSpaceEx structure to store the parse command line result

use multifunction to get the coding

func (*NameSpaceEx) Format Uses

func (self *NameSpaceEx) Format() string

Format return string with all keys set like format {key1=val1;key2=value2;...;keyn=valn}

func (*NameSpaceEx) GetArray Uses

func (self *NameSpaceEx) GetArray(k string) []string

GetArray return []string, default []string{} on no key set or not type of []string

func (*NameSpaceEx) GetBool Uses

func (self *NameSpaceEx) GetBool(k string) bool

GetBool return true/false value ,no key or not the type return false

func (*NameSpaceEx) GetFloat Uses

func (self *NameSpaceEx) GetFloat(k string) float64

GetFloat return type of float64 ,default 0.0 on no key set or not type of float64

func (*NameSpaceEx) GetInt Uses

func (self *NameSpaceEx) GetInt(k string) int

GetInt return int type , default 0 on nokey or not type of int

func (*NameSpaceEx) GetKeys Uses

func (self *NameSpaceEx) GetKeys() []string

GetKeys get all available keys for setted sorted by alphabet value

func (*NameSpaceEx) GetString Uses

func (self *NameSpaceEx) GetString(k string) string

GetString return string type ,default "" on no key or not type of string

func (*NameSpaceEx) GetValue Uses

func (self *NameSpaceEx) GetValue(k string) interface{}

GetValue return interface{} if not set return nil

func (*NameSpaceEx) IsAccessed Uses

func (self *NameSpaceEx) IsAccessed(k string) bool

IsAccessed return whether the key has been setted

func (*NameSpaceEx) SetValue Uses

func (self *NameSpaceEx) SetValue(k string, v interface{})

SetValue to set value

Directories

PathSynopsis
releasechk

Package extargsparse imports 12 packages (graph). Updated 2018-09-26. Refresh now. Tools for package owners.