2021-01-31 01:15:07 +01:00
|
|
|
package cli
|
|
|
|
|
|
|
|
import (
|
2021-03-19 00:27:36 +01:00
|
|
|
"errors"
|
2021-01-31 01:15:07 +01:00
|
|
|
"flag"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
)
|
|
|
|
|
|
|
|
type GlobalOpts struct {
|
|
|
|
ConfigPath string
|
|
|
|
Debug bool
|
|
|
|
ConfigStanza string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (o GlobalOpts) String() string {
|
|
|
|
return "--config --debug --account"
|
|
|
|
}
|
|
|
|
|
|
|
|
type Command interface {
|
|
|
|
Func([]string) error
|
|
|
|
Help(io.Writer, *flag.FlagSet)
|
|
|
|
}
|
|
|
|
|
|
|
|
type CommandMap map[string]Command
|
|
|
|
|
|
|
|
type ProgramInfo struct {
|
|
|
|
Name string
|
|
|
|
Opts GlobalOpts
|
|
|
|
Commands CommandMap
|
|
|
|
}
|
|
|
|
|
|
|
|
func Usage(w io.Writer, info ProgramInfo) {
|
|
|
|
fmt.Fprintf(w, "USAGE: %s [%s] SUBCOMMAND [subcommand opts]\n", info.Name, info.Opts)
|
|
|
|
fmt.Fprintf(w, "\nSUBCOMMANDS:\n")
|
|
|
|
for command := range info.Commands {
|
|
|
|
fmt.Fprintf(w, "\t%s\n", command)
|
|
|
|
}
|
|
|
|
}
|
2021-03-19 00:27:36 +01:00
|
|
|
|
|
|
|
type Pair struct {
|
|
|
|
Set, Unset bool
|
|
|
|
}
|
|
|
|
|
|
|
|
type PairFlag struct {
|
|
|
|
*Pair
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewPairFlag() PairFlag {
|
|
|
|
return PairFlag{
|
|
|
|
&Pair{false, false},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p Pair) String() string {
|
|
|
|
switch p {
|
|
|
|
case Pair{true, false}:
|
|
|
|
return "set"
|
|
|
|
case Pair{false, true}:
|
|
|
|
return "unset"
|
|
|
|
default:
|
|
|
|
return "undef"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (pf PairFlag) String() string {
|
|
|
|
return pf.Pair.String()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (pf PairFlag) Set(s string) error {
|
|
|
|
if s == "set" {
|
|
|
|
v := Pair{true, false}
|
|
|
|
*pf.Pair = v
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if s == "unset" {
|
|
|
|
v := Pair{false, true}
|
|
|
|
*pf.Pair = v
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return ErrAllowedPairFlagValues
|
|
|
|
}
|
|
|
|
|
|
|
|
var ErrAllowedPairFlagValues = errors.New("only `set` or `unset` are allowed")
|