File: func.go

package info (click to toggle)
golang-rsc-tmplfunc 0.0.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 204 kB
  • sloc: makefile: 2
file content (205 lines) | stat: -rw-r--r-- 5,240 bytes parent folder | download
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package tmplfunc

import (
	"bytes"
	"fmt"
	"reflect"
	"regexp"
	"strings"

	"rsc.io/tmplfunc/internal/parse"

	htmltemplate "html/template"
	texttemplate "text/template"
)

var validNameRE = regexp.MustCompile(`\A[_\pL][_\pL\p{Nd}]*\z`)
var validArgNameRE = regexp.MustCompile(`\A[_\pL][_\pL\p{Nd}]*(\.\.\.|\?)?\z`)

func funcs(t Template, names, texts []string) error {
	var leftDelim, rightDelim string
	switch t := t.(type) {
	case nil:
		return fmt.Errorf("tmplfunc: nil Template")
	default:
		return fmt.Errorf("tmplfunc: non-template type %T", t)
	case *texttemplate.Template:
		leftDelim = reflect.ValueOf(t).Elem().FieldByName("leftDelim").String()
		rightDelim = reflect.ValueOf(t).Elem().FieldByName("rightDelim").String()
	case *htmltemplate.Template:
		leftDelim = reflect.ValueOf(t).Elem().FieldByName("text").Elem().FieldByName("leftDelim").String()
		rightDelim = reflect.ValueOf(t).Elem().FieldByName("text").Elem().FieldByName("rightDelim").String()
	}

	trees := make(map[string]*parse.Tree)
	for i, text := range texts {
		t := parse.New(names[i], nil)
		t.Mode = parse.SkipFuncCheck
		_, err := t.Parse(text, leftDelim, rightDelim, trees)
		if err != nil {
			return err
		}
	}

	// Install functions for named templates as appropriate.
	funcs := make(map[string]interface{})
	for name := range trees {
		if err := addFunc(t, name, funcs); err != nil {
			return err
		}
	}

	switch t := t.(type) {
	case *texttemplate.Template:
		t.Funcs(funcs)
	case *htmltemplate.Template:
		t.Funcs(funcs)
	}

	return nil
}

// Funcs installs functions for all the templates in the set containing t.
// After using t.Clone it is necessary to call Funcs on the result to arrange
// for the functions to invoke the cloned templates and not the originals.
func Funcs(t Template) error {
	funcs := make(map[string]interface{})
	switch t := t.(type) {
	case *texttemplate.Template:
		for _, t1 := range t.Templates() {
			if err := addFunc(t, t1.Name(), funcs); err != nil {
				return err
			}
		}
		t.Funcs(funcs)
	case *htmltemplate.Template:
		for _, t1 := range t.Templates() {
			if err := addFunc(t, t1.Name(), funcs); err != nil {
				return err
			}
		}
		t.Funcs(funcs)
	}
	return nil
}

func addFunc(t Template, name string, funcs map[string]interface{}) error {
	fn, bundle, err := bundler(name)
	if err != nil {
		return err
	}
	if fn == "" {
		return nil
	}
	switch t := t.(type) {
	case *texttemplate.Template:
		funcs[fn] = func(args ...interface{}) (string, error) {
			t := t.Lookup(name)
			if t == nil {
				return "", fmt.Errorf("lost template %q", name)
			}
			arg, err := bundle(args)
			if err != nil {
				return "", err
			}
			var buf bytes.Buffer
			err = t.Execute(&buf, arg)
			if err != nil {
				return "", err
			}
			return buf.String(), nil
		}
	case *htmltemplate.Template:
		funcs[fn] = func(args ...interface{}) (htmltemplate.HTML, error) {
			t := t.Lookup(name)
			if t == nil {
				return "", fmt.Errorf("lost template %q", name)
			}
			arg, err := bundle(args)
			if err != nil {
				return "", err
			}
			var buf bytes.Buffer
			err = t.Execute(&buf, arg)
			if err != nil {
				return "", err
			}
			return htmltemplate.HTML(buf.String()), nil
		}
	}
	return nil
}

func bundler(name string) (fn string, bundle func(args []interface{}) (interface{}, error), err error) {
	f := strings.Fields(name)
	if len(f) == 0 || !validNameRE.MatchString(f[0]) {
		return "", nil, nil
	}

	fn = f[0]
	if len(f) == 1 {
		bundle = func(args []interface{}) (interface{}, error) {
			if len(args) == 0 {
				return nil, nil
			}
			if len(args) == 1 {
				return args[0], nil
			}
			return nil, fmt.Errorf("too many arguments in call to template %s", fn)
		}
	} else {
		sawQ := false
		for i, argName := range f[1:] {
			if !validArgNameRE.MatchString(argName) {
				return "", nil, fmt.Errorf("invalid template name %q: invalid argument name %s", name, argName)
			}
			if strings.HasSuffix(argName, "...") {
				if i != len(f)-2 {
					return "", nil, fmt.Errorf("invalid template name %q: %s is not last argument", name, argName)
				}
				break
			}
			if strings.HasSuffix(argName, "?") {
				sawQ = true
				continue
			}
			if sawQ {
				return "", nil, fmt.Errorf("invalid template name %q: required %s after optional %s", name, argName, f[i])
			}
		}

		bundle = func(args []interface{}) (interface{}, error) {
			m := make(map[string]interface{})
			for _, argName := range f[1:] {
				if strings.HasSuffix(argName, "...") {
					m[strings.TrimSuffix(argName, "...")] = args
					args = nil
					break
				}
				if strings.HasSuffix(argName, "?") {
					prefix := strings.TrimSuffix(argName, "?")
					if len(args) == 0 {
						m[prefix] = nil
					} else {
						m[prefix], args = args[0], args[1:]
					}
					continue
				}
				if len(args) == 0 {
					return nil, fmt.Errorf("too few arguments in call to template %s", fn)
				}
				m[argName], args = args[0], args[1:]
			}
			if len(args) > 0 {
				return nil, fmt.Errorf("too many arguments in call to template %s", fn)
			}
			return m, nil
		}
	}

	return fn, bundle, nil
}