Пример #1
0
	Describe("args.ParseArgs(nil)", func() {
		parser := args.Parser()
		It("Should return error if Opt() was never called", func() {
			_, err := parser.ParseArgs(nil)
			Expect(err).ToNot(BeNil())
			Expect(err.Error()).To(Equal("Must create some options to match with args.Opt() before calling arg.ParseArgs()"))
		})
	})

	Describe("args.Opt()", func() {
		cmdLine := []string{"--one", "-two", "++three", "+four", "--power-level"}

		It("Should create optional rule --one", func() {
			parser := args.Parser()
			parser.Opt("--one", args.Count())
			rule := parser.GetRules()[0]
			Expect(rule.Name).To(Equal("one"))
			Expect(rule.IsPos).To(Equal(0))
		})

		It("Should create optional rule ++one", func() {
			parser := args.Parser()
			parser.Opt("++one", args.Count())
			rule := parser.GetRules()[0]
			Expect(rule.Name).To(Equal("one"))
			Expect(rule.IsPos).To(Equal(0))
		})

		It("Should create optional rule -one", func() {
			parser := args.Parser()
Пример #2
0
func main() {
	var conf Config

	//parser := args.Parser(args.WarnUnknownArgs(), args.UsageName("my-program"))
	parser := args.Parser()

	// Positional Argument, there can be more than one argument and the result will be an array
	parser.Pos("count", args.Append(), args.IsInt(), args.Help("Count the numbers provided"))

	// Optional Positional Argument, the order the positional arguments are
	// defined is the order they are expected on the command line
	parser.Pos("infile", args.Optional(), args.IsString(), args.Help("Output file, If none supplied reads from stdin"))
	parser.Pos("outfile", args.Optional(), args.IsString(), args.Help("Input file, If none supplied writes to stdout"))

	// Counts the number of instances a flag is seen and stores the count as an integer
	parser.Opt("--verbose", args.Alias("-v"), args.Count(),
		args.Help("Prints Stuff and things"))

	// String with default option and Environment option (VarName defines the help message value name)
	parser.Opt("--bind", args.Alias("-b"), args.IsString(), args.VarName("ADDRESS"), args.Default("localhost:8080"),
		args.Env("BIND_ADDRESS"), args.Store(&conf.Bind), args.Help("The network interface to bind too"))

	// Unusual option indicators
	parser.Opt("++unusual", args.Alias("+u"), args.IsBool(), args.Default(false),
		args.Help("Unusual option indicator"))
	parser.Opt("-short", args.Alias("-s"), args.IsBool(), args.Default(false),
		args.Help("Short option indicator"))

	// Booleans
	parser.Opt("--debug", args.Alias("-d"), args.IsBool(), args.Default(false),
		args.Help("Turns on debug messages"))

	// Append stores an array, and appends each argument value to the array. This allows an option to be specified multiple times.
	parser.Opt("--endpoint", args.Alias("-e"), args.Append(), args.IsString(),
		args.Default([]string{"http://google.com"}), args.Help("The endpoints to proxy for"))

	// Take an option and split the arguments IE: --terms one,two,three
	parser.Opt("--terms", args.Alias("-t"), args.Array(), args.IsString(),
		args.Default([]string{"foo", "bar"}), args.Help("The terms used to search google with"))

	// Give the user choices
	parser.Opt("--choice", args.Alias("-c"), args.Choice(), args.IsInt(),
		args.Default([]int{1, 2, 3}), args.Help("You can only choose 1,2 or 3"))

	// Give the option is required (Required options can not have defaults)
	parser.Opt("--required", args.Alias("-r"), args.Required(), args.IsString(),
		args.Help("This option is required"))

	// Display Help
	parser.Opt("--help", args.Alias("-h"), args.IsBool(), args.Help("Display this help message"))

	//opts, err := parser.ParseArgs([]string{"-p", "-vvv"})
	opts, err := parser.Parse()
	if err != nil {
		fmt.Println("-- %s", err.Error())
		opts.PrintUsage()
		os.Exit(-1)
	}

	// If user asked for --help or there were no options passed
	if opts.NoArgs() && opts.Bool("help") {
		opts.PrintHelp()
		os.Exit(-1)
	}

	fmt.Printf("Bind Address from opts: %s", opts.String("bind"))
	fmt.Printf("Bind Address from Config struct: %s", conf.Bind)

	fmt.Printf("Verbose Count: %d", opts.Int("verbose"))
	fmt.Printf("Debug Boolean: %b", opts.Bool("debug"))

	for _, endpoint := range opts.Array("endpoint").([]string) {
		fmt.Println("Endpoint: %s", endpoint)
	}

	// Parent that provides shared options
	parent := args.Parser()
	parent.Opt("verbose", args.Alias("-v"), args.Count(), args.Help("Be verbose"))

	// Sub Parser, Any arguments past the positional arg 'sub1' will be considered by this sub
	sub := parser.SubParser("volume")

	// parser and will inherit all the opts from the parent parser
	list := sub.SubParser("list", args.Inherit(parent))

	list.Opt("filter", args.Alias("-f"), args.IsBool(), args.Help("Filter the list by this thingy"))

}
Пример #3
0
func main() {
	var conf Config

	// Create the parser
	parser := args.Parser(args.Name("example"))

	// Store Integers directly into a struct with a default value
	parser.Opt("--power-level", args.Alias("-p"), args.StoreInt(&conf.PowerLevel),
		args.Env("POWER_LEVEL"), args.Default("10000"), args.Help("set our power level"))

	// Options can begin with -name, --name or even ++name. Most alpha non word character are supported
	parser.Opt("++power", args.Alias("+p"), args.IsString(), args.Default("11,000"),
		args.Help("prefix demo"))

	// Use the args.Env() function to define an environment variable
	parser.Opt("--message", args.Alias("-m"), args.StoreStr(&conf.Message),
		args.Env("MESSAGE"), args.Default("over-ten-thousand"), args.Help("send a message"))

	// Pass a comma seperated list of strings and get a []string
	parser.Opt("--slice", args.Alias("-s"), args.StoreSlice(&conf.Slice),
		args.Env("LIST"), args.Default("one,two,three"), args.Help("list of messages"))

	// Count the number of times an argument is seen
	parser.Opt("--verbose", args.Alias("-v"), args.Count(), args.StoreInt(&conf.Verbose),
		args.Help("be verbose"))

	// Set bool to true if the argument is present on the command line
	parser.Opt("--debug", args.Alias("-d"), args.IsTrue(), args.Help("turn on Debug"))

	// Specify the type of the arg with IsInt(), IsString(), IsBool() or IsTrue()
	parser.Opt("--help", args.Alias("-h"), args.IsTrue(), args.Help("show this help message"))

	// Pass our own argument list, or nil to parse os.Args[]
	opt, err := parser.ParseArgs(nil)
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(-1)
	}

	// Fetch values by using the Cast functions
	fmt.Printf("CAST Power     '%d'\n", opt.Int("power-level"))
	fmt.Printf("CAST Message   '%s'\n", opt.String("message"))
	fmt.Printf("CAST Slice     '%s'\n", opt.Slice("slice"))
	fmt.Printf("CAST Verbose   '%d'\n", opt.Int("verbose"))
	fmt.Printf("CAST Debug     '%t'\n", opt.Bool("debug"))
	fmt.Println("")

	// Values can also be stored in a struct
	fmt.Printf("STRUCT Power   '%d'\n", conf.PowerLevel)
	fmt.Printf("STRUCT Message '%s'\n", conf.Message)
	fmt.Printf("STRUCT Slice   '%s'\n", conf.Slice)
	fmt.Printf("STRUCT Verbose '%d'\n", conf.Verbose)
	fmt.Printf("STRUCT Debug   '%t'\n", opt.Bool("debug"))
	fmt.Println("")

	iniFile := []byte(`
		power-level=20000
		message=OVER-THEN-THOUSAND!
		slice=three,four,five,six
		verbose=5
		debug=true
    `)

	// Make configuration simply by reading arguments from an INI file
	opt, err = parser.ParseIni(iniFile)
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(-1)
	}

	// Values from the config file are used only if the argument is not present
	// on the commandline
	fmt.Printf("INI Power      '%d'\n", conf.PowerLevel)
	fmt.Printf("INI Message    '%s'\n", conf.Message)
	fmt.Printf("INI Slice      '%s'\n", conf.Slice)
	fmt.Printf("INI Verbose    '%d'\n", conf.Verbose)
	fmt.Printf("INI Debug      '%t'\n", opt.Bool("debug"))
	fmt.Println("")

	// If user asked for --help or there were no options passed
	if opt.NoArgs() || opt.Bool("help") {
		parser.PrintHelp()
		os.Exit(-1)
	}
}