option: github.com/mkmueller/option Index | Examples | Files

package option

import "github.com/mkmueller/option"

Package option is a command line option and argument parser that will populate a given struct, argument slice, or both. Unix-style keys as well as gnu-style long keywords are accepted. Command line keys are automatically generated based on each struct field name and data type. optional help text may be supplied using a tag for each struct field. Additionally, option keys may be customized using the struct field tags.

All other command line arguments that are not defined in your option struct will be interpreted as regular arguments and appended to your argument slice. The number of arguments accepted by the parser may be limited by simply making your argument slice with a maximum cap value. If the user exceeds this cap, an error will be returned. Alternatively, a fixed array may be defined. This will cause the parser to expect an exact number of aguments, or return an error.

Index

Examples

Package Files

decode.go help.go option.go

type Option Uses

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

func New Uses

func New(v2 ...interface{}) (*Option, error)

Create a new option object struct.

The following example shows a simple option definition

Code:

// Set command line arguments for testing
oldArgs := os.Args
os.Args = []string{"mycommand", "-a", "42", "-b", "-q", "What?", "Towel"}

// Define options
var opt struct {
    Answer   int
    Babel    bool
    Question string
}

// Define argument slice
var args []string

// Create a new command line object
op, err := option.New(&opt, &args)
if err != nil {
    log.Println(err)
    return
}

fmt.Printf("%s\n", op.Cmd())
fmt.Printf("%d\n", opt.Answer)
fmt.Printf("%v\n", opt.Babel)
fmt.Printf("%s\n", opt.Question)
fmt.Printf("%v %v\n", len(args), args[0])
os.Args = oldArgs

Output:

mycommand
42
true
What?
1 Towel

func (*Option) Cmd Uses

func (o *Option) Cmd() string

Returns the path of this executable (os.Args[0])

func (*Option) HasArgs Uses

func (o *Option) HasArgs() bool

HasArgs will return true if any flag, option or argument was supplied.

func (*Option) Help Uses

func (o *Option) Help()

Print the entire help text for this option configuration.

The following example shows a simple option definition

Code:

// Set command line arguments for testing
oldArgs := os.Args
os.Args = []string{"mycommand"}

// Define options
var opt struct {
    Answer   int
    Babel    bool
    Question string
}

// Define argument slice
var args []string

// Create a new command line object
op, err := option.New(&opt, &args)
if err != nil {
    log.Println(err)
    return
}

// Print help text
op.Help()
os.Args = oldArgs

Output:

SYNOPSIS
    mycommand [OPTIONS] [string]...

OPTIONS
    -a int, --answer=int

    -b, --babel

    -q string, --question=string

Defining struct tags will allow you to add help text or optionally change key names.

Code:

// Set command line arguments for testing
oldArgs := os.Args
os.Args = []string{"mycommand"}

// Define options with tags with key name changes
var opt struct {
    Answer   int    `I:Supply your answer`
    Babel    bool   `translate:Enable bable fish translator`
    Question string `a:ask:question:Ask the ultimate question`
}

// Create a new command line object
op, err := option.New(&opt)
if err != nil {
    log.Println(err)
    return
}

// Print help text
op.Help()
os.Args = oldArgs

Output:

SYNOPSIS
    mycommand [OPTIONS]

OPTIONS
    -I int      Supply your answer

    --translate Enable bable fish translator

    -a question, --ask=question
                Ask the ultimate question

func (*Option) HelpString Uses

func (o *Option) HelpString() string

Return the entire help text for this option configuration as a string.

func (*Option) Section Uses

func (o *Option) Section(heading string, paragraph ...string)

Add section heading and paragraphs to your help text

Add sections to help text

Code:

// Set command line arguments for testing
oldArgs := os.Args
os.Args = []string{"mycommand"}

// Define option struct with tags
var opt struct {
    Answer   int    `I:Supply your answer`
    Babel    bool   `translate:Enable bable fish translator`
    Question string `a:ask:question:Ask the ultimate question`
}

// Define argument slice
var args []string

// Create a new command line object
op, err := option.New(&opt, &args)
if err != nil {
    log.Println(err)
    return
}

// Name and description sections will be placed at top of help text
op.Section("NAME", "Hitchhiker Ipsum")
op.Section("DESCRIPTION", "Lorem Ipsum Hitchhiker simply generating "+
    "synthesized improbability drive closes world sector satisfaction "+
    "secretively reasoning ship launch physicists accident with science.")

// Section with option keyword will be inserted before the option
op.Section("translate:BABLE FISH TRANSLATOR", "Babel Fish patterns exist else "+
    "communication decode centers which killed brainwave "+
    "kidneys prove logic combining best refused.")

// Normal section will be placed after option list
op.Section("NOTES", "Stolen whim bizarrely speech have evolved small zebra "+
    "supplied coincidence Deep Thought chosen history nothing purely "+
    "we'll prove.")

// Print help text
op.Help()
os.Args = oldArgs

Output:

NAME
    Hitchhiker Ipsum

SYNOPSIS
    mycommand [OPTIONS] [string]...

DESCRIPTION
    Lorem Ipsum Hitchhiker simply generating synthesized improbability drive
    closes world sector satisfaction secretively reasoning ship launch
    physicists accident with science.

OPTIONS
    -I int      Supply your answer

BABLE FISH TRANSLATOR
    Babel Fish patterns exist else communication decode centers which killed
    brainwave kidneys prove logic combining best refused.

    --translate Enable bable fish translator

    -a question, --ask=question
                Ask the ultimate question

NOTES
    Stolen whim bizarrely speech have evolved small zebra supplied coincidence
    Deep Thought chosen history nothing purely we'll prove.

func (*Option) Usage Uses

func (o *Option) Usage()

Print the usage text for this command

Package option imports 8 packages (graph). Updated 2018-07-06. Refresh now. Tools for package owners.