-
Notifications
You must be signed in to change notification settings - Fork 0
/
temp.go
73 lines (64 loc) · 1.75 KB
/
temp.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
package backupfs
import (
"crypto/rand"
"errors"
"io/fs"
"math/big"
"os"
"path/filepath"
)
// TempDir creates a new temporary directory in the directory dir with a name
// that has the prefix prefix and returns the path of the new directory.
// If dir is the empty string, TempDir uses the default OS temp directory.
func TempDir(fsys FS, dir, prefix string) (name string, err error) {
if dir == "" {
dir = os.TempDir()
}
const (
randLen = 16
perm = 0o700
)
for i := 0; i < 10000; i++ {
tmpDirName := randStringFromCharSetWithPrefix(randLen, charSetAlphaNum, prefix)
try := filepath.Join(dir, tmpDirName)
err = fsys.MkdirAll(try, perm)
if errors.Is(err, fs.ErrExist) {
continue
}
if err == nil {
name = try
}
break
}
return
}
const (
// CharSetAlphaNum is the alphanumeric character set for use with
// randStringFromCharSet
charSetAlphaNum = "abcdefghijklmnopqrstuvwxyz012346789"
)
// randIntRange returns a random integer between min (inclusive) and max (exclusive)
func randIntRange(min int, max int) int {
rbi, err := rand.Int(rand.Reader, big.NewInt(int64(max-min)))
if err != nil {
panic(err)
}
return min + int(rbi.Int64())
}
// randStringFromCharSet generates a random string by selecting characters from
// the charset provided
func randStringFromCharSet(strlen int, charSet string) string {
if strlen <= 0 {
return ""
}
result := make([]byte, strlen)
for i := 0; i < strlen; i++ {
result[i] = charSet[randIntRange(0, len(charSet))]
}
return string(result)
}
// randStringFromCharSetWithPrefix generates a random string by selecting characters from
// the charset provided
func randStringFromCharSetWithPrefix(strlen int, charSet, prefix string) string {
return prefix + randStringFromCharSet(strlen, charSet)
}