-
Notifications
You must be signed in to change notification settings - Fork 2
/
tmpdownloadpath.go
39 lines (34 loc) · 1.12 KB
/
tmpdownloadpath.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
package file
import (
"fmt"
"math/rand"
"os"
"time"
)
const TempDownloadExtension = "download"
// tmpDownloadPath Generates a unique temporary download path for a given file path by appending a ".download" extension and, if necessary, additional identifiers to avoid name conflicts.
func tmpDownloadPath(path string) (string, error) {
var index int
randGenerator := rand.New(rand.NewSource(time.Now().UnixNano()))
for {
var tempPath, uniqueness string
if index == 0 {
tempPath = fmt.Sprintf("%v.%v", path, TempDownloadExtension)
} else if index > 25 {
return "", fmt.Errorf("unable to create a unique temporary path after 25 attempts, consider deleting existing .%v files; attempted path: %v", TempDownloadExtension, path)
} else {
if index > 10 {
for i := 0; i < 4; i++ {
uniqueness += string(rune(randGenerator.Intn(26) + 'a'))
}
} else {
uniqueness = fmt.Sprintf("%v", index)
}
tempPath = fmt.Sprintf("%v (%v).%v", path, uniqueness, TempDownloadExtension)
}
if _, err := os.Stat(tempPath); os.IsNotExist(err) {
return tmpDownloadPathOnNotExist(path, tempPath)
}
index++
}
}