Merge pull request #100 from eparis/pre-post-run
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Pre post run fucntions
authored by Eric Paris · committed by Eric Paris · parents 9cf0f37, fad5931 · Browse files · 3 files·+156 added−4 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+156 added−4 removed
- other:+156 added−4 removed
Provenance
- Commit
3ee9552- Tree
3d555aa- Author
Eric Paris <eparis@redhat.com>- Committer
Eric Paris <eparis@redhat.com>- Parent 1
9cf0f37- Parent 2
fad5931
3 files changed+156 added−4 removed
modified:cobra_test.go+42 added
11 unmodified lines12 var _ = fmt.Println13 var _ = os.Stderr14 15 var tp, te, tt, t1 []string16+var rootPersPre, echoPre, echoPersPre, timesPersPre []string17 var flagb1, flagb2, flagb3, flagbr, flagbp bool18 var flags1, flags2a, flags2b, flags3 string19 var flagi1, flagi2, flagi3, flagir int20 var globalFlag1 bool17 unmodified lines38 Aliases: []string{"say"},39 Short: "Echo anything to the screen",40 Long: `an utterly useless command for testing.`,41 Example: "Just run cobra-test echo",42+ PersistentPreRun: func(cmd *Command, args []string) {43+ echoPersPre = args44+ },45+ PreRun: func(cmd *Command, args []string) {46+ echoPre = args47+ },48 Run: func(cmd *Command, args []string) {49 te = args50 },51 }18 unmodified lines70 var cmdTimes = &Command{71 Use: "times [# times] [string to echo]",72 Short: "Echo anything to the screen more times",73 Long: `a slightly useless command for testing.`,74+ PersistentPreRun: func(cmd *Command, args []string) {75+ timesPersPre = args76+ },77 Run: func(cmd *Command, args []string) {78 tt = args79 },80 }1 unmodified line82 var cmdRootNoRun = &Command{83 Use: "cobra-test",84 Short: "The root can run it's own function",85 Long: "The root description for help",86+ PersistentPreRun: func(cmd *Command, args []string) {87+ rootPersPre = args88+ },89 }90 91 var cmdRootSameName = &Command{92 Use: "print",68 unmodified lines161 }162 163 func initialize() *Command {164 tt, tp, te = nil, nil, nil165+ rootPersPre, echoPre, echoPersPre, timesPersPre = nil, nil, nil, nil166+167 var c = cmdRootNoRun168 flagInit()169 commandInit()170 return c171 }172 173 func initializeWithSameName() *Command {174 tt, tp, te = nil, nil, nil175+ rootPersPre, echoPre, echoPersPre, timesPersPre = nil, nil, nil, nil176 var c = cmdRootSameName177 flagInit()178 commandInit()179 return c662 unmodified lines842 c := fullSetupTest("deprecated")843 844 checkResultContains(t, c, cmdDeprecated.Deprecated)845 }846+847+func TestPreRun(t *testing.T) {848+ noRRSetupTest("echo one two")849+ if echoPre == nil || echoPersPre == nil {850+ t.Error("PreRun or PersistentPreRun not called")851+ }852+ if rootPersPre != nil || timesPersPre != nil {853+ t.Error("Wrong *Pre functions called!")854+ }855+856+ noRRSetupTest("echo times one two")857+ if timesPersPre == nil {858+ t.Error("PreRun or PersistentPreRun not called")859+ }860+ if echoPre != nil || echoPersPre != nil || rootPersPre != nil {861+ t.Error("Wrong *Pre functions called!")862+ }863+864+ noRRSetupTest("print one two")865+ if rootPersPre == nil {866+ t.Error("Parent PersistentPreRun not called but should not have been")867+ }868+ if echoPre != nil || echoPersPre != nil || timesPersPre != nil {869+ t.Error("Wrong *Pre functions called!")870+ }871+}modified:command.go+44 added-4 removed
54 unmodified lines55 // Set of flags childrens of this command will inherit56 pflags *flag.FlagSet57 // Flags that are declared specifically by this command (not inherited).58 lflags *flag.FlagSet59- // Run runs the command.60- // The args are the arguments after the command name.59+ // The *Run functions are executed in the following order:60+ // * PersistentPreRun()61+ // * PreRun()62+ // * Run()63+ // * PostRun()64+ // * PersistentPostRun()65+ // All functions get the same args, the arguments after the command name66+ // PersistentPreRun: children of this command will inherit and execute67+ PersistentPreRun func(cmd *Command, args []string)68+ // PreRun: children of this command will not inherit.69+ PreRun func(cmd *Command, args []string)70+ // Run: Typically the actual work function. Most commands will only implement this71 Run func(cmd *Command, args []string)72+ // PostRun: run after the Run command.73+ PostRun func(cmd *Command, args []string)74+ // PersistentPostRun: children of this command will inherit and execute after PostRun75+ PersistentPostRun func(cmd *Command, args []string)76 // Commands is the list of commands supported by this program.77 commands []*Command78 // Parent Command for this command79 parent *Command381 unmodified lines461 }462 463 c.preRun()464 argWoFlags := c.Flags().Args()465+466+ if c.PersistentPreRun != nil {467+ c.PersistentPreRun(c, argWoFlags)468+ }469+ if c.PreRun != nil {470+ c.PreRun(c, argWoFlags)471+ }472+473 c.Run(c, argWoFlags)474+475+ if c.PostRun != nil {476+ c.PostRun(c, argWoFlags)477+ }478+ if c.PersistentPostRun != nil {479+ c.PersistentPostRun(c, argWoFlags)480+ }481+482 return nil483 }484 485 func (c *Command) preRun() {72 unmodified lines558 Use: "help [command]",559 Short: "Help about any command",560 Long: `Help provides help for any command in the application.561 Simply type ` + c.Name() + ` help [path to command] for full details.`,532- Run: c.HelpFunc(),562+ Run: c.HelpFunc(),563+ PersistentPreRun: func(cmd *Command, args []string) {},564+ PersistentPostRun: func(cmd *Command, args []string) {},565 }566 }567 c.AddCommand(c.helpCommand)568 }31 unmodified lines600 if nameLen > c.commandsMaxNameLen {601 c.commandsMaxNameLen = nameLen602 }603 c.commands = append(c.commands, x)604+605+ // Pass on peristent pre/post functions to children606+ if x.PersistentPreRun == nil {607+ x.PersistentPreRun = c.PersistentPreRun608+ }609+ if x.PersistentPostRun == nil {610+ x.PersistentPostRun = c.PersistentPostRun611+ }612 }613 }614 615 // AddCommand removes one or more commands from a parent command.365 unmodified lines981 c.Flags().VisitAll(addtolocal)982 c.PersistentFlags().VisitAll(addtolocal)983 }984 rmerge = func(x *Command) {945- if ! x.HasParent() {985+ if !x.HasParent() {986 flag.CommandLine.VisitAll(func(f *flag.Flag) {987 if x.PersistentFlags().Lookup(f.Name) == nil {988 x.PersistentFlags().AddFlag(f)989 }16 unmodified linesmodified:README.md+70 added
346 unmodified lines347 command.SetUsageFunc(f func(*Command) error)348 349 command.SetUsageTemplate(s string)350 351+## PreRun or PostRun Hooks352+353+It is possible to run functions before or after the main `Run` function of your command. The `PersistentPreRun` and `PreRun` functions will be executed before `Run`. `PersistendPostRun` and `PostRun` will be executed after `Run`. The `Persistent*Run` functions will be inherrited by children if they do not declare their own. These function are run in the following order:354+355+- `PersistentPreRun`356+- `PreRun`357+- `Run`358+- `PostRun`359+- `PersistenPostRun`360+361+And example of two commands which use all of these features is below. When the subcommand in executed it will run the root command's `PersistentPreRun` but not the root command's `PersistentPostRun`362+363+```go364+package main365+366+import (367+ "fmt"368+369+ "github.com/spf13/cobra"370+)371+372+func main() {373+374+ var rootCmd = &cobra.Command{375+ Use: "root [sub]",376+ Short: "My root command",377+ PersistentPreRun: func(cmd *cobra.Command, args []string) {378+ fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args)379+ },380+ PreRun: func(cmd *cobra.Command, args []string) {381+ fmt.Printf("Inside rootCmd PreRun with args: %v\n", args)382+ },383+ Run: func(cmd *cobra.Command, args []string) {384+ fmt.Printf("Inside rootCmd Run with args: %v\n", args)385+ },386+ PostRun: func(cmd *cobra.Command, args []string) {387+ fmt.Printf("Inside rootCmd PostRun with args: %v\n", args)388+ },389+ PersistentPostRun: func(cmd *cobra.Command, args []string) {390+ fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args)391+ },392+ }393+394+ var subCmd = &cobra.Command{395+ Use: "sub [no options!]",396+ Short: "My sub command",397+ PreRun: func(cmd *cobra.Command, args []string) {398+ fmt.Printf("Inside subCmd PreRun with args: %v\n", args)399+ },400+ Run: func(cmd *cobra.Command, args []string) {401+ fmt.Printf("Inside subCmd Run with args: %v\n", args)402+ },403+ PostRun: func(cmd *cobra.Command, args []string) {404+ fmt.Printf("Inside subCmd PostRun with args: %v\n", args)405+ },406+ PersistentPostRun: func(cmd *cobra.Command, args []string) {407+ fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args)408+ },409+ }410+411+ rootCmd.AddCommand(subCmd)412+413+ rootCmd.SetArgs([]string{""})414+ _ = rootCmd.Execute()415+ fmt.Print("\n")416+ rootCmd.SetArgs([]string{"sub", "arg1", "arg2"})417+ _ = rootCmd.Execute()418+}419+```420+421 ## Generating markdown formatted documentation for your command422 423 Cobra can generate a markdown formatted document based on the subcommands, flags, etc. A simple example of how to do this for your command can be found in [Markdown Docs](md_docs.md)424 61 unmodified lines