-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain_test.go
413 lines (359 loc) · 9.36 KB
/
main_test.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
401
402
403
404
405
406
407
408
409
410
411
412
413
// Copyright 2022 The Hugoreleaser Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"archive/tar"
"bytes"
"compress/gzip"
"fmt"
"io"
"io/fs"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"testing"
"time"
"github.com/bep/helpers/envhelpers"
"github.com/bep/helpers/filehelpers"
"github.com/rogpeppe/go-internal/testscript"
)
// Note: If tests are running slow for you, make sure you have GOMODCACHE set.
func TestCommands(t *testing.T) {
setup := testSetupFunc()
testscript.Run(t, testscript.Params{
Dir: "testscripts/commands",
Setup: func(env *testscript.Env) error {
return setup(env)
},
})
}
func TestMisc(t *testing.T) {
setup := testSetupFunc()
testscript.Run(t, testscript.Params{
Dir: "testscripts/misc",
// UpdateScripts: true,
Setup: func(env *testscript.Env) error {
return setup(env)
},
})
}
// Tests in development can be put in "testscripts/unfinished".
func TestUnfinished(t *testing.T) {
if os.Getenv("CI") != "" {
t.Skip("skip unfinished tests on CI")
}
setup := testSetupFunc()
testscript.Run(t, testscript.Params{
Dir: "testscripts/unfinished",
// TestWork: true,
// UpdateScripts: true,
Setup: func(env *testscript.Env) error {
return setup(env)
},
})
}
func testSetupFunc() func(env *testscript.Env) error {
sourceDir, _ := os.Getwd()
return func(env *testscript.Env) error {
var keyVals []string
// SOURCE is where the hugoreleaser source code lives.
// We do this so we can
// 1. Copy the example/test plugins into the WORK dir where the test script is running.
// 2. Append a replace directive to the plugins' go.mod to get the up-to-date version of the plugin API.
//
// This is a hybrid setup neeed to get a quick development cycle going.
// In production, the plugin Go modules would be addressed on their full form, e.g. "github.com/gohugoio/hugoreleaser/internal/plugins/archives/[email protected]".
keyVals = append(keyVals, "SOURCE", sourceDir)
keyVals = append(keyVals, "GOCACHE", filepath.Join(env.WorkDir, "gocache"))
var gomodCache string
if c := os.Getenv("GOMODCACHE"); c != "" {
// Testscripts will set the GOMODCACHE to an empty dir,
// and this slows down some tests considerably.
// Use the OS env var if it is set.
gomodCache = c
} else {
gomodCache = filepath.Join(env.WorkDir, "gomodcache")
}
keyVals = append(keyVals, "GOMODCACHE", gomodCache)
envhelpers.SetEnvVars(&env.Vars, keyVals...)
return nil
}
}
func TestMain(m *testing.M) {
os.Exit(
testscript.RunMain(m, map[string]func() int{
// The main program.
"hugoreleaser": func() int {
if err := parseAndRun(os.Args[1:]); err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
return 0
},
// dostounix converts \r\n to \n.
"dostounix": func() int {
filename := os.Args[1]
b, err := os.ReadFile(filename)
if err != nil {
fatalf("%v", err)
}
b = bytes.Replace(b, []byte("\r\n"), []byte{'\n'}, -1)
if err := os.WriteFile(filename, b, 0o666); err != nil {
fatalf("%v", err)
}
return 0
},
// log prints to stderr.
"log": func() int {
log.Println(os.Args[1])
return 0
},
"sleep": func() int {
i, err := strconv.Atoi(os.Args[1])
if err != nil {
i = 1
}
time.Sleep(time.Duration(i) * time.Second)
return 0
},
// ls lists a directory to stdout.
"ls": func() int {
dirname := os.Args[1]
dir, err := os.Open(dirname)
if err != nil {
fatalf("%v", err)
}
fis, err := dir.Readdir(-1)
if err != nil {
fatalf("%v", err)
}
for _, fi := range fis {
fmt.Printf("%s %04o %s\n", fi.Mode(), fi.Mode().Perm(), fi.Name())
}
return 0
},
// printarchive prints the contents of an archive to stdout.
"printarchive": func() int {
archiveFilename := os.Args[1]
if !strings.HasSuffix(archiveFilename, ".tar.gz") {
fatalf("only .tar.gz supported for now, got: %q", archiveFilename)
}
f, err := os.Open(archiveFilename)
if err != nil {
fatalf("%v", err)
}
defer f.Close()
gr, err := gzip.NewReader(f)
if err != nil {
fatalf("%v", err)
}
defer gr.Close()
tr := tar.NewReader(gr)
for {
hdr, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
fatalf("%v", err)
}
mode := fs.FileMode(hdr.Mode)
fmt.Printf("%s %04o %s\n", mode, mode.Perm(), hdr.Name)
}
return 0
},
// cpdir copies a file.
"cpfile": func() int {
if len(os.Args) != 3 {
fmt.Fprintln(os.Stderr, "usage: cpdir SRC DST")
return 1
}
fromFile := os.Args[1]
toFile := os.Args[2]
if !filepath.IsAbs(fromFile) {
fromFile = filepath.Join(os.Getenv("SOURCE"), fromFile)
}
if err := os.MkdirAll(filepath.Dir(toFile), 0o755); err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
err := filehelpers.CopyFile(fromFile, toFile)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
return 0
},
// cpdir copies a directory recursively.
"cpdir": func() int {
if len(os.Args) != 3 {
fmt.Fprintln(os.Stderr, "usage: cpdir SRC DST")
return 1
}
fromDir := os.Args[1]
toDir := os.Args[2]
if !filepath.IsAbs(fromDir) {
fromDir = filepath.Join(os.Getenv("SOURCE"), fromDir)
}
err := filehelpers.CopyDir(fromDir, toDir, nil)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
return 0
},
// append appends to a file with a leaading newline.
"append": func() int {
if len(os.Args) < 3 {
fmt.Fprintln(os.Stderr, "usage: append FILE TEXT")
return 1
}
filename := os.Args[1]
words := os.Args[2:]
for i, word := range words {
words[i] = strings.Trim(word, "\"")
}
text := strings.Join(words, " ")
_, err := os.Stat(filename)
if err != nil {
if os.IsNotExist(err) {
fmt.Fprintln(os.Stderr, "file does not exist:", filename)
return 1
}
fmt.Fprintln(os.Stderr, err)
return 1
}
f, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0o644)
if err != nil {
fmt.Fprintln(os.Stderr, "failed to open file:", filename)
return 1
}
defer f.Close()
_, err = f.WriteString("\n" + text)
if err != nil {
fmt.Fprintln(os.Stderr, "failed to write to file:", filename)
return 1
}
return 0
},
// Helpers.
"checkfile": func() int {
// The built-in exists does not check for zero size files.
args := os.Args[1:]
var readonly, exec bool
loop:
for len(args) > 0 {
switch args[0] {
case "-readonly":
readonly = true
args = args[1:]
case "-exec":
exec = true
args = args[1:]
default:
break loop
}
}
if len(args) == 0 {
fatalf("usage: checkfile [-readonly] [-exec] file...")
}
for _, filename := range args {
fi, err := os.Stat(filename)
if err != nil {
fmt.Fprintf(os.Stderr, "stat %s: %v\n", filename, err)
return -1
}
if fi.Size() == 0 {
fmt.Fprintf(os.Stderr, "%s is empty\n", filename)
return -1
}
if readonly && fi.Mode()&0o222 != 0 {
fmt.Fprintf(os.Stderr, "%s is writable\n", filename)
return -1
}
if exec && runtime.GOOS != "windows" && fi.Mode()&0o111 == 0 {
fmt.Fprintf(os.Stderr, "%s is not executable\n", filename)
return -1
}
}
return 0
},
"checkfilecount": func() int {
if len(os.Args) != 3 {
fatalf("usage: checkfilecount count dir")
}
count, err := strconv.Atoi(os.Args[1])
if err != nil {
fatalf("invalid count: %v", err)
}
if count < 0 {
fatalf("count must be non-negative")
}
dir := os.Args[2]
found := 0
filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
found++
return nil
})
if found != count {
fmt.Fprintf(os.Stderr, "found %d files, want %d\n", found, count)
return -1
}
return 0
},
"gobinary": func() int {
if runtime.GOOS == "windows" {
return 0
}
if len(os.Args) < 3 {
fatalf("usage: gobinary binary args...")
}
filename := os.Args[1]
pattern := os.Args[2]
if !strings.HasPrefix(pattern, "(") {
// Multiline matching.
pattern = "(?s)" + pattern
}
re := regexp.MustCompile(pattern)
cmd := exec.Command("go", "version", "-m", filename)
cmd.Stderr = os.Stderr
b, err := cmd.Output()
if err != nil {
fmt.Fprintln(os.Stderr, err)
return -1
}
output := string(b)
if !re.MatchString(output) {
fmt.Fprintf(os.Stderr, "expected %q to match %q\n", output, re)
return -1
}
return 0
},
}),
)
}
func fatalf(format string, a ...any) {
panic(fmt.Sprintf(format, a...))
}