mopt

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Feb 17, 2022 License: MIT Imports: 2 Imported by: 1

README

mopt

a minimalistic Go "flag" substitute that parses cmdline in the getopt style

import "github.com/ohir/mopt"

Package mopt provides command arguments parsing in 90 lines of Go.

It is ready to use right after declaring a single mopt.Usage type variable optionally containing usage text to be printed with an '-h' flag. For just a single option a single line with Usage literal is all you need:

niter := mopt.Usage("-n iterations, default: 9").OptN('n', 9)

For more options declare Usage string variable, eg:

var cl mopt.Usage = "\t-n iterations\n\t-v verbose\n ..."

then you may use its five option read methods:

  • cl.OptB('x') bool tells if '-x' flag is present. Its ok to ask for any type flag presence.
  • cl.OptN('x', def·int) int returns '-x ±digits' as an int, or the default int.
  • cl.OptF('x', def·float) float64 returns '-x ±digits' as a float64, or the default float.
  • cl.OptS('x', "default string") string returns text of '-x text', or the default string.
  • cl.OptL() []string returns slice of arguments following the last option or terminating '--'.

Spaces between flag letter and value are unimportant: ie. -a bc, and -abc are equivalent. Same for numbers: -n-3 and -n -3 both provide -3 number. For this elasticity a leading dash of string value, if needed, must be given after a backslash: eg. -s\-dashed or -s "\- started with a dash". Flag grouping is not supported, too. Ie. -a -b -c are three boolean flags, but -abc would be an -a flag introducing a string value of "bc".

Flag -h is predefined to print a short "ProgName purpose, usage & options:\n" lead, then content of the mopt.Usage variable; then program exits. Lead is kept in a package variable, so it can be changed from the user's code.

Automatic help behaviour can be extended simply by asking about a help topic early on: eg.

var cl mopt.Usage = "\t-v verbose\n ..."
func main(){
  if htopic := cl.OptS('h',"-"); htopic != "-" {
    switch htopic {
      case "": // bare -h
      case "flip": // -h flip
      // ...
      default:
        println("No help about", htopic, "avaliable!")
    }
    os.Exit(0) // exit after
  }
//...
}

Mopt package is meant to be used in the PoC code and ad-hoc cli tools. It parses two leading bytes of each os.Args entry anew on every OptX call. Also, there is no user feedback of "unknown/wrong option", nor developer is guarded against opt-letter reuse. Caveat emptor!

Usage

type Usage
type Usage string

Usage type string provides help message to be printed if program user will pass the '-h' flag. Mopt package whole api is hooked on an Usage type variable.

func (Usage) OptB
func (u Usage) OptB(flag rune) (r bool)

Method OptB returns true if flag was given, otherwise it returns false.  It need not to take a default: flag either is present, or not.

func (Usage) OptF
func (u Usage) OptF(flag rune, def float64) (r float64)

Method OptF returns float64 read as f32 from string following the flag. If flag was not given, or it could not be parsed to the float, OptF returns the def value.

func (Usage) OptL
func (u Usage) OptL() (r []string)

Method OptL returns a slice of strings filled with commandline arguments after the last option, or arguments after the options terminator '--', if given. Or all arguments if no dash-letter was spotted.

func (Usage) OptN
func (u Usage) OptN(flag rune, def int) (r int)

Method OptN returns an int. If flag was not given, or string that followed could not be parsed to an int, OptN returns the def value. Negative values need no special attention: -x-2 and -y -2 both convey -2.

func (Usage) OptS
func (u Usage) OptS(flag rune, def string) string

Method OptS returns following string. If flag was not given, OptS returns the def value. If string after option needs to begin with a dash character, leading dash must be escaped: eg. -s"\-begins with a dash".

NLS variable
var HelpLead string = "purpose, usage & options:\n"

Allows -h to say "propósito, uso y opciones:", or "目的、使用法、オプション"

Exit variable
var Exit func(int) = os.Exit

os.Exit(0) called by -h support can be hijacked here.


Documentation

Overview

Package mopt provides getopt style options parsing in 90 lines of Go.

Its API consist of five OptX methods, with 'X' being of 'B'ool, 'S'tring, 'F'loat, 'N'umber (int), and finally 'L'ist - that returns list (slice) of arguments after the last option (or after terminating --).

Declaration `var cl mopt.Usage = "usage/help"` is the only chore. Then you just call one of cl.OptX(flag, default) methods where needed. If flag was given you will get its value. If it was not - you have the default.

Mopt parses oldschool single letter options, and option "-h" is predefined to print var Usage content (ie. "usage/help" string). Spaces between flag letter and value are unimportant: ie. -a bc, and -abc are equivalent. Same for numbers: -n-3 and -n -3 both provide -3 number. For this elasticity a leading dash of string value must be given escaped with a backslash: eg. -s\-dashed or -s "\- started with a dash"; and flag grouping is not supported, too. Ie. -a -b -c are three boolean flags, but -abc would be an -a option introducing a string value of "bc".

Mopt is meant to be used in the PoC code and ad-hoc cli tools. It parses whole os.Args anew on each OptX call. There is no user feedback of "unknown option", nor developer is guarded against opt-letter reuse. Caveat Emptor!

Index

Constants

This section is empty.

Variables

View Source
var Exit func(int) = os.Exit

Exit(0) can be hijacked here

View Source
var HelpLead string = "purpose, usage & options:\n"

Mopt can also say "propósito, uso y opciones:\n"

Functions

This section is empty.

Types

type Usage

type Usage string
Usage is the API holder type - to be filled with the message to be

printed as "help/usage" after the "prog - purpose, usage & options:\n" predefined lead, if user gave the '-h' option. After printing Usage content program terminates returning zero.

Expanding help: The -h flag and subsequent string can be retrieved early in a program without stepping into the default `print Usage then Exit` path. If first call to the Usage methods will be for the 'h', eg. `subhelp := cl.OptS("h","-")`, returned "subhelp" string (!= "-") will tell that -h option is present, amd that user possibly wants more help on topic. After servicing user needs, program should terminate.

func (Usage) OptB

func (u Usage) OptB(flag rune) (r bool)

Method OptB returns true if flag was given, otherwise it returns false.  It need not to take a default: flag either is present, or not.

func (Usage) OptF

func (u Usage) OptF(flag rune, def float64) (r float64)

Method OptF returns float64 read as f32 from string following the flag. If flag was not given, or it could not be parsed to the float, OptF returns the def value. String is parsed to the float64 but of value that is convertible to the float32 without value changing.

func (Usage) OptL

func (u Usage) OptL() (r []string)

Method OptL returns a slice of commandline arguments after the last option, or arguments after the terminating -- dashes, if given; or all arguments, if no dash-letter was spotted.

func (Usage) OptN

func (u Usage) OptN(flag rune, def int) (r int)

Method OptN returns int read from string that follows the flag. If flag was not given, or it could not be parsed to an int, OptN returns the def value. Negative values need no special attention: -a-2 and -a -2 both resolve to -2.

func (Usage) OptS

func (u Usage) OptS(flag rune, def string) string

Method OptS returns string that followed the flag. If flag was not given, OptS returns the def value. If string after option needs to begin with dash character, it must be escaped: eg. -s"\-begins with a dash".

Jump to

Keyboard shortcuts

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