/
tempdir.go
78 lines (66 loc) · 2.01 KB
/
tempdir.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
package tempdir
import (
"io/ioutil"
"os"
"strings"
"golang.org/x/xerrors"
)
func MakeTempDir(name string) string {
tempDir, err := MakeTempDirE(name)
if err != nil {
panic(err)
}
return tempDir
}
// MakeTempDirE creates a temporary directory with the given name as a prefix.
func MakeTempDirE(name string) (s string, err error) {
defer func() {
if err != nil {
err = xerrors.Errorf("failed to create temporary directory with name %s: %w", name, err)
}
}()
tempDir, err := ioutil.TempDir(os.TempDir(), strings.ReplaceAll(name, " ", "-"))
if err != nil {
return
}
return tempDir, nil
}
func DeleteTempDir(path string) {
if err := DeleteTempDirE(path); err != nil {
panic(err)
}
}
func DeleteTempDirE(path string) (err error) {
defer func() {
if err != nil {
err = xerrors.Errorf("failed to remove temp dir at %s: %w", err)
}
}()
return os.RemoveAll(path)
}
// DeleteTempDirExistingError deletes the given path and prints corresponding messages if it fails whether an existing error exists or not.
func DeleteTempDirExistingError(path string, existingError *error) (err error) {
defer func() {
if err != nil {
if *existingError != nil {
err = xerrors.Errorf("cleanup of directory (%s) failed with (%v) while having an error already: %w", path, err, *existingError)
} else {
err = xerrors.Errorf("failed to remove temp dir at %s: %w", err)
}
}
}()
return os.RemoveAll(path)
}
// DeleteTempDirExistingError deletes the given path and prints corresponding messages if it fails whether an existing error exists or not.
func DeleteTempDirExistingErrorNoReturn(path string, existingError *error) {
cleanupError := os.RemoveAll(path)
if existingError != nil {
if *existingError != nil {
*existingError = xerrors.Errorf("cleanup of directory (%s) failed with (%v) while having an error already: %w", path, cleanupError, *existingError)
} else {
*existingError = xerrors.Errorf("failed to remove temp dir at %s: %w", cleanupError)
}
} else {
existingError = &cleanupError
}
}