parseargs

package module
v0.12.1 Latest Latest
Warning

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

Go to latest
Published: May 10, 2024 License: GPL-3.0, LGPL-3.0 Imports: 5 Imported by: 0

README

parseargs

A fully featured argument parser for Go

Features

  • Short(-s) and long(--long) options
  • Positional arguments
  • Bool, int, and string input types
  • Variadic string arguments
  • Git style sub commands

How To Use

Define a struct and assign fields tags, supported tags are

  • short: A single character string, used to identify short form options
  • long: An arbitrary length string, used to identify long form options
  • position: A number, identifying which position(ignoring options) the argument comes from
  • position: the string "...", any position not specifically assigned will be in this field
  • sub: the string "t", attached to a position argument, anything appearing after will be put into the variadic string array for further parsing

All fields you wish to be assigned to must be public

Valid field types are bool, string, int, and if the position tag is set to "..." field type must be []string

an example struct could be

type MyArgs struct {
	ProgName string   `position:"0"`
	Help     bool     `short:"h" long:"help"`
	Version  bool     `long:"version"`
	Count    int      `short:"c"`
	Command  string   `position:"1" sub:"t"`
	Vari     []string `position:"..."`
}

To populate pass os.Args(or another string array), stdin, and a reference of struct to output to

Parse may return an error if invalid arguments are passed, or may panic if the struct is malformed

stdin may be omitted by passing an empty string if you wish you handle it separately

args := &MyArgs{}
stdin := ""
if (fi.Mode() & os.ModeCharDevice) == 0 {
    stdinBytes, err := io.ReadAll(os.Stdin)
    if err != nil {
        panic(err)
    }
    stdin = string(stdinBytes)
}
err := parseargs.Parse(os.Args, stdin, &args)
if err != nil {
    //handle error
}

Things To Consider

  • position 0 from os.Args is the name of the program, if you have a variadic field, and do not handle position 0 it WILL be inserted there
  • a field can not be a position, and an option(short or long), this is not explicitly prevented, but the behaviour is undefined

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Parse

func Parse(args []string, stdin string, bindArgMap ArgMap) error

Takes in an args list(usually from os.Args) and stdin as a string, binds them to the defined bindArgMap struct Does nothing with untagged fields Returns an error if an unexpected argument or invalid value is given Panics if position tag is not a number or "..."

Types

type ArgMap

type ArgMap interface{}

Jump to

Keyboard shortcuts

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