Files
kopia/cli/inproc.go
Jarek Kowalski 8a4ac4dec3 Upgraded linter to 1.43.0 (#1505)
* fixed new gocritic violations
* fixed new 'contextcheck' violations
* fixed 'gosec' warnings
* suppressed ireturn and varnamelen linters
* fixed tenv violations, enabled building robustness tests on arm64
* fixed remaining linux failures
* makefile: fixed 'lint-all' target when running on arm64
* linter: increase deadline
* disable nilnil linter - to be enabled in separate PR
2021-11-11 17:03:11 -08:00

54 lines
1.2 KiB
Go

package cli
import (
"context"
"io"
"github.com/alecthomas/kingpin"
"github.com/pkg/errors"
"github.com/kopia/kopia/repo/logging"
)
// RunSubcommand executes the subcommand asynchronously in current process
// with flags in an isolated CLI environment and returns standard output and standard error.
func (c *App) RunSubcommand(ctx context.Context, kpapp *kingpin.Application, argsAndFlags []string) (stdout, stderr io.Reader, wait func() error, kill func()) {
stdoutReader, stdoutWriter := io.Pipe()
stderrReader, stderrWriter := io.Pipe()
c.stdoutWriter = stdoutWriter
c.stderrWriter = stderrWriter
c.rootctx = logging.WithLogger(ctx, logging.Writer(stderrWriter))
c.Attach(kpapp) // nolint:contextcheck
var exitCode int
resultErr := make(chan error, 1)
c.osExit = func(ec int) {
exitCode = ec
}
go func() {
defer close(resultErr)
defer stderrWriter.Close() //nolint:errcheck
defer stdoutWriter.Close() //nolint:errcheck
_, err := kpapp.Parse(argsAndFlags)
if err != nil {
resultErr <- err
return
}
if exitCode != 0 {
resultErr <- errors.Errorf("exit code %v", exitCode)
return
}
}()
return stdoutReader, stderrReader, func() error {
return <-resultErr
}, func() {}
}