cmdr

package module
v1.6.36 Latest Latest
Warning

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

Go to latest
Published: May 1, 2020 License: MIT Imports: 33 Imported by: 76

README

cmdr

Build Status Go GitHub tag (latest SemVer) GoDoc Go Report Card codecov Coverage Status Mentioned in Awesome Go

cmdr is a POSIX/GNU style, command-line UI (CLI) Go library. It is a getopt-like parser of command-line options, be compatible with the getopt_long command line UI, which is an extension of the syntax recommended by POSIX.

There are couples of enhancements beyond the standard library flag.

There is a full Options Store (configurations) for your hierarchy configuration data too.

ee99d078e2f7

To review the image frames, go surfing at https://github.com/hedzr/cmdr/issues/1#issuecomment-567779978

Table of Contents

Youtube - 李宗盛2013最新單曲 山丘 官方完整版音檔 / Jonathan Lee - Hill CHT + ENU

Import

Need go-modules enabled:

import "github.com/hedzr/cmdr"

News

  • v1.6.36

    • ToggleGroup:
      • assume the empty Group field with ToggleGroup
      • set "command-path.toggleGroupName" to the hit flag full name as flipping a toggle-group.
        For example, supposed a toggle-group 'KK' under 'server' command with 3 choices/flags: apple, banana, orange. For the input '--orange', these entries will be set in option store:
        server.orange <== true;
        server.KK <== 'orange';
    • fixed: GetStringSliceXxx() return the value array without expand the envvar.
    • improved: some supports for plan9
    • fixed: can't expand envvar correectly at earlier initializing.
  • v1.6.35

    • routine maintenance: take effects with bug fixed of logex, etc.
    • typo, doc
    • fixed a data racing scene: the fs-watcher and build-auto-env [rarely]
  • v1.6.33

    • fixed the wrong prototype for nacl/plan9
  • v1.6.32

    • routine maintainance
      • downward compatibility: to go1.11
      • enable github actions
  • For more information to refer to CHANGELOG

Features

cmdr has rich features:

  • builds multi-level command and sub-commands
  • builds short, long and alias options with kinds of data types
  • defines commands and options via fluent api style
  • or defines its with enhanced stdlib flag style
  • full featured Options Store for hosted any application configurations
    • watchable external config file and child directory conf.d
    • watchable option value merging event: while option value modified in external config file and loaded automatically.
    • watchable option value modifying event: while option value modified (from config file, or programmatically)
    • connectable with external configuration center
More
  • Unix getopt(3) representation but without its programmatic interface.

    • Options with short names (-h)
    • Options with long names (--help)
    • Options with aliases (--helpme, --usage, --info)
    • Options with and without arguments (bool v.s. other type)
    • Options with optional arguments and default values
    • Multiple option groups each containing a set of options
    • Supports the compat short options -aux == -a -u -x
    • Supports namespaces for (nested) option groups
  • Automatic help screen generation (Generates and prints well-formatted help message)

  • Supports the Fluent API style

    Sample codes
    root := cmdr.Root("aa", "1.0.3")
        // Or  // .Copyright("All rights reserved", "sombody@example.com")
        .Header("aa - test for cmdr - hedzr")
    rootCmd = root.RootCommand()
    
    co := root.NewSubCommand().
    	Titles("ms", "micro-service").
    	Description("", "").
    	Group("")
    
    // deprecated since v1.6.9
    // co.NewFlag(cmdr.OptFlagTypeUint).
    //  	Titles("t", "retry").
    // 	Description("", "").
    // 	Group("").
    // 	DefaultValue(3, "RETRY")
    
    co.NewFlagV(3).
    	Titles("t", "retry").
    	Description("", "").
    	Group("").
    	Palceholder("RETRY")
    
    cTags := co.NewSubCommand().
    	Titles("t", "tags").
    	Description("", "").
    	Group("")
    
  • Muiltiple API styles:

  • Strict Mode

    • false: Ignoring unknown command line options (default)
    • true: Report error on unknown commands and options if strict mode enabled (optional) enable strict mode:
      • env var APP_STRICT_MODE=true
      • hidden option: --strict-mode (if cmdr.EnableCmdrCommands == true)
      • entry in config file:
        app:
          strict-mode: true
        
  • Supports for unlimited multi-level sub-commands.

  • Supports -I/usr/include -I=/usr/include -I /usr/include option argument specifications

    Automatically allows those formats (applied to long option too):

    • -I file, -Ifile, and -I=files
    • -I 'file', -I'file', and -I='files'
    • -I "file", -I"file", and -I="files"
  • Supports for -D+, -D- to enable/disable a bool option.

  • Supports for PassThrough by --. (Passing remaining command line arguments after -- (optional))

  • Supports for options being specified multiple times, with different values

    since v1.5.0:

    • and multiple flags -vvv == -v -v -v, then cmdr.FindFlagRecursive("verbose", nil).GetTriggeredTimes() should be 3

    • for bool, string, int, ... flags, last one will be kept and others abandoned:

      -t 1 -t 2 -t3 == -t 3

    • for slice flags, all of its will be merged (NOTE that duplicated entries are as is):

      slice flag overlapped

      • --root A --root B,C,D --root Z,A == --root A,B,C,D,Z cmdr.GetStringSliceR("root") will return []string{"A","B","C","D","Z"}
  • Smart suggestions for wrong command and flags

    since v1.1.3, using Jaro-Winkler distance instead of soundex.

  • Groupable commands and options/flags.

    Sortable group name with [0-9A-Za-z]+\..+ format, eg:

    • 1001.c++, 1100.golang, 1200.java, …;
    • abcd.c++, b999.golang, zzzz.java, …;
  • Sortable commands and options/flags. Or sorted by alphabetic order.

  • Predefined commands and flags:

    • Help: -h, -?, --help, --info, --usage, --helpme, ...
    • Version & Build Info: --version/--ver/-V, --build-info/-#
      • Simulating version at runtime with —version-sim 1.9.1
      • generally, conf.AppName and conf.Version are originally.
      • ~~tree: list all commands and sub-commands.
      • --config <location>: specify the location of the root config file.
    • Verbose & Debug: —verbose/-v, —debug/-D, —quiet/-q
    • Generate Commands:
      • generate shell: —bash/—zsh(todo)/--auto
      • generate manual: man 1 ready.
      • generate doc: markdown ready.
    • cmdr Specials:
      • --no-env-overrides, and --strict-mode
      • --no-color: print the plain text to console without ANSI colors.
  • Generators

    • Todo: manual generator, and markdown/docx/pdf generators.

    • Man Page generator: bin/demo generate man

    • Markdown generator: bin/demo generate [doc|mdk|markdown]

    • Bash and Zsh (not yet, todo) completion.

      $ bin/wget-demo generate shell --bash
      
  • Predefined external config file locations:

    • /etc/<appname>/<appname>.yml and conf.d sub-directory.

    • /usr/local/etc/<appname>/<appname>.yml and conf.d sub-directory.

    • $HOME/.config/<appname>/<appname>.yml and conf.d sub-directory.

    • $HOME/.<appname>/<appname>.yml and conf.d sub-directory.

    • all predefined locations are:

      predefinedLocations: []string{
      	"./ci/etc/%s/%s.yml",       // for developer
      	"/etc/%s/%s.yml",           // regular location: /etc/$APPNAME/$APPNAME.yml
      	"/usr/local/etc/%s/%s.yml", // regular macOS HomeBrew location
      	"$HOME/.config/%s/%s.yml",  // per user: $HOME/.config/$APPNAME/$APPNAME.yml
      	"$HOME/.%s/%s.yml",         // ext location per user
      	"$THIS/%s.yml",             // executable's directory
      	"%s.yml",                   // current directory
      },
      
    • since v1.5.0, uses cmdr.WithPredefinedLocations("a","b",...),

  • Watch conf.d directory:

    • cmdr.WithConfigLoadedListener(listener)

      • AddOnConfigLoadedListener(c)
      • RemoveOnConfigLoadedListener(c)
      • SetOnConfigLoadedListener(c, enabled)
    • As a feature, do NOT watch the changes on <appname>.yml.

      • since v1.6.9, WithWatchMainConfigFileToo(true) allows the main config file <appname>.yml to be watched.
    • on command-line:

      $ bin/demo --configci/etc/demo-yy ~~debug
      $ bin/demo --config=ci/etc/demo-yy/any.yml ~~debug
      $ bin/demo --config ci/etc/demo-yy/any.yml ~~debug
      
    • supports muiltiple file formats:

      • Yaml
      • JSON
      • TOML
    • cmdr.Exec(root, cmdr.WithNoLoadConfigFiles(false)): disable loading external config files.

  • Overrides by environment variables.

    priority level: defaultValue -> config-file -> env-var -> command-line opts

  • Option Store - Unify option value extraction:

    • cmdr.Get(key), cmdr.GetBool(key), cmdr.GetInt(key), cmdr.GetString(key), cmdr.GetStringSlice(key, defaultValues...) and cmdr.GetIntSlice(key, defaultValues...), cmdr.GetDuration(key) for Option value extractions.

      • bool
      • int, int64, uint, uint64, float32, float64
        $ app -t 1    #  float: 1.1, 1e10, hex: 0x9d, oct: 0700, bin: 0b00010010
        
      • string
      • string slice, int slice (comma-separated)
        $ app -t apple,banana      # => []string{"apple", "banana"}
        $ app -t apple -t banana   # => []string{"apple", "banana"}
        
      • time duration (1ns, 1ms, 1s, 1m, 1h, 1d, ...)
        $ app -t 1ns -t 1ms -t 1s -t 1m -t 1h -t 1d
        
      • todo: float, time, duration, int slice, …, all primitive go types
      • map
      • struct: cmdr.GetSectionFrom(sectionKeyPath, &holderStruct)
    • cmdr.Set(key, value), cmdr.SerNx(key, value)

      • Set() set value by key without RxxtPrefix, eg: cmdr.Set("debug", true) for --debug.
      • SetNx() set value by exact key. so: cmdr.SetNx("app.debug", true) for --debug.
    • Fast Guide for Get, GetP and GetR:

      • cmdr.GetP(prefix, key), cmdr.GetBoolP(prefix, key), ….
      • cmdr.GetR(key), cmdr.GetBoolR(key), …, cmdr.GetMapR(key)
      • cmdr.GetRP(prefix, key), cmdr.GetBoolRP(prefix, key), ….

      As a fact, cmdr.Get("app.server.port") == cmdr.GetP("app.server", "port") == cmdr.GetR("server.port") (if cmdr.RxxtPrefix == ["app"]); so:

      cmdr.Set("server.port", 7100)
      assert cmdr.GetR("server.port") == 7100
      assert cmdr.Get("app.server.port") == 7100
      

      In most cases, GetXxxR() are recommended.

      While extracting string value, the evnvar will be expanded automatically but raw version GetStringNoExpandXXX() available since v1.6.7. For example:

      fmt.Println(cmdr.GetStringNoExpandR("kk"))  // = $HOME/Downloads
      fmt.Println(cmdr.GetStringR("kk"))          // = /home/ubuntu/Downloads
      
  • cmdr Options Store

    internal rxxtOptions

  • Walkable

    • Customizable Painter interface to loop each command and flag.
    • Walks on all commands with WalkAllCommands(walker).
  • Daemon (Linux Only)

    rewrote since v1.6.0

    import "github.com/hedzr/cmdr/plugin/daemon"
    func main() {
    	if err := cmdr.Exec(rootCmd,
          daemon.WithDaemon(NewDaemon(), nil,nil,nil),
      	); err != nil {
    		log.Fatal("Error:", err)
    	}
    }
    func NewDaemon() daemon.Daemon {
    	return &DaemonImpl{}
    }
    

    See full codes in demo app, and cmdr-http2.

    $ bin/demo server [start|stop|status|restart|install|uninstall]
    

    install/uninstall sub-commands could install demo app as a systemd service.

    Just for Linux

  • ExecWith(rootCmd *RootCommand, beforeXrefBuilding_, afterXrefBuilt_ HookXrefFunc) (err error)

    AddOnBeforeXrefBuilding(cb)

    AddOnAfterXrefBuilt(cb)

  • cmdr.WithXrefBuildingHooks(beforeXrefBuilding, afterXrefBuilding)

  • Debugging options:

    • ~~debug: dump all key value pairs in parsed options store

      $ bin/demo -? ~~debug
      $ bin/demo -? ~~debug ~~raw  # without envvar expanding
      $ bin/demo -? ~~debug ~~env  # print envvar k-v pairs too
      $ bin/demo -? ~~debug --more
      

      ~~debug depends on --help present (or invoking a command which have one ore more children)

    • InDebugging(), isdelve (refer to here) - To use it, add -tags=delve:

      go build -tags=delve cli/main.go
      go run -tags=delve cli/main.go --help
      
  • ~~tree: dump all sub-commands

    $ bin/demo ~~tree
    

    ~~tree is a special option/flag like a command.

  • More Advanced features

    • Launches external editor by &Flag{BaseOpt:BaseOpt{},ExternalTool:cmdr.ExternalToolEditor}:

      just like git -m, try this command:

      $ EDITOR=nano bin/demo -m ~~debug
      

      Default is vim. And -m "something" can skip the launching.

    • ToggleGroup: make a group of flags as a radio-button group.

    • Safe password input for end-user: cmdr.ExternalToolPasswordInput

    • head-like option: treat app do sth -1973 as app do sth -a=1973, just like head -1.

      Flags: []*cmdr.Flag{
          {
              BaseOpt: cmdr.BaseOpt{
                  Short:       "h",
                  Full:        "head",
                  Description: "head -1 like",
              },
              DefaultValue: 0,
              HeadLike:     true,
          },
      },
      
    • limitation with enumerable values:

      Flags: []*cmdr.Flag{
          {
              BaseOpt: cmdr.BaseOpt{
                  Short:       "e",
                  Full:        "enum",
                  Description: "enum tests",
              },
              DefaultValue: "", // "apple",
              ValidArgs:    []string{"apple", "banana", "orange"},
          },
      },
      

      While a non-in-list value found, An error (*ErrorForCmdr) will be thrown:

      cmdr.ShouldIgnoreWrongEnumValue = true
      if err := cmdr.Exec(rootCmd); err != nil {
          if e, ok := err(*cmdr.ErrorForCmdr); ok {
              // e.Ignorable is a copy of [cmdr.ShouldIgnoreWrongEnumValue]
              if e.Ignorable {
                  logrus.Warning("Non-recognaizable value found: ", e)
                  os.Exit(0)
              }
          }
          logrus.Fatal(err)
      }
      
    • cmdr.TrapSignals(fn, signals...)

      It is a helper to simplify your infidonite loop before exit program:

      Sample codes Here is sample fragment: ```go func enteringLoop() { waiter := cmdr.TrapSignals(func(s os.Signal) { logrus.Debugf("receive signal '%v' in onTrapped()", s) }) go waiter() } ```
  • More...

