...
1
5 package fs
6
7 import (
8 "os"
9 "path/filepath"
10 "runtime"
11 "strings"
12
13 "gotest.tools/v3/assert"
14 "gotest.tools/v3/internal/cleanup"
15 )
16
17
18
19
20 type Path interface {
21 Path() string
22 Remove()
23 }
24
25 var (
26 _ Path = &Dir{}
27 _ Path = &File{}
28 )
29
30
31 type File struct {
32 path string
33 }
34
35 type helperT interface {
36 Helper()
37 }
38
39
40
41
42
43
44 func NewFile(t assert.TestingT, prefix string, ops ...PathOp) *File {
45 if ht, ok := t.(helperT); ok {
46 ht.Helper()
47 }
48 tempfile, err := os.CreateTemp("", cleanPrefix(prefix)+"-")
49 assert.NilError(t, err)
50
51 file := &File{path: tempfile.Name()}
52 cleanup.Cleanup(t, file.Remove)
53
54 assert.NilError(t, tempfile.Close())
55 assert.NilError(t, applyPathOps(file, ops))
56 return file
57 }
58
59 func cleanPrefix(prefix string) string {
60
61 if runtime.GOOS == "windows" {
62 prefix = strings.Replace(prefix, string(os.PathSeparator), "-", -1)
63 }
64 return strings.Replace(prefix, "/", "-", -1)
65 }
66
67
68 func (f *File) Path() string {
69 return f.path
70 }
71
72
73 func (f *File) Remove() {
74 _ = os.Remove(f.path)
75 }
76
77
78 type Dir struct {
79 path string
80 }
81
82
83
84
85
86
87 func NewDir(t assert.TestingT, prefix string, ops ...PathOp) *Dir {
88 if ht, ok := t.(helperT); ok {
89 ht.Helper()
90 }
91 path, err := os.MkdirTemp("", cleanPrefix(prefix)+"-")
92 assert.NilError(t, err)
93 dir := &Dir{path: path}
94 cleanup.Cleanup(t, dir.Remove)
95
96 assert.NilError(t, applyPathOps(dir, ops))
97 return dir
98 }
99
100
101 func (d *Dir) Path() string {
102 return d.path
103 }
104
105
106 func (d *Dir) Remove() {
107 _ = os.RemoveAll(d.path)
108 }
109
110
111 func (d *Dir) Join(parts ...string) string {
112 return filepath.Join(append([]string{d.Path()}, parts...)...)
113 }
114
115
116
117
118
119
120
121 func DirFromPath(t assert.TestingT, path string, ops ...PathOp) *Dir {
122 if ht, ok := t.(helperT); ok {
123 ht.Helper()
124 }
125
126 dir := &Dir{path: path}
127 assert.NilError(t, applyPathOps(dir, ops))
128 return dir
129 }
130
View as plain text