-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
79 lines (63 loc) · 1.52 KB
/
file.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
package lru
import (
"os"
"path/filepath"
"time"
"github.com/pkg/errors"
)
// FileObject is a simple struct that tracks data
type FileObject struct {
Size int
Time time.Time
Path string
index int
}
// NewFile constructs a FileObject from its pathname and an
// os.FileInfo object. If the object is a directory, this method does
// not sum the total size of the directory.
func NewFile(fn string, info os.FileInfo) *FileObject {
return &FileObject{
Path: fn,
Time: info.ModTime(),
Size: int(info.Size()),
}
}
// Update refreshs the objects data, and sums the total size of all
// objects in a directory if the object refers to a directory.
func (f *FileObject) Update() error {
stat, err := os.Stat(f.Path)
if os.IsNotExist(err) {
return errors.Errorf("file %s no longer exists", f.Path)
}
f.Time = stat.ModTime()
if stat.IsDir() {
size, err := dirSize(f.Path)
if err != nil {
return errors.Wrapf(err, "problem finding size of directory %d", f.Path)
}
f.Size = int(size)
} else {
f.Size = int(stat.Size())
}
return nil
}
// Remove deletes the file object, recursively if necessary.
func (f *FileObject) Remove() error {
return os.RemoveAll(f.Path)
}
func dirSize(path string) (int64, error) {
var size int64
err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
size += info.Size()
}
return nil
})
if err != nil {
return 0, errors.Wrapf(err, "problem getting size of %s", path)
}
return size, nil
}