forked from cloudfoundry/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tmp_utils.go
77 lines (62 loc) · 1.36 KB
/
tmp_utils.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
package fileutils
import (
"crypto/rand"
"fmt"
"math"
"math/big"
"os"
"path/filepath"
"time"
)
const dirMask = os.ModeDir | os.ModeTemporary | os.ModePerm
var tmpPathPrefix = ""
func SetTmpPathPrefix(path string) {
tmpPathPrefix = path
}
func TmpPathPrefix() string {
return tmpPathPrefix
}
func TempDir(namePrefix string, cb func(tmpDir string, err error)) {
baseDir, err := baseTempDir()
if err != nil {
return
}
tmpDir := filepath.Join(baseDir, uniqueKey(namePrefix))
err = os.MkdirAll(tmpDir, dirMask)
defer func() {
os.RemoveAll(tmpDir)
}()
cb(tmpDir, err)
}
func TempFile(namePrefix string, cb func(tmpFile *os.File, err error)) {
var (
tmpFile *os.File
tmpFilepath string
err error
tmpDir string
)
tmpDir, err = baseTempDir()
if err != nil {
cb(tmpFile, err)
return
}
tmpFilepath = filepath.Join(tmpDir, uniqueKey(namePrefix))
tmpFile, err = os.Create(tmpFilepath)
defer func() {
tmpFile.Close()
os.Remove(tmpFile.Name())
}()
cb(tmpFile, err)
}
func baseTempDir() (dir string, err error) {
dir = filepath.Join(os.TempDir(), TmpPathPrefix())
err = os.MkdirAll(dir, dirMask)
return
}
func uniqueKey(namePrefix string) string {
salt, err := rand.Int(rand.Reader, big.NewInt(math.MaxInt32))
if err != nil {
salt = big.NewInt(1)
}
return fmt.Sprintf("%s_%d_%d", namePrefix, time.Now().Unix(), salt)
}