This repository has been archived by the owner on Aug 27, 2019. It is now read-only.
forked from apuigsech/seekret
/
load_source.go
95 lines (74 loc) · 1.63 KB
/
load_source.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
package sourcedir
import (
"github.com/18F/seekret"
"github.com/18F/seekret/models"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
var (
SourceTypeDir = &SourceDir{}
)
const (
Type = "dir"
)
type SourceDir struct{}
type SourceDirLoadOptions struct {
Hidden bool
Recursive bool
}
func prepareDirLoadOptions(o seekret.LoadOptions) SourceDirLoadOptions {
opt := SourceDirLoadOptions{
Hidden: false,
Recursive: false,
}
if hidden, ok := o["hidden"].(bool); ok {
opt.Hidden = hidden
}
if recursive, ok := o["recursive"].(bool); ok {
opt.Recursive = recursive
}
return opt
}
func (s *SourceDir) LoadObjects(source string, opta seekret.LoadOptions) ([]models.Object, error) {
var objectList []models.Object
opt := prepareDirLoadOptions(opta)
firstPath := true
err := filepath.Walk(source, func(path string, fi os.FileInfo, err error) error {
if err != nil {
return err
}
if fi.IsDir() {
if firstPath {
firstPath = false
return nil
}
if strings.HasPrefix(filepath.Base(path), ".") && !opt.Hidden {
return filepath.SkipDir
}
if !firstPath && !opt.Recursive {
return filepath.SkipDir
}
} else {
if !strings.HasPrefix(filepath.Base(path), ".") || (strings.HasPrefix(filepath.Base(path), ".") && opt.Hidden) {
f, err := os.Open(path)
if err != nil {
return err
}
content, err := ioutil.ReadAll(f)
if err != nil {
return err
}
o := models.NewObject(path, Type, "file-content", content)
objectList = append(objectList, *o)
f.Close()
}
}
return nil
})
if err != nil {
return objectList, err
}
return objectList, nil
}