Examples

  1. short
    simple codes with structured data style.

  2. demo
    normal demo with external config files.

  3. wget-demo
    partial-covered for GNU wget.

  4. fluent
    demostrates how to define your command-ui with the fluent api style.

  5. ffmain

    a demo to show you how to migrate from go flag smoothly.

  6. cmdr-http2
    http2 server with daemon supports, graceful shutdown

  7. awesome-tool
    awesome-tool is a cli app that fetch the repo stars and generate a markdown summary, accordingly with most of awesome-xxx list in github (such as awesome-go).

Documentation

For Developer

To build and test cmdr:

$ make help   # see all available sub-targets
$ make info   # display building environment
$ make build  # build binary files for examples
$ make gocov  # test

# customizing
$ GOPROXY_CUSTOM=https://goproxy.io make info
$ GOPROXY_CUSTOM=https://goproxy.io make build
$ GOPROXY_CUSTOM=https://goproxy.io make gocov
Build your cli app with cmdr
APP_NAME=your-app-name
APP_VERSION=your-app-version

W_PKG=github.com/hedzr/cmdr/conf

TIMESTAMP=$(date -u '+%Y-%m-%d_%I:%M:%S%p')
GITHASH=$(git rev-parse HEAD)
GOVERSION=$(go version)

LDFLAGS="-s -w -X '$W_PKG.Buildstamp=$TIMESTAMP' -X '$W_PKG.Githash=$GITHASH' -X '$W_PKG.GoVersion=$GOVERSION' -X '$W_PKG.Version=$APP_VERSION' -X '$W_PKG.AppName=$APP_NAME"

go build -ldflags "$LDFLAGS" -o bin/app-name ./cli
Uses Fluent API
Expand to source codes
	root := cmdr.Root("aa", "1.0.1").Header("aa - test for cmdr - hedzr")
	rootCmd = root.RootCommand()

	co := root.NewSubCommand().
		Titles("ms", "micro-service").
		Description("", "").
		Group("")

	co.NewFlag(cmdr.OptFlagTypeUint).
		Titles("t", "retry").
		Description("", "").
		Group("").
		DefaultValue(3, "RETRY")

	cTags := co.NewSubCommand().
		Titles("t", "tags").
		Description("", "").
		Group("")

	cTags.NewFlag(cmdr.OptFlagTypeString).
		Titles("a", "addr").
		Description("", "").
		Group("").
		DefaultValue("consul.ops.local", "ADDR")

	cTags.NewSubCommand().
		Titles("ls", "list").
		Description("", "").
		Group("").
		Action(func(cmd *cmdr.Command, args []string) (err error) {
			return
		})

	cTags.NewSubCommand().
		Titles("a", "add").
		Description("", "").
		Group("").
		Action(func(cmd *cmdr.Command, args []string) (err error) {
			return
		})

At Playground

Try its out :

Uses

Contrib

Feel free to issue me bug reports and fixes. Many thanks to all contributors.

Thanks to JODL

JODL (JetBrains OpenSource Development License) is good:

goland jetbrains

License

MIT.

Documentation

Overview

Package cmdr interprets command-line arguments with POSIX style.

Index

Constants

View Source
const (

	// UnsortedGroup for commands and flags
	UnsortedGroup = "zzzz.unsorted"
	// SysMgmtGroup for commands and flags
	SysMgmtGroup = "zzz9.Misc"

	// DefaultEditor is 'vim'
	DefaultEditor = "vim"

	// ExternalToolEditor environment variable name, EDITOR is fit for most of shells.
	ExternalToolEditor = "EDITOR"

	// ExternalToolPasswordInput enables secure password input without echo.
	ExternalToolPasswordInput = "PASSWD"
)
View Source
const (
	// AppName const
	AppName = "cmdr"
	// Version const
	Version = "1.6.36"
	// VersionInt const
	VersionInt = 0x010623
)
View Source
const (

	// FgBlack terminal color code
	FgBlack = 30
	// FgRed terminal color code
	FgRed = 31
	// FgGreen terminal color code
	FgGreen = 32
	// FgYellow terminal color code
	FgYellow = 33
	// FgBlue terminal color code
	FgBlue = 34
	// FgMagenta terminal color code
	FgMagenta = 35
	// FgCyan terminal color code
	FgCyan = 36
	// FgLightGray terminal color code
	FgLightGray = 37
	// FgDarkGray terminal color code
	FgDarkGray = 90
	// FgLightRed terminal color code
	FgLightRed = 91
	// FgLightGreen terminal color code
	FgLightGreen = 92
	// FgLightYellow terminal color code
	FgLightYellow = 93
	// FgLightBlue terminal color code
	FgLightBlue = 94
	// FgLightMagenta terminal color code
	FgLightMagenta = 95
	// FgLightCyan terminal color code
	FgLightCyan = 96
	// FgWhite terminal color code
	FgWhite = 97

	// BgNormal terminal color code
	BgNormal = 0
	// BgBoldOrBright terminal color code
	BgBoldOrBright = 1
	// BgDim terminal color code
	BgDim = 2
	// BgItalic terminal color code
	BgItalic = 3
	// BgUnderline terminal color code
	BgUnderline = 4
	// BgUlink terminal color code
	BgUlink = 5
	// BgHidden terminal color code
	BgHidden = 8

	// DarkColor terminal color code
	DarkColor = FgLightGray
)

Variables

View Source
var (
	// GormDefaultCopier used for gorm
	GormDefaultCopier = &copierImpl{KeepIfFromIsNil: true, ZeroIfEqualsFrom: true, KeepIfFromIsZero: true, EachFieldAlways: true}
	// StandardCopier is a normal copier
	StandardCopier = &copierImpl{}
)
View Source
var (
	// ErrShouldBeStopException tips `Exec()` cancelled the following actions after `PreAction()`
	ErrShouldBeStopException = newErrorWithMsg("stop me right now")

	// ErrBadArg is a generic error for user
	ErrBadArg = newErrorWithMsg("bad argument")
)
View Source
var (

	// CurrentDescColor the print color for description line
	CurrentDescColor = FgDarkGray
	// CurrentDefaultValueColor the print color for default value line
	CurrentDefaultValueColor = FgDarkGray
	// CurrentGroupTitleColor the print color for titles
	CurrentGroupTitleColor = DarkColor
)

AllLevels is a constant exposing all logging levels

View Source
var SavedOsArgs []string

SavedOsArgs is a copy of os.Args, just for testing

Functions

func AddOnConfigLoadedListener

func AddOnConfigLoadedListener(c ConfigReloaded)

AddOnConfigLoadedListener adds an functor on config loaded and merged

func AsJSON added in v1.1.1

func AsJSON() (b []byte)

AsJSON returns a json string bytes about all options

func AsJSONExt added in v1.6.13

func AsJSONExt() (b []byte, err error)

AsJSONExt returns a json string bytes about all options

func AsToml added in v1.1.1

func AsToml() (b []byte)

AsToml returns a toml string bytes about all options

func AsTomlExt added in v1.6.13

func AsTomlExt() (b []byte, err error)

AsTomlExt returns a toml string bytes about all options

func AsYaml added in v1.1.1

func AsYaml() (b []byte)

AsYaml returns a yaml string bytes about all options

func AsYamlExt added in v1.6.13

func AsYamlExt() (b []byte, err error)

AsYamlExt returns a yaml string bytes about all options

func Clone added in v0.2.3

func Clone(fromValue, toValue interface{}) interface{}

Clone deep copy source to target

func DeleteKey added in v1.6.3

func DeleteKey(key string)

DeleteKey deletes a key from cmdr options store

func DumpAsString

func DumpAsString() (str string)

DumpAsString for debugging.

func EnsureDir

func EnsureDir(dir string) (err error)

EnsureDir checks and creates the directory.

func Exec

func Exec(rootCmd *RootCommand, opts ...ExecOption) (err error)

Exec is main entry of `cmdr`.

func FileExists

func FileExists(name string) bool

FileExists returns the existence of an directory or file

func Get

func Get(key string) interface{}

Get returns the generic value of an `Option` key with WrapWithRxxtPrefix. Such as: ```golang cmdr.Get("app.logger.level") => 'DEBUG',... ```

func GetBool

func GetBool(key string, defaultVal ...bool) bool

GetBool returns the bool value of an `Option` key. Such as: ```golang cmdr.GetBool("app.logger.enable", false) => true,... ```

func GetBoolP added in v0.2.3

func GetBoolP(prefix, key string, defaultVal ...bool) bool

GetBoolP returns the bool value of an `Option` key. Such as: ```golang cmdr.GetBoolP("app.logger", "enable", false) => true,... ```

func GetBoolR added in v0.2.23

func GetBoolR(key string, defaultVal ...bool) bool

GetBoolR returns the bool value of an `Option` key with WrapWithRxxtPrefix. Such as: ```golang cmdr.GetBoolR("logger.enable", false) => true,... ```

func GetBoolRP added in v0.2.23

func GetBoolRP(prefix, key string, defaultVal ...bool) bool

GetBoolRP returns the bool value of an `Option` key with WrapWithRxxtPrefix. Such as: ```golang cmdr.GetBoolRP("logger", "enable", false) => true,... ```

func GetComplex128 added in v1.6.21

func GetComplex128(key string, defaultVal ...complex128) complex128

GetComplex128 returns the complex128 value of an `Option` key.

func GetComplex128P added in v1.6.21

func GetComplex128P(prefix, key string, defaultVal ...complex128) complex128

GetComplex128P returns the complex128 value of an `Option` key.

func GetComplex128R added in v1.6.21

func GetComplex128R(key string, defaultVal ...complex128) complex128

GetComplex128R returns the complex128 value of an `Option` key with WrapWithRxxtPrefix.

func GetComplex128RP added in v1.6.21

func GetComplex128RP(prefix, key string, defaultVal ...complex128) complex128

GetComplex128RP returns the complex128 value of an `Option` key with WrapWithRxxtPrefix.

func GetComplex64 added in v1.6.21

func GetComplex64(key string, defaultVal ...complex64) complex64

GetComplex64 returns the complex64 value of an `Option` key.

func GetComplex64P added in v1.6.21

func GetComplex64P(prefix, key string, defaultVal ...complex64) complex64

GetComplex64P returns the complex64 value of an `Option` key.

func GetComplex64R added in v1.6.21

func GetComplex64R(key string, defaultVal ...complex64) complex64

GetComplex64R returns the complex64 value of an `Option` key with WrapWithRxxtPrefix.

func GetComplex64RP added in v1.6.21

func GetComplex64RP(prefix, key string, defaultVal ...complex64) complex64

GetComplex64RP returns the complex64 value of an `Option` key with WrapWithRxxtPrefix.

func GetCurrentDir

func GetCurrentDir() string

GetCurrentDir returns the current workingFlag directory it should be equal with os.Getenv("PWD")

func GetDebugMode added in v0.2.5

func GetDebugMode() bool

GetDebugMode returns the flag value of `--debug`/`-D`

func GetDuration added in v0.2.19

func GetDuration(key string, defaultVal ...time.Duration) time.Duration

GetDuration returns the int slice value of an `Option` key.

func GetDurationP added in v0.2.19

func GetDurationP(prefix, key string, defaultVal ...time.Duration) time.Duration

GetDurationP returns the int slice value of an `Option` key.

func GetDurationR added in v1.0.0

func GetDurationR(key string, defaultVal ...time.Duration) time.Duration

