spf13/cobra

Data race when using multiple unrelated `cobra.Command` instances

thepaul opened this issue · 1 comments

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?