Documentation ¶
Index ¶
- Constants
- func App() cli.Runner
- func AppDescription() string
- func AppDescriptionLong() string
- func AppName() string
- func AppVersion() string
- func CacheDir(base ...string) string
- func CmdLines() []string
- func ConfigDir(base ...string) string
- func DataDir(base ...string) string
- func Exec(rootCmd *cli.RootCommand, opts ...cli.Opt) (err error)
- func HomeDir() string
- func LoadedSources() []cli.LoadedSources
- func New(opts ...cli.Opt) cli.App
- func Parsed() bool
- func ParsedCommands() []cli.Cmd
- func ParsedLastCmd() cli.Cmd
- func ParsedPositionalArgs() []string
- func RemoveOrderedPrefix(s string) string
- func Set() store.Store
- func Store() store.Store
- func TempDir(base ...string) string
- func TempFileName(fileNamePattern, defaultFileName string, base ...string) (filename string)
- func UsrLibDir(base ...string) string
- func VarLogDir(base ...string) string
- func VarRunDir(base ...string) string
- func WithAutoEnvBindings(b bool, prefix ...string) cli.Opt
- func WithConfig(conf *cli.Config) cli.Opt
- func WithDontExecuteAction(b bool) cli.Opt
- func WithDontGroupInHelpScreen(b bool) cli.Opt
- func WithExternalLoaders(loaders ...cli.Loader) cli.Opt
- func WithForceDefaultAction(b bool) cli.Opt
- func WithPeripherals(peripherals ...basics.Peripheral) cli.Opt
- func WithSortInHelpScreen(b bool) cli.Opt
- func WithStore(conf store.Store) cli.Opt
- func WithTasksAfterRun(tasks ...cli.Task) cli.Opt
- func WithTasksBeforeParse(tasks ...cli.Task) cli.Opt
- func WithTasksBeforeRun(tasks ...cli.Task) cli.Opt
- func WithTasksParsed(tasks ...cli.Task) cli.Opt
- func WithTasksPostCleanup(tasks ...cli.Task) cli.Opt
- func WithTasksSetupPeripherals(tasks ...cli.Task) cli.Opt
- func WithUnmatchedAsError(b bool) cli.Opt
Constants ¶
const Version = "v2.0.16" // Version fir hedzr/cmdr/v2
Variables ¶
This section is empty.
Functions ¶
func App ¶
App returns a light version of builder.Runner (a.k.a. *worker.Worker).
Generally it's a unique instance in one system.
It's available once New() / Exec() called, else nil.
App returns a cli.Runner instance, which is different with builder.App.
func AppDescription ¶ added in v2.0.7
func AppDescription() string
func AppDescriptionLong ¶ added in v2.0.7
func AppDescriptionLong() string
func AppVersion ¶ added in v2.0.7
func AppVersion() string
func CacheDir ¶ added in v2.0.7
CacheDir returns standard cachedir associated with this app. In general, it would be /var/cache/<appName>, $HOME/.cache/<appName>, and so on.
CacheDir returns the default root directory to use for user-specific cached data. Users should create their own application-specific subdirectory within this one and use that.
On Unix systems, it returns $XDG_CACHE_HOME as specified by https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html if non-empty, else $HOME/.cache. On Darwin, it would be $HOME/.cache/<appName>. ~~it returns $HOME/Library/Caches.~~ On Windows, it returns %LocalAppData%/<appName>. On Plan 9, it returns $home/lib/cache/<appName>.
If the location cannot be determined (for example, $HOME is not defined), then it will return an error.
func CmdLines ¶ added in v2.0.7
func CmdLines() []string
CmdLines returns the whole command-line as space-separated slice.
func ConfigDir ¶ added in v2.0.7
ConfigDir returns standard configdir associated with this app. In general, it would be /etc/<appName>, $HOME/.config/<appName>, and so on.
ConfigDir returns the default root directory to use for user-specific configuration data. Users should create their own application-specific subdirectory within this one and use that.
On Unix systems, it returns $XDG_CONFIG_HOME as specified by https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html if non-empty, else $HOME/.config/<appName>. On Darwin, it would be $HOME/.config/<appName>. ~~it returns $HOME/Library/Application Support.~~ On Windows, it returns %AppData%/<appName>. On Plan 9, it returns $home/lib/<appName>.
If the location cannot be determined (for example, $HOME is not defined), then it will return an error.
func DataDir ¶ added in v2.0.7
DataDir returns standard datadir associated with this app. In general, it would be /usr/local/share/<appName>, $HOME/.local/share/<appName>, and so on.
DataDir is used to store app normal runtime data.
For darwin and linux it's generally at "$HOME/.local/share/<app>", or "/usr/local/share/<app>" and "/usr/share/<app>" in some builds.
For windows it is "%APPDATA%/<app>/Data".
In your application, it shall look up config files from ConfigDir, save the runtime data (or persistent data) into DataDir, use CacheDir to store the cache data which can be file and folder or file content indexes, the response replies from remote api, and so on. TempDir is used to store any temporary content which can be erased at any time.
UsrLibDir is the place which an application should be installed at, in linux.
VarRunDir is the place which a .pid, running socket file handle, and others files that can be shared in all processes of this application, sometimes for any apps.
func Exec ¶
func Exec(rootCmd *cli.RootCommand, opts ...cli.Opt) (err error)
Exec starts a new cmdr app (parsing cmdline args based on the given rootCmd) from scratch.
It's a reserved API for back-compatible with cmdr v1.
It'll be removed completely at the recently future version.
Deprecated since 2.1 by app.Run()
func HomeDir ¶ added in v2.0.7
func HomeDir() string
HomeDir returns the current user's home directory. In general, it would be /Users/<username>, /home/<username>, etc.
func LoadedSources ¶ added in v2.0.9
func LoadedSources() []cli.LoadedSources
func New ¶
New starts a new cmdr app.
With the returned builder.App, you may build root and sub-commands fluently.
app := cmdr.New(). Info("demo-app", "0.3.1"). Author("hedzr") app.Cmd("jump"). Description("jump command"). Examples(`jump example`). Deprecated(`jump is a demo command`). With(func(b cli.CommandBuilder) { b.Hidden(false) b.Cmd("to"). Description("to command"). Examples(``). Deprecated(`v0.1.1`). Hidden(false). OnAction(func(cmd *cli.CmdS, args []string) (err error) { main1() return // handling command action here }). With(func(b cli.CommandBuilder) { b.Flg("full", "f"). Default(false). Description("full command"). Build() }) }) app.Flg("dry-run", "n"). Default(false). Build() // no matter even if you're adding the duplicated one. // // simple run the parser of app and trigger the matched command's action // _ = app.Run( // cmdr.WithForceDefaultAction(false), // true for debug in developing time // ) if err := app.Run( cmdr.WithForceDefaultAction(false), // true for debug in developing time ); err != nil { logz.ErrorContext(ctx, "Application Error:", "err", err) }
After the root command and all its children are built, use app.[config.App.Run] to parse end-user's command-line arguments, and invoke the bound action on the hit subcommand.
It is not necessary to attach an action onto a parent command, because its subcommands are the main characters - but you still can do that.
func ParsedCommands ¶ added in v2.0.7
func ParsedLastCmd ¶ added in v2.0.7
func ParsedPositionalArgs ¶ added in v2.0.7
func ParsedPositionalArgs() []string
func RemoveOrderedPrefix ¶ added in v2.0.7
RemoveOrderedPrefix removes '[a-z0-9]+\.' at front of string.
func Store ¶ added in v2.0.7
Store returns the child Store at location 'app.cmd'.
By default, cmdr maintains all command-line subcommands and flags as a child tree in the associated Set ("store") internally.
You can check out the flags state by querying in this child store.
For example, we have a command 'server'->'start' and its flag 'foreground', therefore we can query the flag what if it was given by user's 'app server start --foreground':
fore := cmdr.Store().MustBool("server.start.foreground", false) if fore { runRealMain() } else { service.Start("start", runRealMain) // start the real main as a service } // second form: cs := cmdr.Store().WithPrefix("server.start") fore := cs.MustBool("foreground") port := cs.MustInt("port", 7893)
Q: How to inspect the internal Store()?
A: Running `app [any subcommands] [any options] ~~debug` will dump the internal Store() tree.
Q: Can I list all subcommands?
A: Running `app ~~tree`, `app -v ~~tree` or `app ~~tree -vvv` can get a list of subcommands tree, and with those builtin hidden commands, and with those vendor hidden commands. In this case, `-vvv` dumps the hidden commands and vendor-hidden commands.
func TempFileName ¶ added in v2.0.7
func UsrLibDir ¶ added in v2.0.7
UsrLibDir is the runtime temp dir. "/usr/local/lib/<app>/" or "/usr/lib/<app>" in root mode.
func WithAutoEnvBindings ¶ added in v2.0.9
WithAutoEnvBindings enables the feature which can auto-bind env-vars to flags default value.
For example, APP_JUMP_TO_FULL=1 -> Cmd{"jump.to"}.Flag{"full"}.default-value = true. In this case, `APP` is default prefix so the env-var is different than other normal OS env-vars (like HOME, etc.).
You may specify another prefix optionally. For instance, prefix "CT" will cause CT_JUMP_TO_FULL=1 binding to Cmd{"jump.to"}.Flag{"full"}.default-value = true.
Also you can specify the prefix with multiple section just like "CT_ACCOUNT_SERVICE", it will be treated as a normal plain string and concatted with the rest parts, so "CT_ACCOUNT_SERVICE_JUMP_TO_FULL=1" will be bound in.
func WithConfig ¶ added in v2.0.9
WithConfig allows you passing a *cli.Config object directly.
func WithDontExecuteAction ¶ added in v2.0.7
WithDontExecuteAction prevents internal exec stage which will invoke the matched command's cli.Cmd.OnAction handler.
If cli.Config.DontExecuteAction is true, cmdr works like classical golang stdlib 'flag', which will stop after parsed without any further actions.
cmdr itself is a parsing-and-executing processor. We will launch a matched command's handlers by default.
func WithDontGroupInHelpScreen ¶ added in v2.0.7
func WithExternalLoaders ¶
WithExternalLoaders sets the loaders of external sources, which will be loaded at cmdr's preparing time (xref-building time).
The orders could be referred as:
- constructing cmdr commands system (by your prepareApp) - entering cmdr.Run - cmdr preparing stage
- build commands and flags xref
- load and apply envvars if matched
- load external sources
- post preparing time
- cmdr parsing stage - cmdr invoking stage - cmdr cleanup stage
Using our loaders repo is a good idea: https://github.com/hedzr/cmdr-loaders
Typical app:
app = cmdr.New(opts...). Info("tiny-app", "0.3.1"). Author("The Example Authors") // .Description(``).Header(``).Footer(``) cmdr.WithStore(store.New()), // use an option store explicitly, or a dummy store by default cmdr.WithExternalLoaders( local.NewConfigFileLoader(), // import "github.com/hedzr/cmdr-loaders/local" to get in advanced external loading features local.NewEnvVarLoader(), ), ) if err := app.Run(ctx); err != nil { logz.ErrorContext(ctx, "Application Error:", "err", err) // stacktrace if in debug mode/build os.Exit(app.SuggestRetCode()) }
func WithForceDefaultAction ¶
func WithPeripherals ¶ added in v2.0.7
func WithPeripherals(peripherals ...basics.Peripheral) cli.Opt
WithPeripherals is a better way to register your server peripherals than WithTasksSetupPeripherals. But the 'better' is less.
import "github.com/hedzr/is/basics" type Obj struct{} func (o *Obj) Init(context.Context) *Obj { return o } // initialize itself func (o *Obj) Close(){...} // destory itself obj := new(Obj) // initialize obj at first ctx := context.Background() // app := cmdr.New(cmdr.WithPeripherals(obj.Init(ctx)) // and register it to basics.Closers for auto-shutting-down ...
func WithSortInHelpScreen ¶ added in v2.0.7
func WithStore ¶
WithStore gives a user-defined Store as initial, or by default cmdr makes a dummy Store internally.
So you must have a new Store to be transferred into cmdr if you want integrating cmdr and fully-functional Store. Like this,
app := prepareApp() if err := app.Run( cmdr.WithStore(store.New()), // create a standard Store instead of internal dummyStore // cmdr.WithExternalLoaders( // local.NewConfigFileLoader(), // import "github.com/hedzr/cmdr-loaders/local" to get in advanced external loading features // local.NewEnvVarLoader(), // ), cmdr.WithForceDefaultAction(false), // true for debug in developing time ); err != nil { logz.ErrorContext(ctx, "Application Error:", "err", err) } func prepareApp() cli.App { app = cmdr.New(). // the minimal app is `cmdr.New()` Info("tiny-app", "0.3.1"). Author("example.com Authors") }
func WithTasksAfterRun ¶ added in v2.0.7
WithTasksAfterRun installs callbacks after run/invoke stage.
The internal stages are: initial -> preload + xref -> parse -> run/invoke -> post-actions.
func WithTasksBeforeParse ¶
WithTasksBeforeParse installs callbacks before parsing stage.
The internal stages are: initial -> preload + xref -> parse -> run/invoke -> post-actions.
func WithTasksBeforeRun ¶
WithTasksBeforeRun installs callbacks before run/invoke stage.
The internal stages are: initial -> preload + xref -> parse -> run/invoke -> post-actions.
The internal stages and user-defined tasks are:
- initial
- preload & xref
- <tasksBeforeParse>
- parse
- <tasksParsed>
- <tasksBeforeRun> ( = tasksAfterParse )
- exec (run/invoke)
- <tasksAfterRun>
- <tasksPostCleanup>
- basics.closers...Close()
func WithTasksParsed ¶ added in v2.0.13
WithTasksParsed installs callbacks after parsing stage.
The internal stages are: initial -> preload + xref -> parse -> run/invoke -> post-actions.
Another way is disabling cmdr default executing/run/invoke stage by WithDontExecuteAction(true).
func WithTasksPostCleanup ¶ added in v2.0.13
WithTasksPostCleanup install callbacks at cmdr ending.
See the stagings order introduce at WithTasksBeforeRun.
See also WithTasksSetupPeripherals, WithPeripherals.
func WithTasksSetupPeripherals ¶ added in v2.0.7
WithTasksSetupPeripherals gives a special chance to setup your server's peripherals (such as database, redis, message queues, or others).
For these server peripherals, a better practices would be initializing them with WithTasksSetupPeripherals and destroying them at WithTasksAfterRun.
Another recommendation is implementing your server peripherals as a basics.Closeable component, and register it with basics.RegisterPeripherals(), and that's it. These objects will be destroyed at cmdr ends (later than WithTasksAfterRun but it's okay).
import "github.com/hedzr/is/basics" type Obj struct{} func (o *Obj) Init(context.Context) *Obj { return o } // initialize itself func (o *Obj) Close(){...} // destroy itself app := cmdr.New(cmdr.WithTasksSetupPeripherals(func(ctx context.Context, cmd cli.Cmd, runner cli.Runner, extras ...any) (err error) { obj := new(Obj) basics.RegisterPeripheral(obj.Init(ctx)) // initialize obj at first, and register it to basics.Closers for auto-shutting-down return })) ...
func WithUnmatchedAsError ¶
Types ¶
This section is empty.
Directories ¶
Path | Synopsis |
---|---|
atoa
Package atoa - converters for any to any
|
Package atoa - converters for any to any |
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. |
internal
|
|
pkg
|
|
dir
Package dir provides a series of directory/file operations
|
Package dir provides a series of directory/file operations |