-
Notifications
You must be signed in to change notification settings - Fork 41
/
globals.go
51 lines (48 loc) · 1.16 KB
/
globals.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
package soy
import (
"bufio"
"fmt"
"io"
"strings"
"github.com/robfig/soy/data"
"github.com/robfig/soy/parse"
"github.com/robfig/soy/soyhtml"
)
// ParseGlobals parses the given input, expecting the form:
// <global_name> = <primitive_data>
//
// Furthermore:
// - Empty lines and lines beginning with '//' are ignored.
// - <primitive_data> must be a valid template expression literal for a primitive
// type (null, boolean, integer, float, or string)
func ParseGlobals(input io.Reader) (data.Map, error) {
var globals = make(data.Map)
var scanner = bufio.NewScanner(input)
for scanner.Scan() {
var line = scanner.Text()
if len(line) == 0 || strings.HasPrefix(line, "//") {
continue
}
var eq = strings.Index(line, "=")
if eq == -1 {
return nil, fmt.Errorf("no equals on line: %q", line)
}
var (
name = strings.TrimSpace(line[:eq])
expr = strings.TrimSpace(line[eq+1:])
)
var node, err = parse.Expr(expr)
if err != nil {
return nil, err
}
exprValue, err := soyhtml.EvalExpr(node)
if err != nil {
return nil, err
}
globals[name] = exprValue
}
if err := scanner.Err(); err != nil {
return nil, err
}
return globals, nil
}