opt

package module
v0.0.0-...-e72225a Latest Latest
Warning

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

Go to latest
Published: Sep 11, 2023 License: GPL-3.0 Imports: 2 Imported by: 4

README

opt

Command-line --option parsing for Go

  • long and short options: --help -h --number=7 -n 7 -n7
  • long options can be abbreviated: --version --ver
  • short options can be combined: -rf
  • positional arguments can be interspersed: -a file file2 -b
  • double dash forces positional arguments: --option -- --not --options
package main

import (
	"errors"
	"fmt"
	"git.sr.ht/~geb/opt"
	"os"
)

type Butty struct {
	Bread      string
	Bacon, Egg bool
}

func main() {
	butty := Butty{"brown", true, false}
	o := opt.NewOptSet()

	o.BoolFunc("bacon", func(b bool) error {
		butty.Bacon = b
		return nil
	})

	o.Func("bread", func(s string) error {
		if s != "brown" && s != "white" {
			return errors.New("unknown bread type: " + s)
		}
		butty.Bread = s
		return nil
	})

	o.BoolFunc("egg", func(b bool) error {
		butty.Egg = b
		return nil
	})
	o.Alias("egg", "e")

	o.FlagFunc("help", func() error {
		fmt.Println("Command to make butties.")
		os.Exit(0)
		panic("unreachable")
	})
	o.Alias("help", "h")

	err := o.Parse(true, os.Args[1:])

	fmt.Println(err)
	fmt.Println(butty)
	fmt.Println(o.Args())
	fmt.Println(o.Leftovers())
}

Contact

You can ask a question or send a patch by composing an email to ~geb/public-inbox@lists.sr.ht.

License

GPLv3 only, see LICENSE.

Copyright (c) 2022 John Gebbie

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type OptSet

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

func NewOptSet

func NewOptSet() *OptSet

func (*OptSet) Alias

func (o *OptSet) Alias(name string, aliases ...string)

func (*OptSet) Args

func (o *OptSet) Args() []string

func (*OptSet) BoolFunc

func (o *OptSet) BoolFunc(name string, f func(bool) error)

func (*OptSet) FlagFunc

func (o *OptSet) FlagFunc(name string, f func() error)

func (*OptSet) Func

func (o *OptSet) Func(name string, f func(string) error)

func (*OptSet) Leftovers

func (o *OptSet) Leftovers() []string

func (*OptSet) Parse

func (o *OptSet) Parse(interspersed bool, arguments []string) error

Jump to

Keyboard shortcuts

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