Skip to content

Commit

Permalink
Avoid race on in generation of completions and docs
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
krobelus committed Feb 10, 2021
1 parent 6215930 commit a1db6ce
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 30 deletions.
22 changes: 7 additions & 15 deletions doc/gen_docs.go
Expand Up @@ -4,7 +4,6 @@ import (
"fmt"
"os"
"path/filepath"
"sync"
"time"

"github.com/spf13/cobra"
Expand All @@ -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 {
Expand Down
22 changes: 7 additions & 15 deletions misc/gen_completion.go
Expand Up @@ -4,7 +4,6 @@ import (
"fmt"
"os"
"path/filepath"
"sync"

"github.com/spf13/cobra"

Expand All @@ -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 {
Expand Down

0 comments on commit a1db6ce

Please sign in to comment.