Before this commit, we held onto *cobra.Command objects, but that is not actually supported: after the first Execute(), commands like updateCmd are stuck on the first-ever provided ctx. Instead, turn command initialization into functions. I only noticed this when trying to do two 'gok update' from within the same test, where the fake build timestamp is injected via the context (the timestamp was always the same).
36 lines
634 B
Go
36 lines
634 B
Go
// Package gok allows running the gok CLI from Go code programmatically, to
|
|
// build abstractions on top of gokrazy easily.
|
|
package gok
|
|
|
|
import (
|
|
"context"
|
|
"io"
|
|
|
|
"github.com/gokrazy/tools/internal/gok"
|
|
)
|
|
|
|
type Context struct {
|
|
Stdin io.Reader
|
|
Stdout io.Writer
|
|
Stderr io.Writer
|
|
Args []string
|
|
}
|
|
|
|
func (c Context) Execute(ctx context.Context) error {
|
|
root := gok.RootCmd()
|
|
if r := c.Stdin; r != nil {
|
|
root.SetIn(r)
|
|
}
|
|
if w := c.Stdout; w != nil {
|
|
root.SetOut(w)
|
|
}
|
|
if w := c.Stderr; w != nil {
|
|
root.SetErr(w)
|
|
}
|
|
if args := c.Args; args != nil {
|
|
root.SetArgs(args)
|
|
}
|
|
root.SetContext(ctx)
|
|
return root.Execute()
|
|
}
|