1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package driver
16
17 import (
18 "fmt"
19 "os"
20 "path/filepath"
21 "sync"
22 )
23
24
25 func newTempFile(dir, prefix, suffix string) (*os.File, error) {
26 for index := 1; index < 10000; index++ {
27 switch f, err := os.OpenFile(filepath.Join(dir, fmt.Sprintf("%s%03d%s", prefix, index, suffix)), os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666); {
28 case err == nil:
29 return f, nil
30 case !os.IsExist(err):
31 return nil, err
32 }
33 }
34
35 return nil, fmt.Errorf("could not create file of the form %s%03d%s", prefix, 1, suffix)
36 }
37
38 var tempFiles []string
39 var tempFilesMu = sync.Mutex{}
40
41
42 func deferDeleteTempFile(path string) {
43 tempFilesMu.Lock()
44 tempFiles = append(tempFiles, path)
45 tempFilesMu.Unlock()
46 }
47
48
49 func cleanupTempFiles() error {
50 tempFilesMu.Lock()
51 defer tempFilesMu.Unlock()
52 var lastErr error
53 for _, f := range tempFiles {
54 if err := os.Remove(f); err != nil {
55 lastErr = err
56 }
57 }
58 tempFiles = nil
59 return lastErr
60 }
61
View as plain text