From 8d23da637c73dd9d860659e5752634823ebc2841 Mon Sep 17 00:00:00 2001 From: Johannes Altmanninger Date: Mon, 25 Jan 2021 17:21:29 +0100 Subject: [PATCH] Avoid race on in generation of completions and docs After adding the calls to `cmd.RegisterFlagCompletionFunc()`, `go generate` usually failed because of "concurrent map writes". We used some goroutines that each create their own `cobra.Command`. Apparently these shared some data, hence the race. As a workaround, make the generation code single-threaded. Maybe the commands should be created only once in `init()`? I'm not sure. --- doc/gen_docs.go | 22 +++++++--------------- misc/gen_completion.go | 22 +++++++--------------- 2 files changed, 14 insertions(+), 30 deletions(-) diff --git a/doc/gen_docs.go b/doc/gen_docs.go index 482abd8e9..a9777b8f4 100644 --- a/doc/gen_docs.go +++ b/doc/gen_docs.go @@ -4,7 +4,6 @@ import ( "fmt" "os" "path/filepath" - "sync" "time" "github.com/spf13/cobra" @@ -21,22 +20,15 @@ func main() { "Markdown": genMarkdown, } - var wg sync.WaitGroup for name, f := range tasks { - wg.Add(1) - go func(name string, f func(*cobra.Command) error) { - defer wg.Done() - root := commands.NewRootCommand() - err := f(root) - if err != nil { - fmt.Printf(" - %s: %v\n", name, err) - return - } - fmt.Printf(" - %s: ok\n", name) - }(name, f) + root := commands.NewRootCommand() + err := f(root) + if err != nil { + fmt.Printf(" - %s: %v\n", name, err) + continue + } + fmt.Printf(" - %s: ok\n", name) } - - wg.Wait() } func genManPage(root *cobra.Command) error { diff --git a/misc/gen_completion.go b/misc/gen_completion.go index c073e67e8..cc78cf768 100644 --- a/misc/gen_completion.go +++ b/misc/gen_completion.go @@ -4,7 +4,6 @@ import ( "fmt" "os" "path/filepath" - "sync" "github.com/spf13/cobra" @@ -21,22 +20,15 @@ func main() { "ZSH": genZsh, } - var wg sync.WaitGroup for name, f := range tasks { - wg.Add(1) - go func(name string, f func(*cobra.Command) error) { - defer wg.Done() - root := commands.NewRootCommand() - err := f(root) - if err != nil { - fmt.Printf(" - %s: %v\n", name, err) - return - } - fmt.Printf(" - %s: ok\n", name) - }(name, f) + root := commands.NewRootCommand() + err := f(root) + if err != nil { + fmt.Printf(" - %s: %v\n", name, err) + continue + } + fmt.Printf(" - %s: ok\n", name) } - - wg.Wait() } func genBash(root *cobra.Command) error {