This repository has been archived by the owner on May 18, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdirectory_source.go
73 lines (62 loc) · 1.64 KB
/
directory_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
package configo
import (
"io/ioutil"
"log"
"path"
"strings"
)
// DirectorySource makes a key-value mapping available of filename (key) to file contents (value).
type DirectorySource struct {
files map[string]string
mustExist bool
path string
}
// FromDirectory reads the directory path provided. If the path does not exist, a panic will result.
func FromDirectory(path string) *DirectorySource {
return &DirectorySource{
mustExist: true,
path: path,
}
}
func FromOptionalDirectories(directories ...string) MultiSource {
var sources MultiSource
for _, directory := range directories {
sources = append(sources, FromOptionalDirectory(directory))
}
return sources
}
// FromOptionalDirectory reads the directory path provided, if it exists.
func FromOptionalDirectory(path string) *DirectorySource {
return &DirectorySource{
mustExist: false,
path: path,
}
}
func (this *DirectorySource) Strings(key string) ([]string, error) {
key = sanitizeKey(strings.ToLower(key))
filename, found := this.files[key]
if !found {
return nil, ErrKeyNotFound
}
data, err := ioutil.ReadFile(path.Join(this.path, filename))
if err != nil {
return nil, err
}
return []string{string(data)}, nil
}
func (this *DirectorySource) Initialize() {
this.files = make(map[string]string, 32)
if files, err := ioutil.ReadDir(this.path); err != nil {
log.Printf("[INFO] directory not read [%s]: %s\n", this.path, err)
if this.mustExist {
panic("directory must exist")
}
} else {
for _, file := range files {
if !file.IsDir() {
key := sanitizeKey(strings.ToLower(file.Name()))
this.files[key] = file.Name()
}
}
}
}