forked from 0xERR0R/blocky
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtmpdata.go
126 lines (95 loc) · 1.89 KB
/
tmpdata.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
package helpertest
import (
"bufio"
"io/fs"
"os"
"path/filepath"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
type TmpFolder struct {
Path string
prefix string
}
type TmpFile struct {
Path string
Folder *TmpFolder
}
func NewTmpFolder(prefix string) *TmpFolder {
ipref := prefix
if len(ipref) == 0 {
ipref = "blocky"
}
path, err := os.MkdirTemp("", ipref)
Expect(err).Should(Succeed())
res := &TmpFolder{
Path: path,
prefix: ipref,
}
DeferCleanup(res.Clean)
return res
}
func (tf *TmpFolder) Clean() error {
if len(tf.Path) > 0 {
return os.RemoveAll(tf.Path)
}
return nil
}
func (tf *TmpFolder) CreateSubFolder(name string) *TmpFolder {
var path string
var err error
if len(name) > 0 {
path = filepath.Join(tf.Path, name)
err = os.Mkdir(path, fs.ModePerm)
} else {
path, err = os.MkdirTemp(tf.Path, tf.prefix)
}
Expect(err).Should(Succeed())
res := &TmpFolder{
Path: path,
prefix: tf.prefix,
}
return res
}
func (tf *TmpFolder) CreateEmptyFile(name string) *TmpFile {
f, res := tf.createFile(name)
defer f.Close()
return res
}
func (tf *TmpFolder) CreateStringFile(name string, lines ...string) *TmpFile {
f, res := tf.createFile(name)
defer f.Close()
first := true
w := bufio.NewWriter(f)
for _, l := range lines {
if first {
first = false
} else {
_, err := w.WriteString("\n")
Expect(err).Should(Succeed())
}
_, err := w.WriteString(l)
Expect(err).Should(Succeed())
}
w.Flush()
return res
}
func (tf *TmpFolder) JoinPath(name string) string {
return filepath.Join(tf.Path, name)
}
func (tf *TmpFolder) createFile(name string) (*os.File, *TmpFile) {
var (
f *os.File
err error
)
if len(name) > 0 {
f, err = os.Create(filepath.Join(tf.Path, name))
} else {
f, err = os.CreateTemp(tf.Path, "temp")
}
Expect(err).Should(Succeed())
return f, &TmpFile{
Path: f.Name(),
Folder: tf,
}
}