args

package module
v0.0.0-...-76b6730 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 13, 2015 License: MIT Imports: 6 Imported by: 0

README

args

An experimental argument parser for go.

This is a small project that I used to teach myself the details of Go's reflect package. While I have done other work with Go's reflect package, I wanted a sandbox project for experimenting with the reflect package's techniques.

The basic idea here is to create a struct that has the arguments you wish to accept for a command-line program. args.Parse() then takes the struct as an argument, and tries to match arguments from the command line.

Unlike the flag package, args is a GNU-style argument parser.

Errors try to be sensible but are not well tested.

Some options can be supplied via struct tags. (See eg/main.go)

Documentation: https://godoc.org/github.com/echlebek/args

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Parse

func Parse(strukt interface{}) error

Parse parses command-line arguments.

Parse can fill three different types with command-line data:

  • struct
  • map[string]interface{}
  • []interface{} (typically equivalent to os.Args[1:])

If another type is given, an error is returned.

The main use case is struct. Example:

import (
	"fmt"
	"github.com/echlebek/args"
	"os"
)

type Args struct {
	Foo int     `args:"this is a foo,-f"` // Foo has a short flag, -f
	Bar float32 `args:"this is a bar,r"`  // Bar is required
	Baz string  `args:"a baz!,r"`         // Baz is required too
}

var defaultArgs = Args{Foo: 5}

const progDesc = "A mock program"

func main() {
	a := defaultArgs

	if err := args.Parse(&a); err != nil {
		fmt.Errorf("%s\n", err)
		if err := args.Usage(os.Stdout, defaultArgs, progDesc); err != nil {
			fmt.Errorf("%s\n", err)
		}
		return
	}

	fmt.Printf("%+v\n", a)
}

$ ./main --foo 5 --bar 3.5 --baz asdf

{Foo:5 Bar:3.5 Baz:asdf}

func Usage

func Usage(w io.Writer, strukt interface{}) error

Usage writes the usage for a user program to w.

The strukt value should specify the defaults for the user program.

Here is an example of an args spec that takes three arguments, with one argument having a default. The other two are missing if not supplied.

type Args struct {
	A *int
	B *string
	C float32
}

func showUsage() {
	defaults := Args{C: 0.2}
	if err := args.Usage(os.Stderr, defaults); err != nil {
		log.Fatal(err)
	}
}

A non-pointer struct value will always have a default. If not specified, it will be the zero value for the type.

Pointer values cannot have defaults.

Types

type Positionals

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

Embed Positionals in your args struct to specify positional arguments. TODO

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL