forked from 99designs/smartling
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathcompile_format.go
74 lines (60 loc) · 1.37 KB
/
compile_format.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
package main
import (
"path/filepath"
"strings"
"sync"
"text/template"
"github.com/reconquest/hierr-go"
)
var (
// because we can have specific formats for different file types defined
// in config file, we need to cache templates to prevent overhead in
// runtime
compiledFormatsCache = struct {
sync.Mutex
contents map[string]*Format
}{
contents: map[string]*Format{},
}
)
func compileFormat(definition string) (*Format, error) {
compiledFormatsCache.Lock()
defer compiledFormatsCache.Unlock()
if format, ok := compiledFormatsCache.contents[definition]; ok {
return format, nil
}
definition = strings.NewReplacer(
`\n`, "\n",
`\t`, "\t",
).Replace(definition)
funcs := template.FuncMap{
"name": func(path string) string {
return strings.TrimSuffix(path, filepath.Ext(path))
},
"ext": func(path string) string {
return filepath.Ext(path)
},
}
var (
format Format
err error
)
format.Source = definition
format.Template, err = template.New("format").Funcs(funcs).Option(
"missingkey=error",
).Parse(
definition,
)
if err != nil {
return nil, NewError(
hierr.Errorf(
err,
"failed to compile format template",
),
"Check template syntax accordingly to text/template "+
"documentation:\n\thttps://golang.org/pkg/text/template/",
)
}
compiledFormatsCache.contents[definition] = &format
return &format, nil
}