Command: RedirectTo
Redirect To...
Redirecting root command to a subcmd
THIS TRANSLATION NEEDS UPDATED!
.SetRedirectTo(subcmd) provides a new target for the Root Command.
Redirecting root command to a subcmd, can be used at this scene, makes an input commandline app worked as app a b c, when the .SetRedirectTo("a.b.c") setup.
The well-known case is pnpm, a nodejs package manager, which can forward any unmatched commands like pnpm dev to pnpm run ..., that would be pnpm run dev.
Since v2.1.40
recursive parameter can enable the redirecting action recursively. In recursive mode, subcmds will be forwarded to target command to try to match it.
For instance, there is a redirect-to rule (root) -> server, typing app is equal to input app server command in non-recursive mode; and if it's in recursive mode, typing app run can be interpretted as app server run if possible.
To enable recursive mode, calling SetRedirectTo("server", true) with second parameter true.
Definitions
The key interface is *CmdS.SetRedirectTo(dottedCmdPath). So whatever we need to do is,
The full codes are in examples/redirect-to-subcmd.
In this example, WithAdders(...) will attach two subcmds into app: jump to and wrong.
And With(func(app cli.App){...}) closure block would give you a challenge to operate app object in a streaming call.
It is the right position to calling to SetRedirectTo().
As it ran, end-user's app will have the same effect with typing app wrong in command line.
Multiple Subcmds
To rediect into a multi-level subcmd as target, you can using dottedPath. The dottedPath allows a single string to represent the multi-level subcmds. So SetRedirectTo("jump.to") could point to the target jump/to subcmd.
Run
The result of example app is,
The returning Application Error is the response of the subcmd wrong.
Note that the default action of root command is not work any more. So you must request the root help screen by typing app -h or app --help explicitly.
额外的话题
How is this guide?
Last updated on