forked from benthosdev/benthos
/
from_directory.go
71 lines (57 loc) · 1.72 KB
/
from_directory.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
package manager
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/Jeffail/benthos/v3/lib/config"
"github.com/Jeffail/benthos/v3/lib/stream"
)
//------------------------------------------------------------------------------
// LoadStreamConfigsFromDirectory reads a map of stream ids to configurations
// by walking a directory of .json and .yaml files.
func LoadStreamConfigsFromDirectory(replaceEnvVars bool, dir string) (map[string]stream.Config, error) {
streamMap := map[string]stream.Config{}
dir = filepath.Clean(dir)
if info, err := os.Stat(dir); err != nil {
if os.IsNotExist(err) {
return streamMap, nil
}
return nil, err
} else if !info.IsDir() {
return streamMap, nil
}
err := filepath.Walk(dir, func(path string, info os.FileInfo, werr error) error {
if werr != nil {
return werr
}
if info.IsDir() ||
(!strings.HasSuffix(info.Name(), ".yaml") &&
!strings.HasSuffix(info.Name(), ".json")) {
return nil
}
var id string
if id, werr = filepath.Rel(dir, path); werr != nil {
return werr
}
id = strings.Trim(id, string(filepath.Separator))
id = strings.Replace(id, string(filepath.Separator), "_", -1)
if strings.HasSuffix(info.Name(), ".yaml") {
id = strings.TrimSuffix(id, ".yaml")
} else {
id = strings.TrimSuffix(id, ".json")
}
if _, exists := streamMap[id]; exists {
return fmt.Errorf("stream id (%v) collision from file: %v", id, path)
}
conf := config.New()
if _, readerr := config.Read(path, true, &conf); readerr != nil {
// TODO: Read and report linting errors.
return readerr
}
streamMap[id] = conf.Config
return nil
})
return streamMap, err
}
//------------------------------------------------------------------------------