-
Notifications
You must be signed in to change notification settings - Fork 3
/
tempdir.go
53 lines (43 loc) · 1.06 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
package ociinstaller
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/google/uuid"
"github.com/turbot/pipe-fittings/v2/error_helpers"
)
type tempDir struct {
Path string
}
// NewTempDir creates a directory under the given parent directory.
func NewTempDir(parent string) *tempDir {
return &tempDir{
Path: getOrCreateTempDir(parent),
}
}
func getOrCreateTempDir(parent string) string {
cacheDir := filepath.Join(parent, safeDirName(fmt.Sprintf("tmp-%s", generateTempDirName())))
if _, err := os.Stat(cacheDir); os.IsNotExist(err) {
err = os.MkdirAll(cacheDir, 0755)
error_helpers.FailOnErrorWithMessage(err, "could not create cache directory")
}
return cacheDir
}
func (d *tempDir) Delete() error {
return os.RemoveAll(d.Path)
}
func safeDirName(dirName string) string {
newName := strings.ReplaceAll(dirName, "/", "_")
newName = strings.ReplaceAll(newName, ":", "@")
return newName
}
func generateTempDirName() string {
u, err := uuid.NewRandom()
if err != nil {
// Should never happen?
panic(err)
}
s := u.String()
return s[9:23]
}