GetDurationR returns the int slice value of an `Option` key.

func GetDurationRP added in v1.0.0

func GetDurationRP(prefix, key string, defaultVal ...time.Duration) time.Duration

GetDurationRP returns the int slice value of an `Option` key.

func GetExcutablePath added in v0.2.13

func GetExcutablePath() string

GetExcutablePath returns the executable file path

func GetExecutableDir added in v1.6.0

func GetExecutableDir() string

GetExecutableDir returns the executable file directory

func GetFloat32 added in v1.0.1

func GetFloat32(key string, defaultVal ...float32) float32

GetFloat32 returns the float32 value of an `Option` key.

func GetFloat32P added in v1.0.1

func GetFloat32P(prefix, key string, defaultVal ...float32) float32

GetFloat32P returns the float32 value of an `Option` key.

func GetFloat32R added in v1.0.1

func GetFloat32R(key string, defaultVal ...float32) float32

GetFloat32R returns the float32 value of an `Option` key with WrapWithRxxtPrefix.

func GetFloat32RP added in v1.0.1

func GetFloat32RP(prefix, key string, defaultVal ...float32) float32

GetFloat32RP returns the float32 value of an `Option` key with WrapWithRxxtPrefix.

func GetFloat64 added in v1.0.1

func GetFloat64(key string, defaultVal ...float64) float64

GetFloat64 returns the float64 value of an `Option` key.

func GetFloat64P added in v1.0.1

func GetFloat64P(prefix, key string, defaultVal ...float64) float64

GetFloat64P returns the float64 value of an `Option` key.

func GetFloat64R added in v1.0.1

func GetFloat64R(key string, defaultVal ...float64) float64

GetFloat64R returns the float64 value of an `Option` key with WrapWithRxxtPrefix.

func GetFloat64RP added in v1.0.1

func GetFloat64RP(prefix, key string, defaultVal ...float64) float64

GetFloat64RP returns the float64 value of an `Option` key with WrapWithRxxtPrefix.

func GetHierarchyList added in v1.1.1

func GetHierarchyList() map[string]interface{}

GetHierarchyList returns the hierarchy data

func GetInt

func GetInt(key string, defaultVal ...int) int

GetInt returns the int value of an `Option` key.

func GetInt64 added in v0.2.3

func GetInt64(key string, defaultVal ...int64) int64

GetInt64 returns the int64 value of an `Option` key.

func GetInt64P added in v0.2.3

func GetInt64P(prefix, key string, defaultVal ...int64) int64

GetInt64P returns the int64 value of an `Option` key.

func GetInt64R added in v0.2.23

func GetInt64R(key string, defaultVal ...int64) int64

GetInt64R returns the int64 value of an `Option` key with WrapWithRxxtPrefix.

func GetInt64RP added in v0.2.23

func GetInt64RP(prefix, key string, defaultVal ...int64) int64

GetInt64RP returns the int64 value of an `Option` key with WrapWithRxxtPrefix.

func GetInt64Slice added in v1.6.3

func GetInt64Slice(key string, defaultVal ...int64) []int64

GetInt64Slice returns the int slice value of an `Option` key.

func GetInt64SliceP added in v1.6.3

func GetInt64SliceP(prefix, key string, defaultVal ...int64) []int64

GetInt64SliceP returns the int slice value of an `Option` key.

func GetInt64SliceR added in v1.6.3

func GetInt64SliceR(key string, defaultVal ...int64) []int64

GetInt64SliceR returns the int slice value of an `Option` key with WrapWithRxxtPrefix.

func GetInt64SliceRP added in v1.6.3

func GetInt64SliceRP(prefix, key string, defaultVal ...int64) []int64

GetInt64SliceRP returns the int slice value of an `Option` key with WrapWithRxxtPrefix.

func GetIntP added in v0.2.3

func GetIntP(prefix, key string, defaultVal ...int) int

GetIntP returns the int value of an `Option` key.

func GetIntR added in v0.2.23

func GetIntR(key string, defaultVal ...int) int

GetIntR returns the int value of an `Option` key with WrapWithRxxtPrefix.

func GetIntRP added in v0.2.23

func GetIntRP(prefix, key string, defaultVal ...int) int

GetIntRP returns the int value of an `Option` key with WrapWithRxxtPrefix.

func GetIntSlice added in v0.2.19

func GetIntSlice(key string, defaultVal ...int) []int

GetIntSlice returns the int slice value of an `Option` key.

func GetIntSliceP added in v0.2.19

func GetIntSliceP(prefix, key string, defaultVal ...int) []int

GetIntSliceP returns the int slice value of an `Option` key.

func GetIntSliceR added in v0.2.23

func GetIntSliceR(key string, defaultVal ...int) []int

GetIntSliceR returns the int slice value of an `Option` key with WrapWithRxxtPrefix.

func GetIntSliceRP added in v0.2.23

func GetIntSliceRP(prefix, key string, defaultVal ...int) []int

GetIntSliceRP returns the int slice value of an `Option` key with WrapWithRxxtPrefix.

func GetKibibytes added in v1.6.19

func GetKibibytes(key string, defaultVal ...uint64) uint64

GetKibibytes returns the uint64 value of an `Option` key.

kibibyte format is for human readable. In this format, number presentations are: 2k, 8m, 3g, 5t, 6p, 7e. optional 'b' can be appended, such as: 2kb, 5tb, 7EB. All of them is case-insensitive.

kibibyte is based 1024. That means: 1 KiB = 1k = 1024 bytes

See also: https://en.wikipedia.org/wiki/Kibibyte Its related word is kilobyte, refer to: https://en.wikipedia.org/wiki/Kilobyte

The pure number part can be golang presentation, such as 0x99, 0001b, 0700.

func GetKibibytesP added in v1.6.19

func GetKibibytesP(prefix, key string, defaultVal ...uint64) uint64

GetKibibytesP returns the uint64 value of an `Option` key.

kibibyte format is for human readable. In this format, number presentations are: 2k, 8m, 3g, 5t, 6p, 7e. optional 'b' can be appended, such as: 2kb, 5tb, 7EB. All of them is case-insensitive.

kibibyte is based 1024. That means: 1 KiB = 1k = 1024 bytes

See also: https://en.wikipedia.org/wiki/Kibibyte Its related word is kilobyte, refer to: https://en.wikipedia.org/wiki/Kilobyte

The pure number part can be golang presentation, such as 0x99, 0001b, 0700.

func GetKibibytesR added in v1.6.19

func GetKibibytesR(key string, defaultVal ...uint64) uint64

GetKibibytesR returns the uint64 value of an `Option` key with WrapWithRxxtPrefix.

kibibyte format is for human readable. In this format, number presentations are: 2k, 8m, 3g, 5t, 6p, 7e. optional 'b' can be appended, such as: 2kb, 5tb, 7EB. All of them is case-insensitive.

kibibyte is based 1024. That means: 1 KiB = 1k = 1024 bytes

See also: https://en.wikipedia.org/wiki/Kibibyte Its related word is kilobyte, refer to: https://en.wikipedia.org/wiki/Kilobyte

The pure number part can be golang presentation, such as 0x99, 0001b, 0700.

func GetKibibytesRP added in v1.6.19

func GetKibibytesRP(prefix, key string, defaultVal ...uint64) uint64

GetKibibytesRP returns the uint64 value of an `Option` key with WrapWithRxxtPrefix.

kibibyte format is for human readable. In this format, number presentations are: 2k, 8m, 3g, 5t, 6p, 7e. optional 'b' can be appended, such as: 2kb, 5tb, 7EB. All of them is case-insensitive.

kibibyte is based 1024. That means: 1 KiB = 1k = 1024 bytes

See also: https://en.wikipedia.org/wiki/Kibibyte Its related word is kilobyte, refer to: https://en.wikipedia.org/wiki/Kilobyte

The pure number part can be golang presentation, such as 0x99, 0001b, 0700.

func GetKilobytes added in v1.6.19

func GetKilobytes(key string, defaultVal ...uint64) uint64

GetKilobytes returns the uint64 value of an `Option` key.

kilobyte format is for human readable. In this format, number presentations are: 2k, 8m, 3g, 5t, 6p, 7e. optional 'b' can be appended, such as: 2kb, 5tb, 7EB. All of them is case-insensitive.

kilobyte is based 1000. That means: 1 KB = 1k = 1000 bytes

See also: https://en.wikipedia.org/wiki/Kilobyte Its related word is kibibyte, refer to: https://en.wikipedia.org/wiki/Kibibyte

The pure number part can be golang presentation, such as 0x99, 0001b, 0700.

func GetKilobytesP added in v1.6.19

func GetKilobytesP(prefix, key string, defaultVal ...uint64) uint64

GetKilobytesP returns the uint64 value of an `Option` key.

kilobyte format is for human readable. In this format, number presentations are: 2k, 8m, 3g, 5t, 6p, 7e. optional 'b' can be appended, such as: 2kb, 5tb, 7EB. All of them is case-insensitive.

kilobyte is based 1000. That means: 1 KB = 1k = 1000 bytes

See also: https://en.wikipedia.org/wiki/Kilobyte Its related word is kibibyte, refer to: https://en.wikipedia.org/wiki/Kibibyte

The pure number part can be golang presentation, such as 0x99, 0001b, 0700.

func GetKilobytesR added in v1.6.19

func GetKilobytesR(key string, defaultVal ...uint64) uint64

GetKilobytesR returns the uint64 value of an `Option` key with WrapWithRxxtPrefix.

kilobyte format is for human readable. In this format, number presentations are: 2k, 8m, 3g, 5t, 6p, 7e. optional 'b' can be appended, such as: 2kb, 5tb, 7EB. All of them is case-insensitive.

kilobyte is based 1000. That means: 1 KB = 1k = 1000 bytes

See also: https://en.wikipedia.org/wiki/Kilobyte Its related word is kibibyte, refer to: https://en.wikipedia.org/wiki/Kibibyte

The pure number part can be golang presentation, such as 0x99, 0001b, 0700.

func GetKilobytesRP added in v1.6.19

func GetKilobytesRP(prefix, key string, defaultVal ...uint64) uint64

GetKilobytesRP returns the uint64 value of an `Option` key with WrapWithRxxtPrefix.

kilobyte format is for human readable. In this format, number presentations are: 2k, 8m, 3g, 5t, 6p, 7e. optional 'b' can be appended, such as: 2kb, 5tb, 7EB. All of them is case-insensitive.

kilobyte is based 1000. That means: 1 KB = 1k = 1000 bytes

See also: https://en.wikipedia.org/wiki/Kilobyte Its related word is kibibyte, refer to: https://en.wikipedia.org/wiki/Kibibyte

The pure number part can be golang presentation, such as 0x99, 0001b, 0700.

func GetMap added in v1.0.0

func GetMap(key string) map[string]interface{}

GetMap an `Option` by key string, it returns a hierarchy map or nil

func GetMapR added in v1.0.0

func GetMapR(key string) map[string]interface{}

GetMapR an `Option` by key string with WrapWithRxxtPrefix, it returns a hierarchy map or nil

func GetNoColorMode added in v1.6.3

func GetNoColorMode() bool

GetNoColorMode return the flag value of `--no-color`

func GetPredefinedLocations added in v0.2.5

func GetPredefinedLocations() []string

GetPredefinedLocations return the searching locations for loading config files.

func GetQuietMode added in v0.2.5

func GetQuietMode() bool

GetQuietMode returns the flag value of `--quiet`/`-q`

func GetR added in v0.2.23

func GetR(key string) interface{}

GetR returns the generic value of an `Option` key with WrapWithRxxtPrefix. Such as: ```golang cmdr.GetR("logger.level") => 'DEBUG',... ```

func GetSectionFrom added in v1.0.1

func GetSectionFrom(sectionKeyPath string, holder interface{}) (err error)

GetSectionFrom returns error while cannot yaml Marshal and Unmarshal `cmdr.GetSectionFrom(sectionKeyPath, &holder)` could load all sub-tree nodes from sectionKeyPath and transform them into holder structure, such as: ```go

type ServerConfig struct {
  Port int
  HttpMode int
  EnableTls bool
}
var serverConfig = new(ServerConfig)
cmdr.GetSectionFrom("server", &serverConfig)
assert serverConfig.Port == 7100

```

func GetStrictMode added in v0.2.5

func GetStrictMode() bool

GetStrictMode enables error when opt value missed. such as: xxx a b --prefix” => error: prefix opt has no value specified. xxx a b --prefix'/' => ok.

ENV: use `CMDR_APP_STRICT_MODE=true` to enable strict-mode. NOTE: `CMDR_APP_` prefix could be set by user (via: `EnvPrefix` && `RxxtPrefix`).

the flag value of `--strict-mode`.

func GetString

func GetString(key string, defaultVal ...string) string

GetString returns the string value of an `Option` key.

func GetStringNoExpand added in v1.6.7

func GetStringNoExpand(key string, defaultVal ...string) string

GetStringNoExpand returns the string value of an `Option` key.

func GetStringNoExpandP added in v1.6.7

func GetStringNoExpandP(prefix, key string, defaultVal ...string) string

GetStringNoExpandP returns the string value of an `Option` key.

