RunSubcommand executes the subcommand asynchronously in current process with flags in an isolated CLI environment and returns standard output and standard error.
(ctx context.Context, kpapp *kingpin.Application, stdin io.Reader, argsAndFlags []string)
| 14 | // RunSubcommand executes the subcommand asynchronously in current process |
| 15 | // with flags in an isolated CLI environment and returns standard output and standard error. |
| 16 | func (c *App) RunSubcommand(ctx context.Context, kpapp *kingpin.Application, stdin io.Reader, argsAndFlags []string) (stdout, stderr io.Reader, wait func() error, interrupt func(os.Signal)) { |
| 17 | stdoutReader, stdoutWriter := io.Pipe() |
| 18 | stderrReader, stderrWriter := io.Pipe() |
| 19 | |
| 20 | c.stdinReader = stdin |
| 21 | c.stdoutWriter = stdoutWriter |
| 22 | c.stderrWriter = stderrWriter |
| 23 | c.rootctx = logging.WithLogger(ctx, logging.ToWriter(stderrWriter)) |
| 24 | c.simulatedCtrlC = make(chan bool, 1) |
| 25 | c.isInProcessTest = true |
| 26 | |
| 27 | releasable.Created("simulated-ctrl-c", c.simulatedCtrlC) |
| 28 | |
| 29 | c.Attach(kpapp) |
| 30 | |
| 31 | var exitError error |
| 32 | |
| 33 | resultErr := make(chan error, 1) |
| 34 | |
| 35 | c.exitWithError = func(ec error) { |
| 36 | exitError = ec |
| 37 | } |
| 38 | |
| 39 | go func() { |
| 40 | defer func() { |
| 41 | close(c.simulatedCtrlC) |
| 42 | releasable.Released("simulated-ctrl-c", c.simulatedCtrlC) |
| 43 | }() |
| 44 | |
| 45 | defer close(resultErr) |
| 46 | defer stderrWriter.Close() //nolint:errcheck |
| 47 | defer stdoutWriter.Close() //nolint:errcheck |
| 48 | |
| 49 | _, err := kpapp.Parse(argsAndFlags) |
| 50 | if err != nil { |
| 51 | resultErr <- err |
| 52 | return |
| 53 | } |
| 54 | |
| 55 | if exitError != nil { |
| 56 | resultErr <- exitError |
| 57 | return |
| 58 | } |
| 59 | }() |
| 60 | |
| 61 | return stdoutReader, stderrReader, func() error { |
| 62 | return <-resultErr |
| 63 | }, func(_ os.Signal) { |
| 64 | // deliver simulated Ctrl-C to the app. |
| 65 | c.simulatedCtrlC <- true |
| 66 | } |
| 67 | } |