optionparser

package module
v1.0.5 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2022 License: MIT Imports: 7 Imported by: 8 modules, 8 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

GoDoc

optionparser

Ruby (OptionParser) like command line arguments processor.

Installation

go get github.com/mmpx12/optionparser

Usage

op := optionparser.NewOptionParser()
op.On(arguments ...interface{})
...
err := op.Parse()

where arguments is one of:

  • "-a": a short argument
  • "--argument": a long argument
  • "--argument [FOO]" a long argument with an optional parameter
  • "--argument FOO" a long argument with a mandatory parameter
  • "Some text": The description text for the command line parameter
  • &aboolean: Set the given boolean to true if the argument is given, set to false if parameter is prefixed with no-, such as --no-foo.
  • &astring: Set the string to the value of the given parameter
  • function: Call the function. The function must have the signature func().
  • amap[string]string: Set an entry of the map to the value of the given parameter and the key of the argument.

Help usage

The options -h and --help are included by default. The example below output this on cmd -h:

Usage: [parameter] command
-h, --help                   Show this help
-a, --func                   call myfunc
    --bstring=FOO            set string to FOO
-c                           set boolean option (try -no-c)
-d, --dlong=VAL              set option
-e, --elong[=VAL]            set option with optional parameter
-f                           boolean option

Commands
      y                      Run command y
      z                      Run command z

Exemples:
  go run main.go -a --bstring foo -c -d somevalue -e x -f y z
  go run main.go --help
  
Output:
  Exemple of output

Settings

After calling op := optionparser.NewOptionParser() you can set op.Banner to set the first line of the help output. The default value is Usage: [parameter] command.

To control the first and last column of the help output, set op.Start and op.Stop. The default values are the integer values of 30 and 79.

Example usage

package main

import (
    "fmt"
    "log"

    "github.com/mmpx12/optionparser"
)

func myfunc() {
    fmt.Println("myfunc called")
}

func main() {
    var somestring string
    var truefalse, nologo bool
    options := make(map[string]string)

    op := optionparser.NewOptionParser()
    op.On("-a", "--func", "call myfunc", myfunc)
    op.On("--bstring FOO", "set string to FOO", &somestring)
    op.On("-c", "set boolean option (try -no-c)", options)
    op.On("-d", "--dlong VAL", "set option", options)
    op.On("-e", "--elong [VAL]", "set option with optional parameter", options)
    op.On("-f", "boolean option", &truefalse)
    op.On("--nologo", "Don't print banner", &nologo)
    op.Command("y", "Run command y")
    op.Command("z", "Run command z")
    op.Exemple("go run main.go -a --bstring foo -c -d somevalue -e x -f y z")
    op.Exemple("go run main.go --help")
    op.Output("Exemple of output")

    err := op.Parse()
    if err != nil {
        log.Fatal(err)
    }
    op.Logo("main", "random", nologo)
    fmt.Printf("string `somestring' is now %q\n", somestring)
    fmt.Printf("options %v\n", options)
    fmt.Printf("-f %v\n", truefalse)
    fmt.Printf("Extra: %#v\n", op.Extra)
}

and the output of go run main.go -a --bstring foo --nologo -c -d somevalue -e x -f y z

is:

                       d8b
                       Y8P

88888b.d88b.   8888b.  888 88888b.
888 "888 "88b     "88b 888 888 "88b
888  888  888 .d888888 888 888  888
888  888  888 888  888 888 888  888
888  888  888 "Y888888 888 888  888


myfunc called
string `somestring' is now "foo"
options map[c:true dlong:somevalue elong:x]
-f true
Extra: []string{"y", "z"}

You can hide the ascii logo with "--nologo"

go run main.go -a --bstring foo -c -d somevalue -e x -f y z

string `somestring' is now ""
options map[]
-f false
Extra: []string{}