func GetStringNoExpandR added in v1.6.7

func GetStringNoExpandR(key string, defaultVal ...string) string

GetStringNoExpandR returns the string value of an `Option` key with WrapWithRxxtPrefix.

func GetStringNoExpandRP added in v1.6.7

func GetStringNoExpandRP(prefix, key string, defaultVal ...string) string

GetStringNoExpandRP returns the string value of an `Option` key with WrapWithRxxtPrefix.

func GetStringP added in v0.2.3

func GetStringP(prefix, key string, defaultVal ...string) string

GetStringP returns the string value of an `Option` key.

func GetStringR added in v0.2.23

func GetStringR(key string, defaultVal ...string) string

GetStringR returns the string value of an `Option` key with WrapWithRxxtPrefix.

func GetStringRP added in v0.2.23

func GetStringRP(prefix, key string, defaultVal ...string) string

GetStringRP returns the string value of an `Option` key with WrapWithRxxtPrefix.

func GetStringSlice

func GetStringSlice(key string, defaultVal ...string) []string

GetStringSlice returns the string slice value of an `Option` key.

func GetStringSliceP added in v0.2.3

func GetStringSliceP(prefix, key string, defaultVal ...string) []string

GetStringSliceP returns the string slice value of an `Option` key.

func GetStringSliceR added in v0.2.23

func GetStringSliceR(key string, defaultVal ...string) []string

GetStringSliceR returns the string slice value of an `Option` key with WrapWithRxxtPrefix.

func GetStringSliceRP added in v0.2.23

func GetStringSliceRP(prefix, key string, defaultVal ...string) []string

GetStringSliceRP returns the string slice value of an `Option` key with WrapWithRxxtPrefix.

func GetUint added in v0.2.3

func GetUint(key string, defaultVal ...uint) uint

GetUint returns the uint value of an `Option` key.

func GetUint64 added in v0.2.3

func GetUint64(key string, defaultVal ...uint64) uint64

GetUint64 returns the uint64 value of an `Option` key.

func GetUint64P added in v0.2.3

func GetUint64P(prefix, key string, defaultVal ...uint64) uint64

GetUint64P returns the uint64 value of an `Option` key.

func GetUint64R added in v0.2.23

func GetUint64R(key string, defaultVal ...uint64) uint64

GetUint64R returns the uint64 value of an `Option` key with WrapWithRxxtPrefix.

func GetUint64RP added in v0.2.23

func GetUint64RP(prefix, key string, defaultVal ...uint64) uint64

GetUint64RP returns the uint64 value of an `Option` key with WrapWithRxxtPrefix.

func GetUint64Slice added in v1.6.3

func GetUint64Slice(key string, defaultVal ...uint64) []uint64

GetUint64Slice returns the int slice value of an `Option` key.

func GetUint64SliceP added in v1.6.3

func GetUint64SliceP(prefix, key string, defaultVal ...uint64) []uint64

GetUint64SliceP returns the int slice value of an `Option` key.

func GetUint64SliceR added in v1.6.3

func GetUint64SliceR(key string, defaultVal ...uint64) []uint64

GetUint64SliceR returns the int slice value of an `Option` key with WrapWithRxxtPrefix.

func GetUint64SliceRP added in v1.6.3

func GetUint64SliceRP(prefix, key string, defaultVal ...uint64) []uint64

GetUint64SliceRP returns the int slice value of an `Option` key with WrapWithRxxtPrefix.

func GetUintP added in v0.2.3

func GetUintP(prefix, key string, defaultVal ...uint) uint

GetUintP returns the uint value of an `Option` key.

func GetUintR added in v0.2.23

func GetUintR(key string, defaultVal ...uint) uint

GetUintR returns the uint value of an `Option` key with WrapWithRxxtPrefix.

func GetUintRP added in v0.2.23

func GetUintRP(prefix, key string, defaultVal ...uint) uint

GetUintRP returns the uint value of an `Option` key with WrapWithRxxtPrefix.

func GetUsedConfigFile added in v0.2.3

func GetUsedConfigFile() string

