-
Notifications
You must be signed in to change notification settings - Fork 0
/
populate.go
88 lines (69 loc) · 2.01 KB
/
populate.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
package lru
import (
"io/ioutil"
"os"
"path/filepath"
"github.com/deciduosity/grip"
"github.com/pkg/errors"
)
// DirectoryContents takes a path and builds a cache object. If
// skipDir is true, this option does not include any directories,
// otherwise all directories are included in the cache. When including
// directories in the cache, lru includes the aggregate size of files
// in the directory.
func DirectoryContents(path string, skipDir bool) (*Cache, error) {
absPath, err := filepath.Abs(path)
if err != nil {
return nil, errors.Wrapf(err, "problem getting absolute path for '%s'", path)
}
path = absPath
infos, err := ioutil.ReadDir(path)
if err != nil {
return nil, errors.Wrapf(err, "problem getting directory contents for '%s'", path)
}
c := NewCache()
catcher := grip.NewCatcher()
for _, info := range infos {
if info.IsDir() && skipDir {
continue
}
fn := filepath.Join(path, info.Name())
catcher.Add(c.AddStat(fn, info))
}
if catcher.HasErrors() {
return nil, errors.Wrapf(err, "problem building cache with %d items (of %d)",
catcher.Len(), c.Count())
}
grip.Debugf("created new cache, with %d items and %d bytes",
c.Count(), c.Size())
return c, nil
}
// TreeContents adds all file system items, excluding directories, to
// a cache object.
func TreeContents(root string) (*Cache, error) {
absPath, err := filepath.Abs(root)
if err != nil {
return nil, errors.Wrapf(err, "problem getting absolute path for '%s'", root)
}
root = absPath
c := NewCache()
catcher := grip.NewCatcher()
catcher.Add(filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
fn := filepath.Join(path, info.Name())
catcher.Add(c.AddStat(fn, info))
return nil
}))
if catcher.HasErrors() {
return nil, errors.Wrapf(err, "problem building cache with %d items (of %d)",
catcher.Len(), c.Count())
}
grip.Debugf("created new cache, with %d items and %d bytes",
c.Count(), c.Size())
return c, nil
}