cli.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. // Package cli wires cobra subcommands onto the config/provider/runner/templates
  2. // layers. Each subcommand file (add.go, list.go, use.go, ...) exposes a
  3. // factory function that receives a shared *appState carrying the effective
  4. // config path, loaded config, output streams, and a verbose flag.
  5. //
  6. // Tests drive this package by calling Execute with an argv slice and inspecting
  7. // the (exitCode, err) result plus the stdout/stderr io.Writers they pass via
  8. // ExecuteWithStreams.
  9. package cli
  10. import (
  11. "io"
  12. "os"
  13. )
  14. // Execute runs the CLI against os.Stdin/Stdout/Stderr using argv.
  15. func Execute(argv []string) (int, error) {
  16. return ExecuteWithStreams(argv, os.Stdin, os.Stdout, os.Stderr)
  17. }
  18. // ExecuteWithStreams is the testable form of Execute; callers supply the
  19. // standard streams explicitly. The function returns the exit code cc-switch
  20. // should terminate with. A non-nil error is already printed to stderr by cobra
  21. // (or by the subcommand) before return, so main() need not print it again.
  22. func ExecuteWithStreams(argv []string, stdin io.Reader, stdout, stderr io.Writer) (int, error) {
  23. app := &appState{
  24. stdin: stdin,
  25. stdout: stdout,
  26. stderr: stderr,
  27. }
  28. root := newRootCmd(app)
  29. root.SetArgs(argv)
  30. root.SetIn(stdin)
  31. root.SetOut(stdout)
  32. root.SetErr(stderr)
  33. err := root.Execute()
  34. return app.exitCode(err), err
  35. }