From ff057f06c8ed31e62ef5638890c10bc12322876a Mon Sep 17 00:00:00 2001 From: Tiago Queiroz Date: Wed, 7 Sep 2022 16:03:11 +0200 Subject: [PATCH] fix race condition on magefile Fix a race condition when calling `go-licence-detector`. The original code waited for a goroutine to write to `go-licence-detector`'s stdin before starting the command, so the mage target was hanging. This commit fixes it, adds logging (when verbose set) to the command run as well as improves the error message. --- magefile.go | 41 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 37 insertions(+), 4 deletions(-) diff --git a/magefile.go b/magefile.go index a215f1639d7..d1b1d316202 100644 --- a/magefile.go +++ b/magefile.go @@ -8,6 +8,7 @@ package main import ( + "bytes" "context" "fmt" "io" @@ -111,8 +112,22 @@ func Notice() error { return errors.Wrap(err, "failed running go list, please fix the issues reported") } fmt.Println(">> fmt - go run") - cmd := exec.Command("go", "run", "go.elastic.co/go-licence-detector", "-includeIndirect", "-rules", "dev-tools/notice/rules.json", "-overrides", "dev-tools/notice/overrides.json", "-noticeTemplate", "dev-tools/notice/NOTICE.txt.tmpl", - "-noticeOut", "NOTICE.txt", "-depsOut", "\"\"") + goLicenceDetectorCMD := []string{"go", + "run", + "go.elastic.co/go-licence-detector", + "-includeIndirect", + "-rules", + "dev-tools/notice/rules.json", + "-overrides", + "dev-tools/notice/overrides.json", + "-noticeTemplate", + "dev-tools/notice/NOTICE.txt.tmpl", + "-noticeOut", + "NOTICE.txt", + "-depsOut", + "\"\""} + printCMD(goLicenceDetectorCMD) + cmd := exec.Command(goLicenceDetectorCMD[0], goLicenceDetectorCMD[1:]...) stdin, err := cmd.StdinPipe() if err != nil { return errors.Wrap(err, "failed running go run, please fix the issues reported") @@ -126,10 +141,10 @@ func Notice() error { fmt.Println(err) } }() + out, err := cmd.CombinedOutput() wg.Wait() - _, err = cmd.CombinedOutput() if err != nil { - return errors.Wrap(err, "failed combined output, please fix the issues reported") + return fmt.Errorf("calling go-licence-detector returned an error: '%w'. Its output is: '%s'", err, string(out)) } return nil } @@ -925,3 +940,21 @@ func majorMinor() string { } return "" } + +// printCMD prints the command in the same format than when +// using the functions from the `sh` package. It also respects +// the mage verbose flag +func printCMD(cmd []string) { + if !mg.Verbose() { + return + } + + buff := &bytes.Buffer{} + + fmt.Fprintf(buff, "exec: %s", cmd[0]) + for _, arg := range cmd[1:] { + fmt.Fprintf(buff, " %q", arg) + } + + fmt.Println(buff.String()) +}