-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuiltins.go
77 lines (68 loc) · 1.71 KB
/
builtins.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
package mktree
import (
"fmt"
"io/ioutil"
"os"
"os/user"
"strconv"
"time"
)
func builtins(i *Interpreter) []Option {
return []Option{
WithTemplateFunction("FileExists", newFileExistsBuiltin()),
WithTemplateFunction("FileContents", newFileContentsBuiltin()),
WithTemplateFunction("Now", newNowBuiltin()),
WithTemplateFunction("Year", newYearBuiltin()),
WithTemplateFunction("User", newUserBuiltin()),
WithTemplateFunction("Var", newVarBuiltin(i.Vars)),
}
}
func newFileContentsBuiltin() func(string) (string, error) {
return func(filename string) (string, error) {
contents, err := ioutil.ReadFile(filename)
return string(contents), err
}
}
func newFileExistsBuiltin() func(string) bool {
return func(filename string) bool {
stat, err := os.Stat(filename)
if err != nil {
if !os.IsNotExist(err) {
warn("unable to stat %s: %w", filename, err)
}
return false
}
return !stat.IsDir()
}
}
func newNowBuiltin() func() string {
t := time.Now()
now := t.Format(time.RFC3339)
return func() string { return now }
}
func newUserBuiltin() func() string {
var u string
if usr, err := user.Current(); err != nil {
warn("unable to get current user")
} else {
u = usr.Username
if u == "" {
u = usr.Name
}
}
return func() string { return u }
}
func newVarBuiltin(vars map[string]string) func(string) (string, error) {
return func(varname string) (string, error) {
if v, ok := vars[varname]; ok {
return v, nil
}
return "", fmt.Errorf("variable %q is undefined", varname)
}
}
func newYearBuiltin() func() string {
return func() string { return strconv.Itoa(time.Now().Year()) }
}
func warn(format string, args ...interface{}) {
fmt.Fprintf(os.Stderr, "warning: "+format, args...)
}