| 39 | } |
| 40 | |
| 41 | func ExampleCommands(e *Example) hive.ScriptCmdsOut { |
| 42 | return hive.NewScriptCmds(map[string]script.Cmd{ |
| 43 | // example/hello command says a greeting to the stdout buffer. |
| 44 | "example/hello": script.Command( |
| 45 | script.CmdUsage{ |
| 46 | Summary: "Say hello", |
| 47 | Args: "name", |
| 48 | Flags: func(fs *pflag.FlagSet) { |
| 49 | fs.String("greeting", "Hello,", "Greeting to use") |
| 50 | }, |
| 51 | }, |
| 52 | |
| 53 | // Define the function for executing the command. The function takes |
| 54 | // [script.State] that provides logging, flags and utilities, and the |
| 55 | // command arguments that are left over from parsing [CmdUsage.Flags]. |
| 56 | // |
| 57 | // The function can either directly execute the command and return a |
| 58 | // nil [script.WaitFunc] or if the command should run in the background |
| 59 | // ([script.CmdUsage.Async] is true) or the if the command needs to write |
| 60 | // to stdout/stderr buffers, then a [script.WaitFunc] should be returned. |
| 61 | // |
| 62 | // It is preferable to return output in stdout and not Logf'd so it |
| 63 | // can be matched against. In "cilium-dbg shell" the output looks the |
| 64 | // same regardless of whether Logf() or stdout is used (the "[stdout]" |
| 65 | // banner is stripped). |
| 66 | func(s *script.State, args ...string) (script.WaitFunc, error) { |
| 67 | if len(args) != 1 { |
| 68 | return nil, fmt.Errorf("%w: expected name", script.ErrUsage) |
| 69 | } |
| 70 | name := args[0] |
| 71 | return func(s *script.State) (stdout, stderr string, err error) { |
| 72 | greeting, err := s.Flags.GetString("greeting") |
| 73 | if err != nil { |
| 74 | return "", "", err |
| 75 | } |
| 76 | // In addition to [stdout] and [stderr] the command can also write to |
| 77 | // a separate log buffer. The logs however are not matchable in tests. |
| 78 | s.Logf("calling SayHello(%s, %s)\n", name, greeting) |
| 79 | stdout = e.SayHello(name, greeting) |
| 80 | return |
| 81 | }, nil |
| 82 | }, |
| 83 | ), |
| 84 | |
| 85 | // example/counts command writes the number of times SayHello() has been called to |
| 86 | // stdout. |
| 87 | "example/counts": script.Command( |
| 88 | script.CmdUsage{ |
| 89 | Summary: "Show the call counts of the example module", |
| 90 | }, |
| 91 | func(s *script.State, args ...string) (script.WaitFunc, error) { |
| 92 | return func(s *script.State) (stdout, stderr string, err error) { |
| 93 | stdout = fmt.Sprintf("%d SayHello()\n", e.count.Load()) |
| 94 | return |
| 95 | }, nil |
| 96 | }, |
| 97 | ), |
| 98 | }) |