GetUsedConfigFile returns the main config filename (generally it's `<appname>.yml`)

func GetUsedConfigSubDir added in v0.2.3

func GetUsedConfigSubDir() string

GetUsedConfigSubDir returns the sub-directory `conf.d` of config files. Note that it be always normalized now. Sometimes it might be empty string ("") if `conf.d` have not been found.

func GetUsingConfigFiles added in v1.6.9

func GetUsingConfigFiles() []string

GetUsingConfigFiles returns all loaded config files, includes the main config file and children in sub-directory `conf.d`.

func GetVerboseMode added in v0.2.5

func GetVerboseMode() bool

GetVerboseMode returns the flag value of `--verbose`/`-v`

func HasKey added in v1.6.3

func HasKey(key string) (ok bool)

HasKey detects whether a key exists in cmdr options store or not

func InDebugging added in v1.6.7

func InDebugging() bool

InDebugging return the status if in debug mode noinspection GoBoolExpressions

func InTesting added in v0.2.19

func InTesting() bool

InTesting detects whether is running under go test mode

func IsDebuggerAttached added in v1.6.7

func IsDebuggerAttached() bool

IsDebuggerAttached return the status if in debug mode noinspection GoBoolExpressions

func IsDigitHeavy added in v1.0.2

func IsDigitHeavy(s string) bool

IsDigitHeavy tests if the whole string is digit

func IsDirectory added in v0.2.21

func IsDirectory(path string) (bool, error)

IsDirectory tests whether `path` is a directory or not

func IsRegularFile added in v0.2.21

func IsRegularFile(path string) (bool, error)

IsRegularFile tests whether `path` is a normal regular file or not

func IsZero added in v1.6.32

func IsZero(v reflect.Value) bool

IsZero reports whether v is the zero value for its type. It panics if the argument is invalid.

func Launch added in v0.2.13

func Launch(cmd string, args ...string) (err error)

Launch executes a command setting both standard input, output and error.

func LaunchEditor added in v0.2.13

func LaunchEditor(editor string) (content []byte, err error)

LaunchEditor launches the specified editor

func LaunchEditorWith added in v0.2.19

func LaunchEditorWith(editor string, filename string) (content []byte, err error)

LaunchEditorWith launches the specified editor with a filename

func LoadConfigFile

func LoadConfigFile(file string) (err error)

LoadConfigFile loads a yaml config file and merge the settings into `rxxtOptions` and load files in the `conf.d` child directory too.

func MergeWith added in v1.1.4

func MergeWith(m map[string]interface{}) (err error)

MergeWith will merge a map recursive. You could merge a yaml/json/toml options into cmdr Hierarchy Options.

func NormalizeDir added in v0.2.19

func NormalizeDir(s string) string

NormalizeDir make dir name normalized

func ParseComplex added in v1.6.21

func ParseComplex(s string) (v complex128)

ParseComplex converts a string to complex number.

Examples:

c1 := cmdr.ParseComplex("3-4i")
c2 := cmdr.ParseComplex("3.13+4.79i")

func ParseComplexX added in v1.6.21

func ParseComplexX(s string) (v complex128, err error)

ParseComplexX converts a string to complex number. If the string is not valid complex format, return err not nil.

Examples:

c1 := cmdr.ParseComplex("3-4i")
c2 := cmdr.ParseComplex("3.13+4.79i")

func PressAnyKeyToContinue added in v1.6.8

func PressAnyKeyToContinue(in io.Reader, msg ...string) (input string)

PressAnyKeyToContinue lets program pause and wait for user's ANY key press in console/terminal

func PressEnterToContinue added in v1.6.8

func PressEnterToContinue(in io.Reader, msg ...string) (input string)

PressEnterToContinue lets program pause and wait for user's ENTER key press in console/terminal

func RemoveDirRecursive added in v1.6.3

func RemoveDirRecursive(dir string) (err error)

RemoveDirRecursive removes a directory and any children it contains.

func RemoveOnConfigLoadedListener

func RemoveOnConfigLoadedListener(c ConfigReloaded)

RemoveOnConfigLoadedListener remove an functor on config loaded and merged

func ResetOptions added in v0.2.19

func ResetOptions()

ResetOptions to reset the exists `Options`, so that you could follow a `LoadConfigFile()` with it.

func SaveAsJSON added in v0.2.17

func SaveAsJSON(filename string) (err error)

SaveAsJSON to Save all config entries as a json file

func SaveAsToml added in v0.2.17

func SaveAsToml(filename string) (err error)

SaveAsToml to Save all config entries as a toml file

func SaveAsYaml added in v0.2.17

func SaveAsYaml(filename string) (err error)

SaveAsYaml to Save all config entries as a yaml file

func SaveObjAsToml added in v0.2.19

func SaveObjAsToml(obj interface{}, filename string) (err error)

SaveObjAsToml to Save an object as a toml file

func Set added in v0.2.3

func Set(key string, val interface{})

Set set the value of an `Option` key (with prefix auto-wrap). The key MUST not have an `app` prefix. eg:

cmdr.Set("logger.level", "DEBUG")
cmdr.Set("ms.tags.port", 8500)
...
cmdr.Set("debug", true)
cmdr.GetBool("app.debug") => true

func SetNx added in v0.2.3

func SetNx(key string, val interface{})

SetNx but without prefix auto-wrapped. `rxxtPrefix` is a string slice to define the prefix string array, default is ["app"]. So, cmdr.Set("debug", true) will put an real entry with (`app.debug`, true).

func SetOnConfigLoadedListener

func SetOnConfigLoadedListener(c ConfigReloaded, enabled bool)

SetOnConfigLoadedListener enable/disable an functor on config loaded and merged

func SignalQuitSignal added in v1.6.7

func SignalQuitSignal()

SignalQuitSignal post a SIGQUIT signal to the current process

func SignalTermSignal added in v1.6.7

func SignalTermSignal()

SignalTermSignal post a SIGTERM signal to the current process

func SignalToSelf added in v1.6.7

func SignalToSelf(sig os.Signal) (err error)

SignalToSelf trigger the sig signal to the current process

func Soundex added in v0.2.25

func Soundex(s string) (snd4 string)

Soundex returns the english word's soundex value, such as: 'tags' => 't322'

func StripOrderPrefix added in v0.2.9

func StripOrderPrefix(s string) string

StripOrderPrefix strips the prefix string fragment for sorting order. see also: Command.Group, Flag.Group, ...

func StripPrefix added in v1.6.8

func StripPrefix(s, p string) string

StripPrefix strips the prefix 'p' from a string 's'

func StripQuotes added in v1.6.8

func StripQuotes(s string) string

StripQuotes strips single or double quotes around a string.

func TrapSignals added in v1.1.7

func TrapSignals(onTrapped func(s os.Signal), signals ...os.Signal) (waiter func())

TrapSignals is a helper for simplify your infinite loop codes.

Usage

 func enteringLoop() {
	  waiter := cmdr.TrapSignals(func(s os.Signal) {
	    logrus.Debugf("receive signal '%v' in onTrapped()", s)
	  })
	  go waiter()
 }

func TrapSignalsEnh added in v1.6.7

func TrapSignalsEnh(done chan bool, onTrapped func(s os.Signal), signals ...os.Signal) (waiter func())

TrapSignalsEnh is a helper for simplify your infinite loop codes.

Usage

 func enteringLoop() {
   done := make(chan bool, 1)
   go func(done chan bool){
      // your main serve loop
      done <- true   // to end the TrapSignalsEnh waiter by manually, instead of os signals caught.
   }(done)
	  waiter := cmdr.TrapSignalsEnh(done, func(s os.Signal) {
	    logrus.Debugf("receive signal '%v' in onTrapped()", s)
	  })
	  go waiter()
 }

func WalkAllCommands added in v0.2.9

func WalkAllCommands(walk func(cmd *Command, index int) (err error)) (err error)

WalkAllCommands loops for all commands, starting from root.

func WrapWithRxxtPrefix added in v0.2.23

func WrapWithRxxtPrefix(key string) string

WrapWithRxxtPrefix wrap an key with [RxxtPrefix], for [GetXxx(key)] and [GetXxxP(prefix,key)]

Types

type BaseOpt

type BaseOpt struct {
	Name string
	// Short rune. short option/command name.
	// single char. example for flag: "a" -> "-a"
	Short string
	// Full full/long option/command name.
	// word string. example for flag: "addr" -> "--addr"
	Full string
	// Aliases are the more synonyms
	Aliases []string
	// Group group name
	Group string

	Description     string
	LongDescription string
	Examples        string
	Hidden          bool

	// Deprecated is a version string just like '0.5.9' or 'v0.5.9', that means this command/flag was/will be deprecated since `v0.5.9`.
	Deprecated string

	// Action is callback for the last recognized command/sub-command.
	// return: ErrShouldBeStopException will break the following flow and exit right now
	// cmd 是 flag 被识别时已经得到的子命令
	Action func(cmd *Command, args []string) (err error)
	// contains filtered or unexported fields
}

BaseOpt is base of `Command`, `Flag`

func (*BaseOpt) GetLongTitleNamesArray added in v0.2.3

func (s *BaseOpt) GetLongTitleNamesArray() []string

GetLongTitleNamesArray returns long name and aliases as an array

func (*BaseOpt) GetShortTitleNamesArray added in v0.2.3

func (s *BaseOpt) GetShortTitleNamesArray() []string

GetShortTitleNamesArray returns short name as an array

func (*BaseOpt) GetTitleName

func (s *BaseOpt) GetTitleName() string

GetTitleName returns name/full/short string

func (*BaseOpt) GetTitleNames

func (s *BaseOpt) GetTitleNames() string

GetTitleNames return the joint string of short,full,aliases names

func (*BaseOpt) GetTitleNamesArray

func (s *BaseOpt) GetTitleNamesArray() []string

GetTitleNamesArray returns short,full,aliases names

func (*BaseOpt) GetTitleNamesBy

func (s *BaseOpt) GetTitleNamesBy(delimChar string) string

GetTitleNamesBy returns the joint string of short,full,aliases names

func (*BaseOpt) HasParent added in v0.2.9

func (s *BaseOpt) HasParent() bool

HasParent detects whether owner is available or not

type Command

type Command struct {
	BaseOpt

	Flags []*Flag

	SubCommands []*Command
	// return: ErrShouldBeStopException will break the following flow and exit right now
	PreAction func(cmd *Command, args []string) (err error)
	// PostAction will be run after Action() invoked.
	PostAction func(cmd *Command, args []string)
	// be shown at tail of command usages line. Such as for TailPlaceHolder="<host-fqdn> <ipv4/6>":
	// austr dns add <host-fqdn> <ipv4/6> [Options] [Parent/Global Options]
	TailPlaceHolder string
	// contains filtered or unexported fields
}

Command holds the structure of commands and sub-commands

func FindSubCommand added in v0.2.17

func FindSubCommand(longName string, cmd *Command) (res *Command)

FindSubCommand find sub-command with `longName` from `cmd` if cmd == nil: finding from root command

func FindSubCommandRecursive added in v0.2.17

func FindSubCommandRecursive(longName string, cmd *Command) (res *Command)

FindSubCommandRecursive find sub-command with `longName` from `cmd` recursively if cmd == nil: finding from root command

func Match added in v1.6.17

func Match(inputCommandlineWithoutArg0 string, opts ...ExecOption) (last *Command, err error)

Match try parsing the input command-line, the result is the last hit *Command.

func (*Command) FindFlag added in v1.5.1

func (c *Command) FindFlag(longName string) (res *Flag)

FindFlag find flag with `longName` from `cmd`

func (*Command) FindFlagRecursive added in v1.5.1

func (c *Command) FindFlagRecursive(longName string) (res *Flag)

FindFlagRecursive find flag with `longName` from `cmd` recursively

func (*Command) FindSubCommand added in v1.5.1

func (c *Command) FindSubCommand(longName string) (res *Command)

FindSubCommand find sub-command with `longName` from `cmd`

func (*Command) FindSubCommandRecursive added in v1.5.1

func (c *Command) FindSubCommandRecursive(longName string) (res *Command)

FindSubCommandRecursive find sub-command with `longName` from `cmd` recursively

func (*Command) GetDottedNamePath added in v1.6.19

func (c *Command) GetDottedNamePath() string

GetDottedNamePath return the dotted key path of this command in the options store. For example, the returned string just like: 'server.start'. NOTE that there is no OptiontPrefixes in this key path. For more information about Option Prefix, refer to WithOptionsPrefix

func (*Command) GetExpandableNames

func (c *Command) GetExpandableNames() string

GetExpandableNames returns the names comma splitted string.

func (*Command) GetExpandableNamesArray

func (c *Command) GetExpandableNamesArray() []string

GetExpandableNamesArray returns the names array of command, includes short name and long name.

func (*Command) GetHitStr added in v0.2.11

func (c *Command) GetHitStr() string

GetHitStr returns the matched command string

func (*Command) GetName

func (c *Command) GetName() string

GetName returns the name of a `Command`.

func (*Command) GetOwner added in v0.2.19

func (c *Command) GetOwner() *Command

GetOwner returns the parent command object

func (*Command) GetParentName

func (c *Command) GetParentName() string

GetParentName returns the owner command name

func (*Command) GetQuotedGroupName

func (c *Command) GetQuotedGroupName() string

GetQuotedGroupName returns the group name quoted string.

func (*Command) GetRoot

func (c *Command) GetRoot() *RootCommand

GetRoot returns the `RootCommand`

func (*Command) GetSubCommandNamesBy

func (c *Command) GetSubCommandNamesBy(delimChar string) string

GetSubCommandNamesBy returns the joint string of subcommands

func (*Command) IsRoot added in v0.2.9

func (c *Command) IsRoot() bool

IsRoot returns true if this command is a RootCommand

func (*Command) PrintBuildInfo added in v1.5.0

func (c *Command) PrintBuildInfo()

PrintBuildInfo print building information

func (*Command) PrintHelp

func (c *Command) PrintHelp(justFlags bool)

PrintHelp prints help screen

func (*Command) PrintVersion

func (c *Command) PrintVersion()

PrintVersion prints versions information

type ConfigReloaded

type ConfigReloaded interface {
	OnConfigReloaded()
}

ConfigReloaded for config reloaded

type Copier added in v0.2.3

type Copier interface {
	SetIgnoreNames(ignoreNames ...string) Copier
	SetEachFieldAlways(b bool) Copier
	Copy(toValue interface{}, fromValue interface{}, ignoreNames ...string) (err error)
}

Copier interface Copier is based on from github.com/jinzhu/copier

type DistanceOption added in v1.1.3

type DistanceOption func(StringDistance)

DistanceOption is a functional options prototype

func JWWithThreshold added in v1.1.3

func JWWithThreshold(threshold float64) DistanceOption

JWWithThreshold sets the threshold for Jaro-Winkler algorithm.

type ErrorForCmdr added in v1.0.2

type ErrorForCmdr struct {
	// Inner     error
	// Msg       string
	Ignorable bool
	// contains filtered or unexported fields
}

ErrorForCmdr structure

func (*ErrorForCmdr) As added in v1.6.21

func (w *ErrorForCmdr) As(target interface{}) bool

As finds the first error in err's chain that matches target, and if so, sets target to that error value and returns true.

func (*ErrorForCmdr) Attach added in v1.6.9

func (w *ErrorForCmdr) Attach(errs ...error)

Attach appends errs. For ErrorForCmdr, only one last error will be kept.

func (*ErrorForCmdr) Cause added in v1.6.21

func (w *ErrorForCmdr) Cause() error

Cause returns the underlying cause of the error recursively, if possible.

func (*ErrorForCmdr) Error added in v1.0.2

func (w *ErrorForCmdr) Error() string

func (*ErrorForCmdr) FormatNew added in v1.6.21

func (w *ErrorForCmdr) FormatNew(ignorable bool, livedArgs ...interface{}) *errors.WithStackInfo

FormatNew creates a new error object based on this error template 'w'.

Example:

errTmpl1001 := BUG1001.NewTemplate("something is wrong %v")
err4 := errTmpl1001.FormatNew("ok").Attach(errBug1)
fmt.Println(err4)
fmt.Printf("%+v\n", err4)

func (*ErrorForCmdr) Is added in v1.6.21

func (w *ErrorForCmdr) Is(target error) bool

Is reports whether any error in err's chain matches target.

func (*ErrorForCmdr) Unwrap added in v1.6.21

func (w *ErrorForCmdr) Unwrap() error

Unwrap returns the result of calling the Unwrap method on err, if err's type contains an Unwrap method returning error. Otherwise, Unwrap returns nil.

type ExecOption added in v1.5.0

type ExecOption func(w *ExecWorker)

ExecOption is the functional option for Exec()

func WithAfterArgsParsed added in v1.6.3

func WithAfterArgsParsed(hookFunc func(cmd *Command, args []string) (err error)) ExecOption

WithAfterArgsParsed sets a callback point after command-line args parsed by cmdr internal exec().

Your callback func will be invoked before invoking the matched command `cmd`. At this time, all command-line args parsed and a command found.

If program was launched with empty or wrong arguments, your callback func won't be triggered.

When empty argument or `--help` found, cmdr will display help screen. To customize it see also cmdr.WithCustomShowVersion and cmdr.WithCustomShowBuildInfo.

When any wrong/warn arguments found, cmdr will display some tip messages. To customize it see also cmdr.WithUnknownOptionHandler.

func WithAutomaticEnvHooks added in v1.5.1

func WithAutomaticEnvHooks(hook HookOptsFunc) ExecOption

WithAutomaticEnvHooks sets the hook after building automatic environment.

At this point, you could override the option default values.

func WithBuiltinCommands added in v1.5.0

func WithBuiltinCommands(versionsCmds, helpCmds, verboseCmds, generateCmds, generalCmdrCmds bool) ExecOption

WithBuiltinCommands enables/disables those builtin predefined commands. Such as:

  • versionsCmds / EnableVersionCommands supports injecting the default `--version` flags and commands
  • helpCmds / EnableHelpCommands supports injecting the default `--help` flags and commands
  • verboseCmds / EnableVerboseCommands supports injecting the default `--verbose` flags and commands
  • generalCmdrCmds / EnableCmdrCommands support these flags: `--strict-mode`, `--no-env-overrides`, and `--no-color`
  • generateCmds / EnableGenerateCommands supports injecting the default `generate` commands and sub-commands

func WithConfigLoadedListener added in v1.5.0

func WithConfigLoadedListener(c ConfigReloaded) ExecOption

WithConfigLoadedListener adds a functor on config loaded and merged

func WithCustomShowBuildInfo added in v1.5.0

func WithCustomShowBuildInfo(fn func()) ExecOption

WithCustomShowBuildInfo supports your `ShowBuildInfo()` instead of internal `showBuildInfo()`

func WithCustomShowVersion added in v1.5.0

func WithCustomShowVersion(fn func()) ExecOption

WithCustomShowVersion supports your `ShowVersion()` instead of internal `showVersion()`

func WithEnvPrefix added in v1.5.0

func WithEnvPrefix(prefix ...string) ExecOption

WithEnvPrefix sets the environment variable text prefixes. cmdr will lookup envvars for a key. Default env-prefix is array ["CMDR"], ie 'CMDR_'

func WithEnvVarMap added in v1.6.3

func WithEnvVarMap(varToValue map[string]func() string) ExecOption

WithEnvVarMap adds a (envvar-name, value) map, which will be applied to string option value, string-slice option values, .... For example, you could define a key-value entry in your `<app>.yml` file:

app:
  test-value: "$THIS/$APPNAME.yml"
  home-dir: "$HOME"

it will be expanded by mapping to OS environment and this map (WithEnvVarMap). That is, $THIS will be expanded to the directory path of this executable, $APPNAME to the app name. And of course, $HOME will be mapped to os home directory path.

func WithHelpPainter added in v1.5.0

func WithHelpPainter(painter Painter) ExecOption

WithHelpPainter allows to change the behavior and facade of help screen.

func WithHelpTabStop added in v1.5.0

func WithHelpTabStop(tabStop int) ExecOption

WithHelpTabStop sets the tab-stop position in the help screen Default tabstop is 48

func WithHelpTailLine added in v1.6.11

func WithHelpTailLine(line string) ExecOption

WithHelpTailLine setup the tail line in help screen

Default line is:

"\nType '-h' or '--help' to get command help screen."

func WithIgnoreWrongEnumValue added in v1.5.0

func WithIgnoreWrongEnumValue(ignored bool) ExecOption

WithIgnoreWrongEnumValue will be put into `cmdrError.Ignorable` while wrong enumerable value found in parsing command-line options. The default is true.

Main program might decide whether it's a warning or error.

See also

[Flag.ValidArgs]

func WithInternalOutputStreams added in v1.5.0

func WithInternalOutputStreams(out, err *bufio.Writer) ExecOption

WithInternalOutputStreams sets the internal output streams for debugging

func WithLogex added in v1.6.3

func WithLogex(lvl Level, opts ...logex.LogexOption) ExecOption

WithLogex enables logex integration

func WithLogexPrefix added in v1.6.5

func WithLogexPrefix(prefix string) ExecOption

WithLogexPrefix specify a prefix string PS.

In cmdr options store, we will load the logging options under this key path:

app:
  logger:
    level:  DEBUG            # panic, fatal, error, warn, info, debug, trace, off
    format: text             # text, json, logfmt
    target: default          # default, todo: journal

As showing above, the default prefix is "logger". You can replace it with yours, via WithLogexPrefix(). For example, when you compose WithLogexPrefix("logging"), the following entries would be applied:

app:
  logging:
    level:  DEBUG
    format:
    target:

func WithLogexSkipFrames added in v1.6.31

func WithLogexSkipFrames(skipFrames int) ExecOption

WithLogexSkipFrames specify the skip frames to lookup the caller

func WithNoColor added in v1.6.3

func WithNoColor(b bool) ExecOption

WithNoColor make console outputs plain and without ANSI escape colors

Since v1.6.2+

func WithNoCommandAction added in v1.6.17

func WithNoCommandAction(b bool) ExecOption

WithNoCommandAction do NOT run the action of the matched command.

func WithNoDefaultHelpScreen added in v1.6.0

func WithNoDefaultHelpScreen(b bool) ExecOption

WithNoDefaultHelpScreen true to disable printing help screen if without any arguments

func WithNoEnvOverrides added in v1.6.3

func WithNoEnvOverrides(b bool) ExecOption

WithNoEnvOverrides enables the internal no-env-overrides mode

Since v1.6.2+

In this mode, cmdr do NOT find and transfer equivalent envvar value into cmdr options store.

func WithNoLoadConfigFiles added in v1.5.0

func WithNoLoadConfigFiles(b bool) ExecOption

WithNoLoadConfigFiles true means no loading config files

func WithNoWatchConfigFiles added in v1.6.9

func WithNoWatchConfigFiles(b bool) ExecOption

WithNoWatchConfigFiles true means no watching the config files

func WithOnPassThruCharHit added in v1.6.18

func WithOnPassThruCharHit(fn func(parsed *Command, switchChar string, args []string) (err error)) ExecOption

WithOnPassThruCharHit handle the passthrough char(s) (i.e. '--') matched For example, type `bin/fluent mx -d -- --help` will trigger this callback at the 2nd flag '--'.

func WithOnSwitchCharHit added in v1.6.18

func WithOnSwitchCharHit(fn func(parsed *Command, switchChar string, args []string) (err error)) ExecOption

WithOnSwitchCharHit handle the exact single switch-char (such as '-', '/', '~') matched. For example, type `bin/fluent mx -d - --help` will trigger this callback at the 2nd flag '-'.

func WithOptionMergeModifying added in v1.6.12

func WithOptionMergeModifying(onMergingSet func(keyPath string, value, oldVal interface{})) ExecOption

WithOptionMergeModifying adds a callback which invoked on new configurations was merging into, typically on loading the modified external config file(s). NOTE that MergeWith(...) can make it triggered too. A onMergingSet callback will be enabled after first loaded any external configuration files and environment variables merged.

func WithOptionModifying added in v1.6.12

func WithOptionModifying(onOptionSet func(keyPath string, value, oldVal interface{})) ExecOption

WithOptionModifying adds a callback which invoked at each time any option was modified. It will be enabled after any external config files first loaded and the env variables had been merged.

func WithOptionsPrefix added in v1.5.0

func WithOptionsPrefix(prefix ...string) ExecOption

WithOptionsPrefix create a top-level namespace, which contains all normalized `Flag`s. =WithRxxtPrefix Default Options Prefix is array ["app"], ie 'app.xxx'

func WithPredefinedLocations added in v1.5.0

func WithPredefinedLocations(locations ...string) ExecOption

WithPredefinedLocations sets the environment variable text prefixes. cmdr will lookup envvars for a key. Default locations are:

[]string{
  "./ci/etc/%s/%s.yml",       // for developer
  "/etc/%s/%s.yml",           // regular location
  "/usr/local/etc/%s/%s.yml", // regular macOS HomeBrew location
  "$HOME/.config/%s/%s.yml",  // per user
  "$HOME/.%s/%s.yml",         // ext location per user
  "$THIS/%s.yml",             // executable's directory
  "%s.yml",                   // current directory
},

See also InternalResetWorker

func WithRxxtPrefix added in v1.5.0

func WithRxxtPrefix(prefix ...string) ExecOption

WithRxxtPrefix create a top-level namespace, which contains all normalized `Flag`s. cmdr will lookup envvars for a key. Default Options Prefix is array ["app"], ie 'app.xxx'

func WithSimilarThreshold added in v1.5.5

func WithSimilarThreshold(similiarThreshold float64) ExecOption

WithSimilarThreshold defines a threshold for command/option similar detector. Default threshold is 0.6666666666666666. See also JaroWinklerDistance

func WithStrictMode added in v1.6.3

func WithStrictMode(b bool) ExecOption

WithStrictMode enables the internal strict mode

Since v1.6.2+

In this mode, any warnings will be treat as an error and cause app fatal exit.

In normal mode, these cases are assumed as warnings: - flag name not found - command or sub-command name not found - value extracting failed - ...

func WithUnhandledErrorHandler added in v1.6.13

func WithUnhandledErrorHandler(handler UnhandledErrorHandler) ExecOption

WithUnhandledErrorHandler handle the panics or exceptions generally

func WithUnknownOptionHandler added in v1.5.5

func WithUnknownOptionHandler(handler UnknownOptionHandler) ExecOption

WithUnknownOptionHandler enables your customized wrong command/flag processor. internal processor supports smart suggestions for those wrong commands and flags.

func WithWatchMainConfigFileToo added in v1.6.9

func WithWatchMainConfigFileToo(b bool) ExecOption

WithWatchMainConfigFileToo enables the watcher on main config file. By default, cmdr watches all files in the sub-directory `conf.d` of which folder contains the main config file. But as a feature, cmdr ignore the changes in main config file.

WithWatchMainConfigFileToo can switch this feature.

envvars:

CFG_DIR: will be set to the folder contains the main config file
no-watch-conf-dir: if set true, the watcher will be disabled.

func WithXrefBuildingHooks added in v1.5.0

func WithXrefBuildingHooks(beforeXrefBuildingX, afterXrefBuiltX HookFunc) ExecOption

WithXrefBuildingHooks sets the hook before and after building xref indices. It's replacers for AddOnBeforeXrefBuilding, and AddOnAfterXrefBuilt.

By using beforeXrefBuildingX, you could append, modify, or remove the builtin commands and options.

type ExecWorker added in v1.5.0

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

ExecWorker is a core logic worker and holder

func (*ExecWorker) AddOnAfterXrefBuilt added in v1.5.0

func (w *ExecWorker) AddOnAfterXrefBuilt(cb HookFunc)

AddOnAfterXrefBuilt add hook func daemon plugin needed

func (*ExecWorker) AddOnBeforeXrefBuilding added in v1.5.0

func (w *ExecWorker) AddOnBeforeXrefBuilding(cb HookFunc)

AddOnBeforeXrefBuilding add hook func daemon plugin needed

func (*ExecWorker) InternalExecFor added in v1.5.0

func (w *ExecWorker) InternalExecFor(rootCmd *RootCommand, args []string) (last *Command, err error)

InternalExecFor is an internal helper, esp for debugging

type Flag

type Flag struct {
	BaseOpt

	// ToggleGroup for Toggle Group
	ToggleGroup string
	// DefaultValuePlaceholder for flag
	DefaultValuePlaceholder string
	// DefaultValue default value for flag
	DefaultValue interface{}
	// ValidArgs for enum flag
	ValidArgs []string
	// Required to-do
	Required bool

	// ExternalTool to get the value text by invoking external tool.
	// It's an environment variable name, such as: "EDITOR" (or cmdr.ExternalToolEditor)
	ExternalTool string

	// EnvVars give a list to bind to environment variables manually
	// it'll take effects since v1.6.9
	EnvVars []string

	// HeadLike enables a free-hand option like `head -3`.
	//
	// When a free-hand option presents, it'll be treated as a named option with an integer value.
	//
	// For example, option/flag = `{{Full:"line",Short:"l"},HeadLike:true}`, the command line:
	// `app -3`
	// is equivalent to `app -l 3`, and so on.
	//
	// HeadLike assumed an named option with an integer value, that means, Min and Max can be applied on it too.
	// NOTE: Only one head-like option can be defined in a command/sub-command chain.
	HeadLike bool

	// Min minimal value of a range.
	Min int64
	// Max maximal value of a range.
	Max int64
	// contains filtered or unexported fields
}

Flag means a flag, a option, or a opt.

func FindFlag added in v0.2.17

func FindFlag(longName string, cmd *Command) (res *Flag)

FindFlag find flag with `longName` from `cmd` if cmd == nil: finding from root command

func FindFlagRecursive added in v0.2.17

func FindFlagRecursive(longName string, cmd *Command) (res *Flag)

FindFlagRecursive find flag with `longName` from `cmd` recursively if cmd == nil: finding from root command

func (*Flag) GetDescZsh added in v0.2.13

func (s *Flag) GetDescZsh() (desc string)

GetDescZsh temp

func (*Flag) GetTitleFlagNames added in v0.2.13

func (s *Flag) GetTitleFlagNames() string

GetTitleFlagNames temp

func (*Flag) GetTitleFlagNamesBy added in v0.2.13

func (s *Flag) GetTitleFlagNamesBy(delimChar string) string

GetTitleFlagNamesBy temp

func (*Flag) GetTitleFlagNamesByMax added in v0.2.13

func (s *Flag) GetTitleFlagNamesByMax(delimChar string, maxCount int) string

GetTitleFlagNamesByMax temp

func (*Flag) GetTitleZshFlagName added in v0.2.13

func (s *Flag) GetTitleZshFlagName() (str string)

GetTitleZshFlagName temp

func (*Flag) GetTitleZshFlagNames added in v0.2.13

func (s *Flag) GetTitleZshFlagNames(delimChar string) (str string)

GetTitleZshFlagNames temp

func (*Flag) GetTitleZshFlagNamesArray added in v0.2.13

func (s *Flag) GetTitleZshFlagNamesArray() (ary []string)

GetTitleZshFlagNamesArray temp

func (*Flag) GetTriggeredTimes added in v1.5.1

func (s *Flag) GetTriggeredTimes() int

GetTriggeredTimes returns the matched times

type HookFunc added in v1.5.1

type HookFunc func(root *RootCommand, args []string)

HookFunc the hook function prototype for SetBeforeXrefBuilding and SetAfterXrefBuilt

type HookOptsFunc added in v1.5.1

type HookOptsFunc func(root *RootCommand, opts *Options)

HookOptsFunc the hook function prototype

type Level added in v1.6.25

type Level uint32

Level type

const (
	// PanicLevel level, highest level of severity. Logs and then calls panic with the
	// message passed to Debug, Info, ...
	PanicLevel Level = iota
	// FatalLevel level. Logs and then calls `logger.Exit(1)`. It will exit even if the
	// logging level is set to Panic.
	FatalLevel
	// ErrorLevel level. Logs. Used for errors that should definitely be noted.
	// Commonly used for hooks to send errors to an error tracking service.
	ErrorLevel
	// WarnLevel level. Non-critical entries that deserve eyes.
	WarnLevel
	// InfoLevel level. General operational entries about what's going on inside the
	// application.
	InfoLevel
	// DebugLevel level. Usually only enabled when debugging. Very verbose logging.
	DebugLevel
	// TraceLevel level. Designates finer-grained informational events than the Debug.
	TraceLevel
	// OffLevel level. The logger will be shutdown.
	OffLevel
)

These are the different logging levels. You can set the logging level to log on your instance of logger, obtained with `logrus.New()`.

func GetLoggerLevel added in v1.6.25

func GetLoggerLevel() Level

GetLoggerLevel returns the current logger level after parsed.

func ParseLevel added in v1.6.25

func ParseLevel(lvl string) (Level, error)

ParseLevel takes a string level and returns the Logrus log level constant.

func (Level) MarshalText added in v1.6.25

func (level Level) MarshalText() ([]byte, error)

MarshalText convert Level to string and []byte

func (Level) String added in v1.6.25

func (level Level) String() string

Convert the Level to a string. E.g. PanicLevel becomes "panic".

func (*Level) UnmarshalText added in v1.6.25

func (level *Level) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

type OnSet added in v1.6.8

type OnSet interface {
	// OnSet will be callback'd after this flag parsed
	OnSet(f func(keyPath string, value interface{})) (opt OptFlag)
}

OnSet interface

type OptCmd added in v0.2.15

type OptCmd interface {
	Titles(short, long string, aliases ...string) (opt OptCmd)
	Short(short string) (opt OptCmd)
	Long(long string) (opt OptCmd)
	Aliases(ss ...string) (opt OptCmd)
	Description(oneLine string, long ...string) (opt OptCmd)
	Examples(examples string) (opt OptCmd)
	Group(group string) (opt OptCmd)
	Hidden(hidden bool) (opt OptCmd)
	Deprecated(deprecation string) (opt OptCmd)
	// Action will be triggered after all command-line arguments parsed
	Action(action func(cmd *Command, args []string) (err error)) (opt OptCmd)

	// PreAction will be invoked before running Action
	// NOTE that RootCommand.PreAction will be invoked too.
	PreAction(pre func(cmd *Command, args []string) (err error)) (opt OptCmd)
	// PostAction will be invoked after run Action
	// NOTE that RootCommand.PostAction will be invoked too.
	PostAction(post func(cmd *Command, args []string)) (opt OptCmd)

	TailPlaceholder(placeholder string) (opt OptCmd)

	// NewFlag create a new flag object and return it for further operations.
	// Deprecated since v1.6.9, replace it with FlagV(defaultValue)
	NewFlag(typ OptFlagType) (opt OptFlag)
	// NewFlagV create a new flag object and return it for further operations.
	// the titles in arguments MUST be: longTitle, [shortTitle, [aliasTitles...]]
	NewFlagV(defaultValue interface{}, titles ...string) (opt OptFlag)
	// NewSubCommand make a new sub-command optcmd object with optional titles.
	// the titles in arguments MUST be: longTitle, [shortTitle, [aliasTitles...]]
	NewSubCommand(titles ...string) (opt OptCmd)

	OwnerCommand() (opt OptCmd)
	SetOwner(opt OptCmd)

	RootCommand() *RootCommand

	ToCommand() *Command

	AddOptFlag(flag OptFlag)
	AddFlag(flag *Flag)
	// AddOptCmd adds 'opt' OptCmd as a sub-command
	AddOptCmd(opt OptCmd)
	// AddCommand adds a *Command as a sub-command
	AddCommand(cmd *Command)
	// AttachTo attaches itself as a sub-command of 'opt' OptCmd object
	AttachTo(opt OptCmd)
	// AttachTo attaches itself as a sub-command of *Command object
	AttachToCommand(cmd *Command)
	// AttachTo attaches itself as a sub-command of *RootCommand object
	AttachToRoot(root *RootCommand)
}

OptCmd to support fluent api of cmdr. see also: cmdr.Root().NewSubCommand()/.NewFlag()

func NewCmd added in v0.2.17

func NewCmd() (opt OptCmd)

NewCmd creates a wrapped Command object as OptCmd

func NewCmdFrom added in v0.2.17

func NewCmdFrom(cmd *Command) (opt OptCmd)

NewCmdFrom creates a wrapped Command object as OptCmd, and make it as the current working item.

func NewSubCmd added in v0.2.17

func NewSubCmd() (opt OptCmd)

NewSubCmd creates a wrapped Command object as OptCmd, and append it into the current working item.

type OptFlag added in v0.2.15

type OptFlag interface {
	Titles(short, long string, aliases ...string) (opt OptFlag)
	Short(short string) (opt OptFlag)
	Long(long string) (opt OptFlag)
	Aliases(ss ...string) (opt OptFlag)
	Description(oneLineDesc string, longDesc ...string) (opt OptFlag)
	Examples(examples string) (opt OptFlag)
	Group(group string) (opt OptFlag)
	Hidden(hidden bool) (opt OptFlag)
	Deprecated(deprecation string) (opt OptFlag)
	// Action will be triggered once being parsed ok
	Action(action func(cmd *Command, args []string) (err error)) (opt OptFlag)

	ToggleGroup(group string) (opt OptFlag)
	// DefaultValue needs an exact typed 'val'.
	// IMPORTANT: cmdr interprets value type of an option based on the underlying default value set.
	DefaultValue(val interface{}, placeholder string) (opt OptFlag)
	Placeholder(placeholder string) (opt OptFlag)
	ExternalTool(envKeyName string) (opt OptFlag)
	ValidArgs(list ...string) (opt OptFlag)
	// HeadLike enables `head -n` mode.
	// 'min', 'max' will be ignored at this version, its might be impl in the future.
	// There's only one head-like flag in one command and its parent and children commands.
	HeadLike(enable bool, min, max int64) (opt OptFlag)

	// EnvKeys is a list of env-var names of binding on this flag
	EnvKeys(keys ...string) (opt OptFlag)

	OwnerCommand() (opt OptCmd)
	SetOwner(opt OptCmd)

	RootCommand() *RootCommand

	ToFlag() *Flag

	// AttachTo attach as a flag of `opt` OptCmd object
	AttachTo(opt OptCmd)
	// AttachToCommand attach as a flag of *Command object
	AttachToCommand(cmd *Command)
	// AttachToRoot attach as a flag of *RootCommand object
	AttachToRoot(root *RootCommand)

	OnSet
}

OptFlag to support fluent api of cmdr. see also: cmdr.Root().NewSubCommand()/.NewFlag()

For an option, its default value must be declared with exact type as is

func NewBool added in v0.2.17

func NewBool(defaultValue bool) (opt OptFlag)

NewBool creates a wrapped OptFlag, you can connect it to a OptCmd via OptFlag.AttachXXX later.

func NewComplex128 added in v1.6.21

func NewComplex128(defaultValue complex128) (opt OptFlag)

NewComplex128 creates a wrapped OptFlag, you can connect it to a OptCmd via OptFlag.AttachXXX later.

func NewComplex64 added in v1.6.21

func NewComplex64(defaultValue complex64) (opt OptFlag)

NewComplex64 creates a wrapped OptFlag, you can connect it to a OptCmd via OptFlag.AttachXXX later.

func NewDuration added in v0.2.17

func NewDuration(defaultValue time.Duration) (opt OptFlag)

NewDuration creates a wrapped OptFlag, you can connect it to a OptCmd via OptFlag.AttachXXX later.

func NewDurationFrom added in v1.0.3

func NewDurationFrom(flg *Flag) (opt OptFlag)

NewDurationFrom creates a wrapped OptFlag, and append it into the current working item.

func NewFloat32 added in v1.0.1

func NewFloat32(defaultValue float32) (opt OptFlag)

NewFloat32 creates a wrapped OptFlag, you can connect it to a OptCmd via OptFlag.AttachXXX later.

func NewFloat64 added in v1.0.1

func NewFloat64(defaultValue float64) (opt OptFlag)

NewFloat64 creates a wrapped OptFlag, you can connect it to a OptCmd via OptFlag.AttachXXX later.

func NewInt added in v0.2.17

func NewInt(defaultValue int) (opt OptFlag)

NewInt creates a wrapped OptFlag, you can connect it to a OptCmd via OptFlag.AttachXXX later.

func NewInt64 added in v0.2.17

func NewInt64(defaultValue int64) (opt OptFlag)

NewInt64 creates a wrapped OptFlag, you can connect it to a OptCmd via OptFlag.AttachXXX later.

func NewIntSlice added in v0.2.17

func NewIntSlice(defaultValue []int) (opt OptFlag)

NewIntSlice creates a wrapped OptFlag, you can connect it to a OptCmd via OptFlag.AttachXXX later.

func NewString added in v0.2.17

func NewString(defaultValue string) (opt OptFlag)

NewString creates a wrapped OptFlag, you can connect it to a OptCmd via OptFlag.AttachXXX later.

func NewStringSlice added in v0.2.17

func NewStringSlice(defaultValue []string) (opt OptFlag)

NewStringSlice creates a wrapped OptFlag, you can connect it to a OptCmd via OptFlag.AttachXXX later.

func NewUint added in v0.2.17

func NewUint(defaultValue uint) (opt OptFlag)

NewUint creates a wrapped OptFlag, you can connect it to a OptCmd via OptFlag.AttachXXX later.

func NewUint64 added in v0.2.17

func NewUint64(defaultValue uint64) (opt OptFlag)

NewUint64 creates a wrapped OptFlag, you can connect it to a OptCmd via OptFlag.AttachXXX later.

type OptFlagType added in v0.2.15

type OptFlagType int

OptFlagType to support fluent api of cmdr. see also: OptCmd.NewFlag(OptFlagType)

Usage

root := cmdr.Root()
co := root.NewSubCommand()
co.NewFlag(cmdr.OptFlagTypeUint)

See also those short-hand constructors: Bool(), Int(), ....

const (
	// OptFlagTypeBool to create a new bool flag
	OptFlagTypeBool OptFlagType = iota
	// OptFlagTypeInt to create a new int flag
	OptFlagTypeInt OptFlagType = iota + 1
	// OptFlagTypeUint to create a new uint flag
	OptFlagTypeUint OptFlagType = iota + 2
	// OptFlagTypeInt64 to create a new int64 flag
	OptFlagTypeInt64 OptFlagType = iota + 3
	// OptFlagTypeUint64 to create a new uint64 flag
	OptFlagTypeUint64 OptFlagType = iota + 4
	// OptFlagTypeFloat32 to create a new int float32 flag
	OptFlagTypeFloat32 OptFlagType = iota + 8
	// OptFlagTypeFloat64 to create a new int float64 flag
	OptFlagTypeFloat64 OptFlagType = iota + 9
	// OptFlagTypeComplex64 to create a new int complex64 flag
	OptFlagTypeComplex64 OptFlagType = iota + 10
	// OptFlagTypeComplex128 to create a new int complex128 flag
	OptFlagTypeComplex128 OptFlagType = iota + 11
	// OptFlagTypeString to create a new string flag
	OptFlagTypeString OptFlagType = iota + 12
	// OptFlagTypeStringSlice to create a new string slice flag
	OptFlagTypeStringSlice OptFlagType = iota + 13
	// OptFlagTypeIntSlice to create a new int slice flag
	OptFlagTypeIntSlice OptFlagType = iota + 14
	// OptFlagTypeInt64Slice to create a new int slice flag
	OptFlagTypeInt64Slice OptFlagType = iota + 15
	// OptFlagTypeUint64Slice to create a new int slice flag
	OptFlagTypeUint64Slice OptFlagType = iota + 16
	// OptFlagTypeDuration to create a new duration flag
	OptFlagTypeDuration OptFlagType = iota + 17
	// OptFlagTypeHumanReadableSize to create a new human readable size flag
	OptFlagTypeHumanReadableSize OptFlagType = iota + 18
)

type Options

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

Options is a holder of all options

func GetOptions added in v1.5.0

func GetOptions() *Options

GetOptions returns the global options instance (rxxtOptions), ie. cmdr Options Store

func (*Options) Delete added in v1.6.3

func (s *Options) Delete(key string)

Delete deletes a key from cmdr options store

func (*Options) DumpAsString

func (s *Options) DumpAsString() (str string)

DumpAsString for debugging.

func (*Options) FromKibibytes added in v1.6.19

func (s *Options) FromKibibytes(sz string) (ir64 uint64)

FromKibibytes convert string to the uint64 value based kibibyte format.

kibibyte format is for human readable. In this format, number presentations are: 2k, 8m, 3g, 5t, 6p, 7e. optional 'b' can be appended, such as: 2kb, 5tb, 7EB. All of them is case-insensitive.

kibibyte is based 1024. That means: 1 KiB = 1k = 1024 bytes

See also: https://en.wikipedia.org/wiki/Kibibyte Its related word is kilobyte, refer to: https://en.wikipedia.org/wiki/Kilobyte

The pure number part can be golang presentation, such as 0x99, 0001b, 0700.

func (*Options) FromKilobytes added in v1.6.19

func (s *Options) FromKilobytes(sz string) (ir64 uint64)

FromKilobytes convert string to the uint64 value based kilobyte format.

kilobyte format is for human readable. In this format, number presentations are: 2k, 8m, 3g, 5t, 6p, 7e. optional 'b' can be appended, such as: 2kb, 5tb, 7EB. All of them is case-insensitive.

kilobyte is based 1000. That means: 1 KB = 1k = 1000 bytes

See also: https://en.wikipedia.org/wiki/Kilobyte Its related word is kibibyte, refer to: https://en.wikipedia.org/wiki/Kibibyte

The pure number part can be golang presentation, such as 0x99, 0001b, 0700.

func (*Options) Get

func (s *Options) Get(key string) interface{}

Get an `Option` by key string, eg: ```golang cmdr.Get("app.logger.level") => 'DEBUG',... ```

func (*Options) GetBoolEx added in v1.6.3

func (s *Options) GetBoolEx(key string, defaultVal ...bool) (ret bool)

GetBoolEx returns the bool value of an `Option` key.

func (*Options) GetComplex128 added in v1.6.21

func (s *Options) GetComplex128(key string, defaultVal ...complex128) (ir complex128)

GetComplex128 returns the complex128 value of an `Option` key.

func (*Options) GetComplex64 added in v1.6.21

func (s *Options) GetComplex64(key string, defaultVal ...complex64) (ir complex64)

GetComplex64 returns the complex64 value of an `Option` key.

func (*Options) GetDuration added in v0.2.11

func (s *Options) GetDuration(key string, defaultVal ...time.Duration) (ir time.Duration)

GetDuration returns the time duration value of an `Option` key.

func (*Options) GetFloat32Ex added in v1.6.3

func (s *Options) GetFloat32Ex(key string, defaultVal ...float32) (ir float32)

GetFloat32Ex returns the float32 value of an `Option` key.

func (*Options) GetFloat64Ex added in v1.6.3

func (s *Options) GetFloat64Ex(key string, defaultVal ...float64) (ir float64)

GetFloat64Ex returns the float64 value of an `Option` key.

func (*Options) GetHierarchyList added in v0.2.17

func (s *Options) GetHierarchyList() map[string]interface{}

GetHierarchyList returns the hierarchy data for dumping

func (*Options) GetInt64Ex added in v1.6.3

func (s *Options) GetInt64Ex(key string, defaultVal ...int64) (ir int64)

GetInt64Ex returns the int64 value of an `Option` key.

func (*Options) GetInt64Slice added in v1.5.5

func (s *Options) GetInt64Slice(key string, defaultVal ...int64) (ir []int64)

GetInt64Slice returns the string slice value of an `Option` key.

func (*Options) GetIntEx added in v1.6.3

func (s *Options) GetIntEx(key string, defaultVal ...int) (ir int)

GetIntEx returns the int64 value of an `Option` key.

func (*Options) GetIntSlice added in v0.2.11

func (s *Options) GetIntSlice(key string, defaultVal ...int) (ir []int)

GetIntSlice returns the string slice value of an `Option` key.

func (*Options) GetKibibytesEx added in v1.6.19

func (s *Options) GetKibibytesEx(key string, defaultVal ...uint64) (ir64 uint64)

GetKibibytesEx returns the uint64 value of an `Option` key based kibibyte format.

kibibyte format is for human readable. In this format, number presentations are: 2k, 8m, 3g, 5t, 6p, 7e. optional 'b' can be appended, such as: 2kb, 5tb, 7EB. All of them is case-insensitive.

kibibyte is based 1024. That means: 1 KiB = 1k = 1024 bytes

See also: https://en.wikipedia.org/wiki/Kibibyte Its related word is kilobyte, refer to: https://en.wikipedia.org/wiki/Kilobyte

The pure number part can be golang presentation, such as 0x99, 0001b, 0700.

func (*Options) GetKilobytesEx added in v1.6.19

func (s *Options) GetKilobytesEx(key string, defaultVal ...uint64) (ir64 uint64)

GetKilobytesEx returns the uint64 value of an `Option` key with kilobyte format.

kilobyte format is for human readable. In this format, number presentations are: 2k, 8m, 3g, 5t, 6p, 7e. optional 'b' can be appended, such as: 2kb, 5tb, 7EB. All of them is case-insensitive.

kilobyte is based 1000. That means: 1 KB = 1k = 1000 bytes

See also: https://en.wikipedia.org/wiki/Kilobyte Its related word is kibibyte, refer to: https://en.wikipedia.org/wiki/Kibibyte

The pure number part can be golang presentation, such as 0x99, 0001b, 0700.

func (*Options) GetMap added in v1.0.0

func (s *Options) GetMap(key string) map[string]interface{}

GetMap an `Option` by key string, it returns a hierarchy map or nil

func (*Options) GetString

func (s *Options) GetString(key string, defaultVal ...string) (ret string)

GetString returns the string value of an `Option` key.

func (*Options) GetStringNoExpand added in v1.6.7

func (s *Options) GetStringNoExpand(key string, defaultVal ...string) (ret string)

GetStringNoExpand returns the string value of an `Option` key.

func (*Options) GetStringSlice

func (s *Options) GetStringSlice(key string, defaultVal ...string) (ir []string)

GetStringSlice returns the string slice value of an `Option` key.

func (*Options) GetUint64Ex added in v1.6.3

func (s *Options) GetUint64Ex(key string, defaultVal ...uint64) (ir uint64)

GetUint64Ex returns the uint64 value of an `Option` key.

func (*Options) GetUint64Slice added in v1.5.5

func (s *Options) GetUint64Slice(key string, defaultVal ...uint64) (ir []uint64)

GetUint64Slice returns the string slice value of an `Option` key.

func (*Options) GetUintEx added in v1.6.3

func (s *Options) GetUintEx(key string, defaultVal ...uint) (ir uint)

GetUintEx returns the uint64 value of an `Option` key.

func (*Options) Has added in v1.6.3

func (s *Options) Has(key string) (ok bool)

Has detects whether a key exists in cmdr options store or not

func (*Options) LoadConfigFile

func (s *Options) LoadConfigFile(file string) (err error)

LoadConfigFile loads a yaml config file and merge the settings into `rxxtOptions` and load files in the `conf.d` child directory too.

func (*Options) MergeWith added in v1.1.4

func (s *Options) MergeWith(m map[string]interface{}) (err error)

MergeWith will merge a map recursive.

func (*Options) Reset

func (s *Options) Reset()

Reset the exists `Options`, so that you could follow a `LoadConfigFile()` with it.

func (*Options) Set

func (s *Options) Set(key string, val interface{})

Set set the value of an `Option` key. The key MUST not have an `app` prefix. eg: ```golang cmdr.Set("debug", true) cmdr.GetBool("app.debug") => true ```

func (*Options) SetNx

func (s *Options) SetNx(key string, val interface{})

SetNx but without prefix auto-wrapped. `rxxtPrefix` is a string slice to define the prefix string array, default is ["app"]. So, cmdr.Set("debug", true) will put an real entry with (`app.debug`, true).

type Painter added in v0.2.9

type Painter interface {
	Printf(fmtStr string, args ...interface{})

	FpPrintHeader(command *Command)
	FpPrintHelpTailLine(command *Command)

	FpUsagesTitle(command *Command, title string)
	FpUsagesLine(command *Command, fmt, appName, cmdList, cmdsTitle, tailPlaceHolder string)
	FpDescTitle(command *Command, title string)
	FpDescLine(command *Command)
	FpExamplesTitle(command *Command, title string)
	FpExamplesLine(command *Command)

	FpCommandsTitle(command *Command)
	FpCommandsGroupTitle(group string)
	FpCommandsLine(command *Command)
	FpFlagsTitle(command *Command, flag *Flag, title string)
	FpFlagsGroupTitle(group string)
	FpFlagsLine(command *Command, flag *Flag, defValStr string)

	Flush()

	Results() []byte

	// clear any internal states and reset itself
	Reset()
}

Painter to support the genManual, genMarkdown, printHelpScreen.

type RootCmdOpt added in v0.2.15

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

RootCmdOpt for fluent api

func Root added in v0.2.15

func Root(appName, version string) (opt *RootCmdOpt)

Root for fluent api, to create a new *RootCmdOpt object.

func RootFrom added in v1.0.3

func RootFrom(root *RootCommand) (opt *RootCmdOpt)

RootFrom for fluent api, to create the new *RootCmdOpt object from an existed RootCommand

func (*RootCmdOpt) Action added in v0.2.15

func (s *RootCmdOpt) Action(action func(cmd *Command, args []string) (err error)) (opt OptCmd)

func (*RootCmdOpt) AddCommand added in v1.6.7

func (s *RootCmdOpt) AddCommand(cmd *Command)

func (*RootCmdOpt) AddFlag added in v1.6.7

func (s *RootCmdOpt) AddFlag(flag *Flag)

func (*RootCmdOpt) AddOptCmd added in v1.6.7

func (s *RootCmdOpt) AddOptCmd(opt OptCmd)

func (*RootCmdOpt) AddOptFlag added in v1.6.7

func (s *RootCmdOpt) AddOptFlag(flag OptFlag)

func (*RootCmdOpt) Aliases added in v0.2.15

func (s *RootCmdOpt) Aliases(aliases ...string) (opt OptCmd)

func (*RootCmdOpt) AttachTo added in v1.6.7

func (s *RootCmdOpt) AttachTo(opt OptCmd)

func (*RootCmdOpt) AttachToCommand added in v1.6.7

func (s *RootCmdOpt) AttachToCommand(cmd *Command)

func (*RootCmdOpt) AttachToRoot added in v1.6.7

func (s *RootCmdOpt) AttachToRoot(root *RootCommand)

func (*RootCmdOpt) Bool added in v0.2.15

func (s *RootCmdOpt) Bool() (opt OptFlag)

func (*RootCmdOpt) Complex128 added in v1.6.21

func (s *RootCmdOpt) Complex128() (opt OptFlag)

func (*RootCmdOpt) Complex64 added in v1.6.21

func (s *RootCmdOpt) Complex64() (opt OptFlag)

func (*RootCmdOpt) Copyright added in v0.2.15

func (s *RootCmdOpt) Copyright(copyright, author string) *RootCmdOpt

Copyright for fluent api

func (*RootCmdOpt) Deprecated added in v0.2.15

func (s *RootCmdOpt) Deprecated(deprecation string) (opt OptCmd)

func (*RootCmdOpt) Description added in v0.2.15

func (s *RootCmdOpt) Description(oneLine string, long ...string) (opt OptCmd)

func (*RootCmdOpt) Duration added in v0.2.17

func (s *RootCmdOpt) Duration() (opt OptFlag)

func (*RootCmdOpt) Examples added in v0.2.15

func (s *RootCmdOpt) Examples(examples string) (opt OptCmd)

func (*RootCmdOpt) Float32 added in v1.0.1

func (s *RootCmdOpt) Float32() (opt OptFlag)

func (*RootCmdOpt) Float64 added in v1.0.1

func (s *RootCmdOpt) Float64() (opt OptFlag)

func (*RootCmdOpt) Group added in v0.2.15

func (s *RootCmdOpt) Group(group string) (opt OptCmd)

func (*RootCmdOpt) Header added in v0.2.15

func (s *RootCmdOpt) Header(header string) *RootCmdOpt

Header for fluent api

func (*RootCmdOpt) Hidden added in v0.2.15

func (s *RootCmdOpt) Hidden(hidden bool) (opt OptCmd)

func (*RootCmdOpt) Int added in v0.2.15

func (s *RootCmdOpt) Int() (opt OptFlag)

func (*RootCmdOpt) Int64 added in v0.2.15

func (s *RootCmdOpt) Int64() (opt OptFlag)

func (*RootCmdOpt) IntSlice added in v0.2.15

func (s *RootCmdOpt) IntSlice() (opt OptFlag)

func (*RootCmdOpt) Long added in v0.2.15

func (s *RootCmdOpt) Long(long string) (opt OptCmd)

func (*RootCmdOpt) NewFlag added in v0.2.15

func (s *RootCmdOpt) NewFlag(typ OptFlagType) (opt OptFlag)

func (*RootCmdOpt) NewFlagV added in v1.6.8

func (s *RootCmdOpt) NewFlagV(defaultValue interface{}, titles ...string) (opt OptFlag)

func (*RootCmdOpt) NewSubCommand added in v0.2.15

func (s *RootCmdOpt) NewSubCommand(titles ...string) (opt OptCmd)

func (*RootCmdOpt) OwnerCommand added in v0.2.15

func (s *RootCmdOpt) OwnerCommand() (opt OptCmd)

func (*RootCmdOpt) PostAction added in v0.2.15

func (s *RootCmdOpt) PostAction(post func(cmd *Command, args []string)) (opt OptCmd)

func (*RootCmdOpt) PreAction added in v0.2.15

func (s *RootCmdOpt) PreAction(pre func(cmd *Command, args []string) (err error)) (opt OptCmd)

func (*RootCmdOpt) RootCommand added in v0.2.15

func (s *RootCmdOpt) RootCommand() (root *RootCommand)

func (*RootCmdOpt) SetOwner added in v0.2.15

func (s *RootCmdOpt) SetOwner(opt OptCmd)

func (*RootCmdOpt) Short added in v0.2.15

func (s *RootCmdOpt) Short(short string) (opt OptCmd)

func (*RootCmdOpt) String added in v0.2.15

func (s *RootCmdOpt) String() (opt OptFlag)

func (*RootCmdOpt) StringSlice added in v0.2.15

func (s *RootCmdOpt) StringSlice() (opt OptFlag)

func (*RootCmdOpt) TailPlaceholder added in v0.2.15

func (s *RootCmdOpt) TailPlaceholder(placeholder string) (opt OptCmd)

func (*RootCmdOpt) Titles added in v0.2.15

func (s *RootCmdOpt) Titles(short, long string, aliases ...string) (opt OptCmd)

func (*RootCmdOpt) ToCommand added in v1.6.7

func (s *RootCmdOpt) ToCommand() *Command

func (*RootCmdOpt) Uint added in v0.2.15

func (s *RootCmdOpt) Uint() (opt OptFlag)

func (*RootCmdOpt) Uint64 added in v0.2.15

func (s *RootCmdOpt) Uint64() (opt OptFlag)

type RootCommand

type RootCommand struct {
	Command

	AppName    string
	Version    string
	VersionInt uint32

	Copyright string
	Author    string
	Header    string // using `Header` for header and ignore built with `Copyright` and `Author`, and no usage lines too.

	PostActions []func(cmd *Command, args []string)
	// contains filtered or unexported fields
}

RootCommand holds some application information

func (*RootCommand) AppendPostActions added in v1.6.22

func (c *RootCommand) AppendPostActions(fns ...func(cmd *Command, args []string))

AppendPostActions adds the global post-action to cmdr system

type StringDistance added in v1.1.3

type StringDistance interface {
	Calc(s1, s2 string, opts ...DistanceOption) (distance int)
}

StringDistance is an interface for string metric. A string metric is a metric that measures distance between two strings. In most case, it means that the edit distance about those two strings. This is saying, it is how many times are needed while you were modifying string to another one, note that inserting, deleting, substing one character means once.

func JaroWinklerDistance added in v1.1.3

func JaroWinklerDistance(opts ...DistanceOption) StringDistance

JaroWinklerDistance returns an calculator for two strings distance metric, with Jaro-Winkler algorithm.

type UnhandledErrorHandler added in v1.6.13

type UnhandledErrorHandler func(err interface{})

UnhandledErrorHandler for WithUnhandledErrorHandler

type UnknownOptionHandler added in v1.5.5

type UnknownOptionHandler func(isFlag bool, title string, cmd *Command, args []string) (fallbackToDefaultDetector bool)

UnknownOptionHandler for WithSimilarThreshold/SetUnknownOptionHandler

Directories

Path Synopsis
Package conf are used to store the app-level constants (app name/vaersion) for cmdr and your app
Package conf are used to store the app-level constants (app name/vaersion) for cmdr and your app
examples
Package flag is used to wrap some APIs from go stdlib flag
Package flag is used to wrap some APIs from go stdlib flag
plugin

Jump to

Keyboard shortcuts

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