1
1
package config
2
2
3
3
import (
4
+ "cmp"
5
+ "fmt"
4
6
"os"
7
+ "path/filepath"
8
+ "slices"
5
9
"strings"
6
10
7
11
hcversion "github.com/hashicorp/go-version"
8
- "github.com/ldez/gomoddirectives"
12
+ "github.com/ldez/grignotin/gomod"
13
+ "golang.org/x/mod/modfile"
9
14
)
10
15
11
16
// Config encapsulates the config data specified in the golangci-lint YAML config file.
@@ -93,8 +98,33 @@ func detectGoVersion() string {
93
98
// else it returns `go` version if present,
94
99
// else it returns empty.
95
100
func detectGoVersionFromGoMod () string {
96
- file , _ := gomoddirectives .GetModuleFile ()
97
- if file == nil {
101
+ info , err := gomod .GetModuleInfo ()
102
+ if err != nil {
103
+ return ""
104
+ }
105
+
106
+ wd , err := os .Getwd ()
107
+ if err != nil {
108
+ return ""
109
+ }
110
+
111
+ slices .SortFunc (info , func (a , b gomod.ModInfo ) int {
112
+ return cmp .Compare (len (b .Path ), len (a .Path ))
113
+ })
114
+
115
+ goMod := info [0 ]
116
+ for _ , m := range info {
117
+ if ! strings .HasPrefix (wd , m .Dir ) {
118
+ continue
119
+ }
120
+
121
+ goMod = m
122
+
123
+ break
124
+ }
125
+
126
+ file , err := parseGoMod (goMod .GoMod )
127
+ if err != nil {
98
128
return ""
99
129
}
100
130
@@ -110,3 +140,12 @@ func detectGoVersionFromGoMod() string {
110
140
111
141
return ""
112
142
}
143
+
144
+ func parseGoMod (goMod string ) (* modfile.File , error ) {
145
+ raw , err := os .ReadFile (filepath .Clean (goMod ))
146
+ if err != nil {
147
+ return nil , fmt .Errorf ("reading go.mod file: %w" , err )
148
+ }
149
+
150
+ return modfile .Parse ("go.mod" , raw , nil )
151
+ }
0 commit comments