Skip to content

Commit 5513615

Browse files
gnuletikccojocar
authored andcommittedMar 20, 2024··
fix(helpers/goversion): get from go.mod
1 parent 43b8b75 commit 5513615

File tree

1 file changed

+36
-7
lines changed

1 file changed

+36
-7
lines changed
 

‎helpers.go

+36-7
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,15 @@
1515
package gosec
1616

1717
import (
18+
"bytes"
19+
"encoding/json"
1820
"errors"
1921
"fmt"
2022
"go/ast"
2123
"go/token"
2224
"go/types"
2325
"os"
26+
"os/exec"
2427
"os/user"
2528
"path/filepath"
2629
"regexp"
@@ -493,19 +496,45 @@ func RootPath(root string) (string, error) {
493496
return filepath.Abs(root)
494497
}
495498

496-
// GoVersion returns parsed version of Go from runtime
499+
// GoVersion returns parsed version of Go mod version and fallback to runtime version if not found.
497500
func GoVersion() (int, int, int) {
498-
return parseGoVersion(runtime.Version())
501+
goVersion, err := goModVersion()
502+
if err != nil {
503+
return parseGoVersion(strings.TrimPrefix(runtime.Version(), "go"))
504+
}
505+
506+
return parseGoVersion(goVersion)
507+
}
508+
509+
type goListOutput struct {
510+
GoVersion string `json:"GoVersion"`
511+
}
512+
513+
func goModVersion() (string, error) {
514+
cmd := exec.Command("go", "list", "-m", "-json")
515+
516+
raw, err := cmd.CombinedOutput()
517+
if err != nil {
518+
return "", fmt.Errorf("command go list: %w: %s", err, string(raw))
519+
}
520+
521+
var v goListOutput
522+
err = json.NewDecoder(bytes.NewBuffer(raw)).Decode(&v)
523+
if err != nil {
524+
return "", fmt.Errorf("unmarshaling error: %w: %s", err, string(raw))
525+
}
526+
527+
return v.GoVersion, nil
499528
}
500529

501530
// parseGoVersion parses Go version.
502531
// example:
503-
// - go1.19rc2
504-
// - go1.19beta2
505-
// - go1.19.4
506-
// - go1.19
532+
// - 1.19rc2
533+
// - 1.19beta2
534+
// - 1.19.4
535+
// - 1.19
507536
func parseGoVersion(version string) (int, int, int) {
508-
exp := regexp.MustCompile(`go(\d+).(\d+)(?:.(\d+))?.*`)
537+
exp := regexp.MustCompile(`(\d+).(\d+)(?:.(\d+))?.*`)
509538
parts := exp.FindStringSubmatch(version)
510539
if len(parts) <= 1 {
511540
return 0, 0, 0

0 commit comments

Comments
 (0)
Please sign in to comment.