-
Notifications
You must be signed in to change notification settings - Fork 0
/
helper.go
102 lines (93 loc) · 2.15 KB
/
helper.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package revolver
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
)
func setupDirs(dirs string) error {
dirs = filepath.FromSlash(dirs)
if dirs == "." {
return nil
}
info, err := os.Stat(dirs)
if err == nil {
if !info.IsDir() {
return fmt.Errorf("error in dir setup %s is not a directory", dirs)
}
return nil
}
if !os.IsNotExist(err) {
return fmt.Errorf("error in dir setup, %v", err)
}
return os.MkdirAll(dirs, 0755)
}
func createFile(dir, prefix, suffix string, filename func() string) (*os.File, error) {
name := filepath.FromSlash(filepath.Join(dir, prefix+filename()))
try := 0
file := name
for {
file = file + suffix
if _, err := os.Stat(file); err != nil {
if os.IsNotExist(err) {
return os.Create(file)
}
return nil, fmt.Errorf("error on create file, %v", err)
}
file = name + "_" + strconv.Itoa(try)
try++
}
}
func fileCount(dir, prefix string) (int, error) {
files, err := ioutil.ReadDir(filepath.FromSlash(dir))
if err != nil {
return 0, fmt.Errorf("error while counting files, %v", err)
}
count := 0
for _, info := range files {
if isRevolverFile(prefix, info) {
count++
}
}
return count, nil
}
func removeOldestFile(dir, prefix string) error {
dir = filepath.FromSlash(dir)
files, err := ioutil.ReadDir(dir)
if err != nil {
return fmt.Errorf("error listing oldest file, %v", err)
}
var oldest os.FileInfo
for _, info := range files {
if isRevolverFile(prefix, info) && isOlder(info, oldest) {
oldest = info
}
}
if oldest != nil {
if err := os.Remove(filepath.Join(dir, oldest.Name())); err != nil {
return fmt.Errorf("error removing oldest file, %v", err)
}
}
return nil
}
func isRevolverFile(prefix string, file os.FileInfo) bool {
return !file.IsDir() && strings.HasPrefix(file.Name(), prefix)
}
func isOlder(test, old os.FileInfo) bool {
return old == nil || old.ModTime().After(test.ModTime())
}
func countAndRemoveFiles(dir, prefix string, maxFiles int) error {
count, err := fileCount(dir, prefix)
if err != nil {
return err
}
for maxFiles <= count {
if err := removeOldestFile(dir, prefix); err != nil {
return err
}
count--
}
return nil
}