Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Data race when using multiple unrelated cobra.Command instances #2109

Open
thepaul opened this issue Feb 16, 2024 · 1 comment
Open

Data race when using multiple unrelated cobra.Command instances #2109

thepaul opened this issue Feb 16, 2024 · 1 comment

Comments

@thepaul
Copy link

thepaul commented Feb 16, 2024

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?

@nirs
Copy link
Contributor

nirs commented May 3, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants