-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpattern_loader.go
103 lines (79 loc) · 2.41 KB
/
pattern_loader.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
96
97
98
99
100
101
102
103
package zmdocs
import (
"bytes"
"errors"
"fmt"
"path/filepath"
"regexp"
"text/template"
)
// Matched file with the file path and the pattern matches
type PatternMatch struct {
Path string
PathMatches [][]string
}
// Finds files that match a glob (source) and finds pattern matches on each file
func GetPatternMatches(source, pattern string) ([]*PatternMatch, error) {
if source == "" {
return nil, errors.New("source glob is required")
}
if pattern == "" {
return nil, errors.New("pattern is required")
}
rgx, err := regexp.Compile(pattern)
if err != nil {
return nil, fmt.Errorf("unable to compile regex pattern: %s", pattern)
}
matches, err := filepath.Glob(source)
if err != nil {
return nil, fmt.Errorf("unable to find files matching glob (%s): %s", source, err.Error())
}
mLen := len(matches)
if mLen == 0 {
return nil, fmt.Errorf("no files were found for glob (%s)", source)
}
pms := make([]*PatternMatch, mLen, mLen)
for i, path := range matches {
pathMatches := rgx.FindAllStringSubmatch(path, -1)
pm := PatternMatch{
Path: path,
PathMatches: pathMatches,
}
pms[i] = &pm
}
return pms, nil
}
// Constructs a File instance from a pattern match
func GetFileForPatternMatch(ap *PagePattern, pm *PatternMatch) (*File, error) {
if ap == nil {
return nil, errors.New("page pattern object cannot be nil")
}
if pm == nil {
return nil, errors.New("pattern match cannot be nil")
}
file := File{}
file.EditOnGithub = ap.EditOnGithub
file.AddToMenu = ap.AddToMenu
file.MenuGroup = ap.MenuGroup
file.Template = ap.Template
file.SourceFile = pm.Path
var err error
if file.Name, err = stringFromTemplate(ap.Name, pm); err != nil {
return nil, fmt.Errorf("unable to parse name template: \n\t%s", err.Error())
} else if file.Path, err = stringFromTemplate(ap.Path, pm); err != nil {
return nil, fmt.Errorf("unable to parse path template: \n\t%s", err.Error())
}
return &file, nil
}
// Utility function to generate a string from a provided Go template
func stringFromTemplate(t string, pm *PatternMatch) (string, error) {
if tmpl, err := template.New("").Parse(t); err != nil {
return "", fmt.Errorf("unable to parse template: \n\t%s", err.Error())
} else {
buff := bytes.NewBuffer(make([]byte, 0))
if err := tmpl.Execute(buff, pm); err != nil {
return "", fmt.Errorf("unable to execute template: \n\t%s", err.Error())
}
return buff.String(), nil
}
}