cobra
cobra copied to clipboard
Data race when using multiple unrelated `cobra.Command` instances
This short program causes data races when run with the race detector:
package main
import (
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"golang.org/x/sync/errgroup"
)
var (
_ = pflag.Int("a", 0, "")
)
func main() {
var group errgroup.Group
for i := 0; i < 2; i++ {
group.Go(func() error {
cmd := &cobra.Command{}
return cmd.Execute()
})
}
if err := group.Wait(); err != nil {
panic(err)
}
}
Is that expected? Is it just not supported to try and use multiple unrelated cobra.Command instances?
Our use case is that we're trying to test subsystems that are normally run as their own processes, without actually starting new processes (because of the difficulties in doing that in the Go test paradigm). We had hoped that these separate instances could run at the same time without causing problems, but it looks like they both try to add the members of the global pflag.CommandLine
list as persistent flags.
Is there a way to avoid this?
Our use case is that we're trying to test subsystems that are normally run as their own processes, without actually starting new processes
This seems like the real issue, you will hit other issue depending on global state. Global state is fine for command line tools since they are a separate process.
Of course Cobra would be more useful if multiple commands can run in parallel, but it probably require different interface that will make the normal use case harder to use.