Skip to content

Commit

Permalink
fix race-condition issue 406 (#407)
Browse files Browse the repository at this point in the history
  • Loading branch information
effoeffi authored Oct 31, 2023
1 parent 9d5123f commit f148c7e
Showing 1 changed file with 38 additions and 34 deletions.
72 changes: 38 additions & 34 deletions internal/run.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package internal

import (
"context"
"io"
"os"
"strconv"
Expand All @@ -14,9 +15,16 @@ import (
)

func Run(args []string, stdout io.Writer, stderr io.Writer) int {

ctx, cancelCtx := context.WithDeadline(context.Background(), time.Now().Add(model.DefaultTimeout))
defer cancelCtx()

chanPreRun := make(chan int)
rootCmd := &cobra.Command{
Use: "oasdiff",
Short: "OpenAPI specification diff",
Use: "oasdiff",
Short: "OpenAPI specification diff",
PersistentPreRun: func(cmd *cobra.Command, args []string) { preRun(chanPreRun, cmd) },
PersistentPostRun: func(*cobra.Command, []string) { postRun(ctx, chanPreRun) },
}

rootCmd.SetArgs(args[1:])
Expand All @@ -33,7 +41,34 @@ func Run(args []string, stdout io.Writer, stderr io.Writer) int {
getChecksCmd(),
)

return strategy()(rootCmd)
return run(rootCmd)
}

func preRun(c chan int, cmd *cobra.Command) {

go func(c chan int) {
defer close(c)
if os.Getenv(model.EnvNoTelemetry) != "1" {
_ = client.NewCollector(util.NewStringSet().Add("err-ignore").
Add("warn-ignore").
Add("match-path").
Add("prefix-base").
Add("prefix-revision").
Add("strip-prefix-base").
Add("strip-prefix-revision").
Add("filter-extension")).SendCommand(cmd)
}
}(c)
}

func postRun(ctx context.Context, c chan int) {

select {
case <-c:
break
case <-ctx.Done():
break
}
}

func setReturnValue(cmd *cobra.Command, code int) {
Expand Down Expand Up @@ -63,37 +98,6 @@ func getReturnValue(cmd *cobra.Command) int {
return code
}

func strategy() func(*cobra.Command) int {

if os.Getenv(model.EnvNoTelemetry) == "1" {
return run
}

return func(cmd *cobra.Command) int {
c := make(chan int)
go func() {
defer close(c)
_ = client.NewCollector(util.NewStringSet().Add("err-ignore").
Add("warn-ignore").
Add("match-path").
Add("prefix-base").
Add("prefix-revision").
Add("strip-prefix-base").
Add("strip-prefix-revision").
Add("filter-extension")).SendCommand(cmd)
}()

ret := run(cmd)

select {
case <-c:
case <-time.After(model.DefaultTimeout):
}

return ret
}
}

func run(cmd *cobra.Command) int {

if err := cmd.Execute(); err != nil {
Expand Down

0 comments on commit f148c7e

Please sign in to comment.