Skip to content

Commit 77461f7

Browse files
authored
Merge pull request #730 from owen-mc/bugfix/build/go-mod-tidy
Run `go mod tidy -e` before building
2 parents 32e2949 + 2930bd4 commit 77461f7

File tree

1 file changed

+40
-1
lines changed

1 file changed

+40
-1
lines changed

extractor/cli/go-autobuilder/go-autobuilder.go

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package main
22

33
import (
44
"fmt"
5-
"golang.org/x/mod/semver"
65
"io/ioutil"
76
"log"
87
"net/url"
@@ -13,6 +12,8 @@ import (
1312
"runtime"
1413
"strings"
1514

15+
"golang.org/x/mod/semver"
16+
1617
"github.com/github/codeql-go/extractor/autobuilder"
1718
"github.com/github/codeql-go/extractor/util"
1819
)
@@ -289,6 +290,44 @@ func main() {
289290
}
290291
}
291292

293+
// Go 1.16 and later won't automatically attempt to update go.mod / go.sum during package loading, so try to update them here:
294+
if depMode == GoGetWithModules && semver.Compare(getEnvGoSemVer(), "1.16") >= 0 {
295+
// stat go.mod and go.sum
296+
beforeGoModFileInfo, beforeGoModErr := os.Stat("go.mod")
297+
if beforeGoModErr != nil {
298+
log.Println("Failed to stat go.mod before running `go mod tidy -e`")
299+
}
300+
301+
beforeGoSumFileInfo, beforeGoSumErr := os.Stat("go.sum")
302+
303+
// run `go mod tidy -e`
304+
res := util.RunCmd(exec.Command("go", "mod", "tidy", "-e"))
305+
306+
if !res {
307+
log.Println("Failed to run `go mod tidy -e`")
308+
} else {
309+
if beforeGoModFileInfo != nil {
310+
afterGoModFileInfo, afterGoModErr := os.Stat("go.mod")
311+
if afterGoModErr != nil {
312+
log.Println("Failed to stat go.mod after running `go mod tidy -e`")
313+
} else if afterGoModFileInfo.ModTime().After(beforeGoModFileInfo.ModTime()) {
314+
// if go.mod has been changed then notify the user
315+
log.Println("We have run `go mod tidy -e` and it altered go.mod. You may wish to check these changes into version control. ")
316+
}
317+
}
318+
319+
afterGoSumFileInfo, afterGoSumErr := os.Stat("go.sum")
320+
if afterGoSumErr != nil {
321+
log.Println("Failed to stat go.sum after running `go mod tidy -e`")
322+
} else {
323+
if beforeGoSumErr != nil || afterGoSumFileInfo.ModTime().After(beforeGoSumFileInfo.ModTime()) {
324+
// if go.sum has been changed then notify the user
325+
log.Println("We have run `go mod tidy -e` and it altered go.sum. You may wish to check these changes into version control. ")
326+
}
327+
}
328+
}
329+
}
330+
292331
// if `LGTM_INDEX_NEED_GOPATH` is set, it overrides the value for `needGopath` inferred above
293332
if needGopathOverride := os.Getenv("LGTM_INDEX_NEED_GOPATH"); needGopathOverride != "" {
294333
inLGTM = true

0 commit comments

Comments
 (0)