-
Notifications
You must be signed in to change notification settings - Fork 0
/
clean.go
125 lines (111 loc) · 2.46 KB
/
clean.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
// Copyright 2017. All rights reserved.
// This file is part of cleaner project
// Created by duguying on 2017/10/1.
package cleaner
import (
"io"
"log"
"os"
"path/filepath"
"time"
)
type FCleaner struct {
root string
expire time.Duration
interval time.Duration
batchNum int64
filter func(path string, info os.FileInfo) (willClean bool)
count int64
}
// New new a Cleaner
// root - root directory
// expire - expire time
// interval - scan interval
// batchNum - every scan remove batch number limit
func New(root string, expire time.Duration, interval time.Duration, batchNum int64) *FCleaner {
return &FCleaner{
root: root,
expire: expire,
interval: interval,
batchNum: batchNum,
filter: func(path string, info os.FileInfo) (willClean bool) {
return true
},
}
}
func (fc *FCleaner) SetFilter(filter func(path string, info os.FileInfo) (willClean bool)) {
fc.filter = filter
}
// StartCleanTask start the cleaning task
func (fc *FCleaner) StartCleanTask() {
go func(fc *FCleaner) {
for {
fc.count = 0
err := fc.clean(fc.root)
if err != nil {
log.Printf("[FCleaner] clean err: %v\n", err)
}
log.Printf("[FCleaner] total file number: %d\n", fc.count)
time.Sleep(fc.interval)
}
}(fc)
}
func (fc *FCleaner) clean(root string) error {
defer func() {
if re := recover(); re != nil {
log.Println("clean log recover panic : ", re)
}
}()
return filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if path == root {
return nil
}
if fc.batchNum > 0 && fc.count > fc.batchNum {
return nil
}
if info.IsDir() {
// do sth
err := fc.clean(path)
if err != nil {
return err
} else {
empty, err := fc.isEmpty(path)
if err == nil && empty {
// remove empty directory
fc.removePath(path)
}
return nil
}
} else {
// do clean
if fc.filter(path, info) && fc.checkExpire(info) {
fc.removePath(path)
}
return nil
}
})
}
func (fc *FCleaner) removePath(path string) error {
fc.count++
log.Println("[cleaner]", path)
return os.Remove(path)
}
func (fc *FCleaner) checkExpire(info os.FileInfo) (isExpire bool) {
if info.ModTime().Add(fc.expire).Before(time.Now()) {
return true
} else {
return false
}
}
func (fc *FCleaner) isEmpty(path string) (bool, error) {
f, err := os.Open(path)
if err != nil {
return false, err
}
defer f.Close()
_, err = f.Readdirnames(1)
if err == io.EOF {
return true, nil
}
return false, err
}