-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmod.go
400 lines (342 loc) · 9.03 KB
/
mod.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
package testutil
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"testing"
"github.com/otiai10/copy"
"github.com/tenntenn/modver"
tnntransform "github.com/tenntenn/text/transform"
"golang.org/x/mod/modfile"
"golang.org/x/text/transform"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/analysistest"
)
// WithModules creates a temp dir which is copied from srcdir and generates vendor directory with go.mod.
// go.mod can be specified by modfileReader.
// Example:
//
// func TestAnalyzer(t *testing.T) {
// testdata := testutil.WithModules(t, analysistest.TestData(), nil)
// analysistest.Run(t, testdata, sample.Analyzer, "a")
// }
func WithModules(t *testing.T, testdata string, gomodfile io.Reader) (dir string) {
t.Helper()
dir = t.TempDir()
if err := copy.Copy(testdata, dir); err != nil {
t.Fatal("cannot copy a directory:", err)
}
src := filepath.Join(dir, "src")
var data []byte
if gomodfile != nil {
_data, err := io.ReadAll(gomodfile)
if err != nil {
t.Fatal("unexpected error:", err)
}
data = _data
}
replaceGoMod(t, src, data)
addLineComment(t, src)
return dir
}
func replaceGoMod(t *testing.T, src string, gomodfile []byte) {
t.Helper()
var ok bool
err := filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() || info.Name() != "go.mod" {
return nil
}
if gomodfile != nil {
if err := os.WriteFile(path, gomodfile, 0o644); err != nil {
t.Fatal("cannot write go.mod:", err)
}
}
dir := filepath.Dir(path)
execCmd(t, dir, "go", "mod", "tidy")
execCmd(t, dir, "go", "mod", "vendor")
ok = true
return nil
})
if err != nil {
t.Fatal("go mod vendor:", err)
}
if ok {
return
}
if gomodfile == nil {
t.Fatal("does not find go.mod")
}
entries, err := os.ReadDir(src)
if err != nil {
t.Fatal("unexpected error:", err)
}
for _, entry := range entries {
if !entry.IsDir() {
continue
}
pkgdir := filepath.Join(src, entry.Name())
fn := filepath.Join(pkgdir, "go.mod")
gomod, err := modfile.Parse(fn, gomodfile, nil)
if err != nil {
t.Fatal("unexpected error:", err)
}
gomod.AddModuleStmt(entry.Name())
gomod.Cleanup()
out, err := gomod.Format()
if err != nil {
t.Fatal("cannot format go.mod:", err)
}
if err := os.WriteFile(fn, out, 0o644); err != nil {
t.Fatal("cannot write go.mod:", err)
}
execCmd(t, pkgdir, "go", "mod", "tidy")
execCmd(t, pkgdir, "go", "mod", "vendor")
}
}
func addLineComment(t *testing.T, src string) {
t.Helper()
moddirs := make(map[string]string)
err := filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
// Prepend line directive to .go files
if filepath.Ext(info.Name()) == ".go" {
dir := filepath.Dir(path)
moddir, ok := moddirs[dir]
if !ok {
r := execCmd(t, dir, "go", "list", "-m", "-json")
var mod struct {
Dir string
}
if err := json.NewDecoder(r).Decode(&mod); err != nil {
t.Fatal("unexpected error:", err)
}
moddir = mod.Dir
}
rel, err := filepath.Rel(moddir, path)
if err != nil {
t.Fatal("cannot get relative path:", err)
}
if err := prependToFile(path, fmt.Sprintf("//line %s:1\n", rel)); err != nil {
t.Fatal("cannot prepend line directive:", err)
}
}
return nil
})
if err != nil {
t.Fatal("go mod vendor:", err)
}
}
func prependToFile(filename string, ld string) error {
f, err := os.OpenFile(filename, os.O_RDWR, 0)
if err != nil {
return err
}
defer f.Close()
b, err := io.ReadAll(f)
if err != nil {
return err
}
if _, err := f.Seek(0, 0); err != nil {
return err
}
if _, err := f.WriteString(ld + "\n"); err != nil {
return err
}
if _, err := f.Write(b); err != nil {
return err
}
return nil
}
// ModFile opens a mod file with the path and fixes versions by the version fixer.
// If the path is direcotry, ModFile opens go.mod which is under the path.
func ModFile(t *testing.T, path string, fix modfile.VersionFixer) io.Reader {
t.Helper()
gomod := path
info, err := os.Stat(path)
if err != nil {
t.Fatal("cannot get stat of path:", err)
}
if info.IsDir() {
gomod = modfilePath(t, path)
}
data, err := os.ReadFile(gomod)
if err != nil {
t.Fatal("cannot read go.mod:", err)
}
f, err := modfile.Parse(gomod, data, fix)
if err != nil {
t.Fatal("cannot parse go.mod:", err)
}
out, err := f.Format()
if err != nil {
t.Fatal("cannot format go.mod:", err)
}
return bytes.NewReader(out)
}
func modfilePath(t *testing.T, dir string) string {
t.Helper()
var stdout bytes.Buffer
cmd := exec.Command("go", "list", "-m", "-f", "{{.GoMod}}")
cmd.Dir = dir
cmd.Stdout = &stdout
if err := cmd.Run(); err != nil {
t.Fatalf("cannot get the parent module with %s: %v", dir, err)
}
gomod := strings.TrimSpace(stdout.String())
if gomod == "" {
t.Fatalf("cannot find go.mod, %s may not managed with Go Modules", dir)
}
return gomod
}
// ModuleVersion has module path and its version.
type ModuleVersion = modver.ModuleVersion
// AllVersion get available all versions of the module.
func AllVersion(t *testing.T, module string) []ModuleVersion {
t.Helper()
vers, err := modver.AllVersion(module)
if err != nil {
t.Fatal("unexpected error", err)
}
return vers
}
// FilterVersion returns versions of the module which satisfy the constraints such as ">= v2.0.0"
// The constraints rule uses github.com/hashicorp/go-version.
//
// Example:
//
// func TestAnalyzer(t *testing.T) {
// vers := FilterVersion(t, "github.com/tenntenn/greeting/v2", ">= v2.0.0")
// RunWithVersions(t, analysistest.TestData(), sample.Analyzer, vers, "a")
// }
func FilterVersion(t *testing.T, module, constraints string) []ModuleVersion {
t.Helper()
vers, err := modver.FilterVersion(module, constraints)
if err != nil {
t.Fatal("unexpected error", err)
}
return vers
}
// LatestVersion returns most latest versions (<= max) of each minner version.
//
// Example:
//
// func TestAnalyzer(t *testing.T) {
// vers := LatestVersion(t, "github.com/tenntenn/greeting/v2", 3)
// RunWithVersions(t, analysistest.TestData(), sample.Analyzer, vers, "a")
// }
func LatestVersion(t *testing.T, module string, max int) []ModuleVersion {
t.Helper()
vers, err := modver.LatestVersion(module, max)
if err != nil {
t.Fatal("unexpected error", err)
}
return vers
}
// RunWithVersions runs analysistest.Run with modules which version is specified the vers.
//
// Example:
//
// func TestAnalyzer(t *testing.T) {
// vers := AllVersion(t, "github.com/tenntenn/greeting/v2")
// RunWithVersions(t, analysistest.TestData(), sample.Analyzer, vers, "a")
// }
//
// The test run in temporary directory which is isolated the dir.
// analysistest.Run uses packages.Load and it prints errors into os.Stderr.
// Becase the error messages include the temporary directory path, so RunWithVersions replaces os.Stderr.
// Replacing os.Stderr is not thread safe.
// If you want to turn off replacing os.Stderr, you can use ReplaceStderr(false).
func RunWithVersions(t *testing.T, dir string, a *analysis.Analyzer, vers []ModuleVersion, pkg string) map[ModuleVersion][]*analysistest.Result {
t.Helper()
path := filepath.Join(dir, "src", pkg)
results := make(map[ModuleVersion][]*analysistest.Result, len(vers))
for _, modver := range vers {
modver := modver
t.Run(modver.String(), func(t *testing.T) {
t.Parallel()
modfile := ModFile(t, path, func(module, ver string) (string, error) {
if modver.Module == module {
return modver.Version, nil
}
return ver, nil
})
tmpdir := WithModules(t, dir, modfile)
replaceStderr(t, tmpdir, dir)
results[modver] = analysistest.Run(t, tmpdir, a, pkg)
})
}
return results
}
func execCmd(t *testing.T, dir, cmd string, args ...string) io.Reader {
t.Helper()
var stdout, stderr bytes.Buffer
_cmd := exec.Command(cmd, args...)
_cmd.Stdout = &stdout
_cmd.Stderr = &stderr
_cmd.Dir = dir
if err := _cmd.Run(); err != nil {
t.Fatal(err, "\n", &stderr)
}
return &stdout
}
var (
stderrMutex sync.RWMutex
doNotUseFilteredStderr bool
)
// ReplaceStderr sets whether RunWithVersions replace os.Stderr or not.
// The default value is true which means that RunWithVersions replaces os.Stderr.
func ReplaceStderr(onoff bool) {
stderrMutex.Lock()
doNotUseFilteredStderr = !onoff
stderrMutex.Unlock()
}
func replaceStderr(t *testing.T, old, new string) {
t.Helper()
stderrMutex.RLock()
ok := !doNotUseFilteredStderr
stderrMutex.RUnlock()
if !ok {
return
}
r, w, err := os.Pipe()
if err != nil {
t.Fatal("cannot create pipe", err)
}
origStderr := os.Stderr
stderrMutex.Lock()
os.Stderr = w
stderrMutex.Unlock()
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(func() {
cancel()
stderrMutex.Lock()
os.Stderr = origStderr
stderrMutex.Unlock()
})
go func() {
t := tnntransform.ReplaceString(old, new)
w := transform.NewWriter(origStderr, t)
for {
select {
case <-ctx.Done():
default:
io.CopyN(w, r, 1024)
}
}
}()
}