-
Notifications
You must be signed in to change notification settings - Fork 3
/
YamlFile.go
89 lines (74 loc) · 2.5 KB
/
YamlFile.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
package main
import (
"fmt"
"io/ioutil"
"path/filepath"
"regexp"
"strings"
"gopkg.in/yaml.v2"
)
const (
templateFilePattern = ".+\\.yml"
)
// YamlFile represents the structure of a yaml template file
type YamlFile struct {
ID string // Name by which this template should be identified
Description string // The description of this template
Inherit string // ID of the template that should be inherited
Presets map[string]ContentData // Named preset sections
Content map[string]ContentData // The Content.
}
// GetYamlFile reads the yaml file from the provided location.
func GetYamlFile(filename string) (yFile *YamlFile, err error) {
yFile = new(YamlFile)
fileData, err := ioutil.ReadFile(filename)
if err != nil {
return nil, fmt.Errorf("Reading file '%v': %w", filename, err)
}
err = yaml.UnmarshalStrict(fileData, yFile)
if err != nil {
return nil, fmt.Errorf("Parsing file '%v': %w", filename, err)
}
return yFile, nil
}
// GetTemplateFilenamesFromDir takes a directory name as input and returns a list of names
// of all template files within that dir and its subdirectories. All returned paths are
// prefixed with the provided path argument.
func GetTemplateFilenamesFromDir(dirName string) (yamlFilenames []string, err error) {
tmplFileRegex := regexp.MustCompile(templateFilePattern)
files, err := ioutil.ReadDir(dirName)
if err != nil {
return yamlFilenames, err
}
for _, file := range files {
if file.IsDir() {
tmplFilesInSubDir, err := GetTemplateFilenamesFromDir(filepath.Join(dirName, file.Name()))
if err != nil {
return nil, err
}
yamlFilenames = append(yamlFilenames, tmplFilesInSubDir...)
} else if tmplFileRegex.MatchString(strings.ToLower(file.Name())) {
filename := filepath.Join(dirName, file.Name())
yamlFilenames = append(yamlFilenames, filename)
}
}
return yamlFilenames, nil
}
// GetTemplateFilesFromDir takes a directory name as input and returns a list of
// YamlFile objects that hold the contents of all yaml files contained in that
// directory and its subdirectories.
func GetTemplateFilesFromDir(dirName string) (yamlFiles map[string]*YamlFile, err error) {
fileList, err := GetTemplateFilenamesFromDir(dirName)
if err != nil {
return nil, err
}
yamlFiles = make(map[string]*YamlFile, len(fileList))
for _, filename := range fileList {
yFile, err := GetYamlFile(filename)
if err != nil {
return nil, err
}
yamlFiles[filename] = yFile
}
return yamlFiles, nil
}