State: Actively maintained, and used in production. Without warranty, of course.
Maturity level: 5/5 (works well in all tested repositories, there will be no API change)
License: Free software (MIT License)
Installation: Just run go get github.com/mmpx12/optionparser
API documentation: https://godoc.org/github.com/mmpx12/optionparser
Contact: gundlach@speedata.de, @speedata
Repository: https://github.com/mmpx12/optionparser
Dependencies: None
Contribution: We like to get any kind of feedback (success stories, bug reports, merge requests, ...)

Documentation

Overview

Package optionparser is a library for defining and parsing command line options. It aims to provide a natural language interface for defining short and long parameters and mandatory and optional arguments. It provides the user for nice output formatting on the built in method '--help'.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type OptionParser

type OptionParser struct {
	Extra  []string
	Banner string
	Start  int
	Stop   int
	// contains filtered or unexported fields
}

OptionParser contains the methods to parse options and the settings to influence the output of --help. Set the Banner for usage info, set Start and Stop for output of the long description text.

func NewOptionParser

func NewOptionParser() *OptionParser

NewOptionParser initializes the OptionParser struct with sane settings for Banner, Start and Stop and adds a "-h", "--help" option for convenience.

func (*OptionParser) Command

func (op *OptionParser) Command(cmd string, helptext string)

Command defines optional arguments to the command line. These are written in a separate section called 'Commands' on --help.

func (*OptionParser) Exemple added in v1.0.1

func (op *OptionParser) Exemple(ex string)

Exemple is an optianal function that will print exemple(s) when using `-h` or `--help` flag.

func (*OptionParser) Help

func (op *OptionParser) Help()

Help prints help text generated from the "On" commands

func (op *OptionParser) Logo(name string, font string, nobanner bool)

Ascii art Program name First parameter is the program name Seccond parameter is the font name. If random is passed it will choose a ransom font Third parameter is for print the banner or not This function msut be used AFTER op.Parse()

func (*OptionParser) On

func (op *OptionParser) On(a ...interface{})

On defines arguments and parameters. Each argument is one of: a short option, such as "-x", a long option, such as "--extra", a long option with an argument such as "--extra FOO" (or "--extra=FOO") for a mandatory argument, a long option with an argument in brackets, e.g. "--extra [FOO]" for a parameter with optional argument, a string (not starting with "-") used for the parameter description, e.g. "This parameter does this and that", a string variable in the form of &str that is used for saving the result of the argument, a variable of type map[string]string which is used to store the result (the parameter name is the key, the value is either the string true or the argument given on the command line) a bool variable (in the form &bool) to hold a boolean value, or a function in the form of func() or in the form of func(string) which gets called if the command line parameter is found.

On panics if the user supplies is an type in its argument other the ones given above.

op := optionparser.NewOptionParser()
op.Banner = "main.go usage:"
op.On("-a", "--func", "call myfunc", myfunc)
op.On("--bstring FOO", "set string to FOO", &somestring)
op.On("-c", "set boolean option (try -no-c)", options)
op.On("-d", "--dlong VAL", "set option", options)
op.On("-e", "--elong [VAL]", "set option with optional parameter", options)
op.On("-f", "boolean option", &truefalse)
op.Exemple("go run main.go -d VALUE")
op.Exemple("go run main.go -e VALUE -a")
op.Output("exemple of program output")

and running the program with --help gives the following output:

$go run main.go --help
   main.go usage:
   -h, --help                   Show this help
   -a, --func                   call myfunc
       --bstring=FOO            set string to FOO
   -c                           set boolean option (try -no-c)
   -d, --dlong=VAL              set option
   -e, --elong[=VAL]            set option with optional parameter
   -f                           boolean option

 Exemples:
   go run main.go -d VALUE
   go run main.go -d VALUE -e VALUE

 Output:
   exemple of program output

func (*OptionParser) Output added in v1.0.2

func (op *OptionParser) Output(output string)

Output is an optianal function that will print exemple of the output when using `-h` or `--help` flag.

func (*OptionParser) Parse

func (op *OptionParser) Parse() error

Parse takes the command line arguments as found in os.Args and interprets them. If it finds an unknown option or a missing mandatory argument, it returns an error.

Jump to

Keyboard shortcuts

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