forked from golang/gddo
/
template.go
503 lines (462 loc) · 12.7 KB
/
template.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
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
// Copyright 2013 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 or at
// https://developers.google.com/open-source/licenses/bsd.
package main
import (
"bytes"
"encoding/base64"
"errors"
"fmt"
godoc "go/doc"
htemp "html/template"
"io"
"net/http"
"net/url"
"path"
"path/filepath"
"reflect"
"regexp"
"sort"
"strings"
ttemp "text/template"
"time"
"github.com/golang/gddo/doc"
"github.com/golang/gddo/gosrc"
"github.com/golang/gddo/httputil"
)
var cacheBusters httputil.CacheBusters
type flashMessage struct {
ID string
Args []string
}
// getFlashMessages retrieves flash messages from the request and clears the flash cookie if needed.
func getFlashMessages(resp http.ResponseWriter, req *http.Request) []flashMessage {
c, err := req.Cookie("flash")
if err == http.ErrNoCookie {
return nil
}
http.SetCookie(resp, &http.Cookie{Name: "flash", Path: "/", MaxAge: -1, Expires: time.Now().Add(-100 * 24 * time.Hour)})
if err != nil {
return nil
}
p, err := base64.URLEncoding.DecodeString(c.Value)
if err != nil {
return nil
}
var messages []flashMessage
for _, s := range strings.Split(string(p), "\000") {
idArgs := strings.Split(s, "\001")
messages = append(messages, flashMessage{ID: idArgs[0], Args: idArgs[1:]})
}
return messages
}
// setFlashMessages sets a cookie with the given flash messages.
func setFlashMessages(resp http.ResponseWriter, messages []flashMessage) {
var buf []byte
for i, message := range messages {
if i > 0 {
buf = append(buf, '\000')
}
buf = append(buf, message.ID...)
for _, arg := range message.Args {
buf = append(buf, '\001')
buf = append(buf, arg...)
}
}
value := base64.URLEncoding.EncodeToString(buf)
http.SetCookie(resp, &http.Cookie{Name: "flash", Value: value, Path: "/"})
}
type tdoc struct {
*doc.Package
allExamples []*texample
}
type texample struct {
ID string
Label string
Example *doc.Example
obj interface{}
}
func newTDoc(pdoc *doc.Package) *tdoc {
return &tdoc{Package: pdoc}
}
func (pdoc *tdoc) SourceLink(pos doc.Pos, text, anchor string) htemp.HTML {
text = htemp.HTMLEscapeString(text)
if pos.Line == 0 || pdoc.LineFmt == "" || pdoc.Files[pos.File].URL == "" {
return htemp.HTML(text)
}
var u string
if anchor != "" && strings.HasPrefix(pdoc.Files[pos.File].URL, "/") {
u = fmt.Sprintf("%s#%s", pdoc.Files[pos.File].URL, anchor)
} else {
u = fmt.Sprintf(pdoc.LineFmt, pdoc.Files[pos.File].URL, pos.Line)
}
u = htemp.HTMLEscapeString(u)
return htemp.HTML(fmt.Sprintf(`<a title="View Source" href="%s">%s</a>`, u, text))
}
func (pdoc *tdoc) PageName() string {
if pdoc.Name != "" && !pdoc.IsCmd {
return pdoc.Name
}
_, name := path.Split(pdoc.ImportPath)
return name
}
func (pdoc *tdoc) addExamples(obj interface{}, export, method string, examples []*doc.Example) {
label := export
id := export
if method != "" {
label += "." + method
id += "-" + method
}
for _, e := range examples {
te := &texample{Label: label, ID: id, Example: e, obj: obj}
if e.Name != "" {
te.Label += " (" + e.Name + ")"
if method == "" {
te.ID += "-"
}
te.ID += "-" + e.Name
}
pdoc.allExamples = append(pdoc.allExamples, te)
}
}
type byExampleID []*texample
func (e byExampleID) Len() int { return len(e) }
func (e byExampleID) Less(i, j int) bool { return e[i].ID < e[j].ID }
func (e byExampleID) Swap(i, j int) { e[i], e[j] = e[j], e[i] }
func (pdoc *tdoc) AllExamples() []*texample {
if pdoc.allExamples != nil {
return pdoc.allExamples
}
pdoc.allExamples = make([]*texample, 0)
pdoc.addExamples(pdoc, "package", "", pdoc.Examples)
for _, f := range pdoc.Funcs {
pdoc.addExamples(f, f.Name, "", f.Examples)
}
for _, t := range pdoc.Types {
pdoc.addExamples(t, t.Name, "", t.Examples)
for _, f := range t.Funcs {
pdoc.addExamples(f, f.Name, "", f.Examples)
}
for _, m := range t.Methods {
if len(m.Examples) > 0 {
pdoc.addExamples(m, t.Name, m.Name, m.Examples)
}
}
}
sort.Sort(byExampleID(pdoc.allExamples))
return pdoc.allExamples
}
func (pdoc *tdoc) ObjExamples(obj interface{}) []*texample {
var examples []*texample
for _, e := range pdoc.allExamples {
if e.obj == obj {
examples = append(examples, e)
}
}
return examples
}
func (pdoc *tdoc) Breadcrumbs(templateName string) htemp.HTML {
if !strings.HasPrefix(pdoc.ImportPath, pdoc.ProjectRoot) {
return ""
}
var buf bytes.Buffer
i := 0
j := len(pdoc.ProjectRoot)
if j == 0 {
j = strings.IndexRune(pdoc.ImportPath, '/')
if j < 0 {
j = len(pdoc.ImportPath)
}
}
for {
if i != 0 {
buf.WriteString(`<span class="text-muted">/</span>`)
}
link := j < len(pdoc.ImportPath) ||
(templateName != "dir.html" && templateName != "cmd.html" && templateName != "pkg.html")
if link {
buf.WriteString(`<a href="`)
buf.WriteString(formatPathFrag(pdoc.ImportPath[:j], ""))
buf.WriteString(`">`)
} else {
buf.WriteString(`<span class="text-muted">`)
}
buf.WriteString(htemp.HTMLEscapeString(pdoc.ImportPath[i:j]))
if link {
buf.WriteString("</a>")
} else {
buf.WriteString("</span>")
}
i = j + 1
if i >= len(pdoc.ImportPath) {
break
}
j = strings.IndexRune(pdoc.ImportPath[i:], '/')
if j < 0 {
j = len(pdoc.ImportPath)
} else {
j += i
}
}
return htemp.HTML(buf.String())
}
func formatPathFrag(path, fragment string) string {
if len(path) > 0 && path[0] != '/' {
path = "/" + path
}
u := url.URL{Path: path, Fragment: fragment}
return u.String()
}
func hostFn(urlStr string) string {
u, err := url.Parse(urlStr)
if err != nil {
return ""
}
return u.Host
}
func mapFn(kvs ...interface{}) (map[string]interface{}, error) {
if len(kvs)%2 != 0 {
return nil, errors.New("map requires even number of arguments")
}
m := make(map[string]interface{})
for i := 0; i < len(kvs); i += 2 {
s, ok := kvs[i].(string)
if !ok {
return nil, errors.New("even args to map must be strings")
}
m[s] = kvs[i+1]
}
return m, nil
}
// relativePathFn formats an import path as HTML.
func relativePathFn(path string, parentPath interface{}) string {
if p, ok := parentPath.(string); ok && p != "" && strings.HasPrefix(path, p) {
path = path[len(p)+1:]
}
return path
}
// importPathFn formats an import with zero width space characters to allow for breaks.
func importPathFn(path string) htemp.HTML {
path = htemp.HTMLEscapeString(path)
if len(path) > 45 {
// Allow long import paths to break following "/"
path = strings.Replace(path, "/", "/​", -1)
}
return htemp.HTML(path)
}
var (
h3Pat = regexp.MustCompile(`<h3 id="([^"]+)">([^<]+)</h3>`)
rfcPat = regexp.MustCompile(`RFC\s+(\d{3,4})`)
packagePat = regexp.MustCompile(`\s+package\s+([-a-z0-9]\S+)`)
)
func replaceAll(src []byte, re *regexp.Regexp, replace func(out, src []byte, m []int) []byte) []byte {
var out []byte
for len(src) > 0 {
m := re.FindSubmatchIndex(src)
if m == nil {
break
}
out = append(out, src[:m[0]]...)
out = replace(out, src, m)
src = src[m[1]:]
}
if out == nil {
return src
}
return append(out, src...)
}
// commentFn formats a source code comment as HTML.
func commentFn(v string) htemp.HTML {
var buf bytes.Buffer
godoc.ToHTML(&buf, v, nil)
p := buf.Bytes()
p = replaceAll(p, h3Pat, func(out, src []byte, m []int) []byte {
out = append(out, `<h4 id="`...)
out = append(out, src[m[2]:m[3]]...)
out = append(out, `">`...)
out = append(out, src[m[4]:m[5]]...)
out = append(out, ` <a class="permalink" href="#`...)
out = append(out, src[m[2]:m[3]]...)
out = append(out, `">¶</a></h4>`...)
return out
})
p = replaceAll(p, rfcPat, func(out, src []byte, m []int) []byte {
out = append(out, `<a href="http://tools.ietf.org/html/rfc`...)
out = append(out, src[m[2]:m[3]]...)
out = append(out, `">`...)
out = append(out, src[m[0]:m[1]]...)
out = append(out, `</a>`...)
return out
})
p = replaceAll(p, packagePat, func(out, src []byte, m []int) []byte {
path := bytes.TrimRight(src[m[2]:m[3]], ".!?:")
if !gosrc.IsValidPath(string(path)) {
return append(out, src[m[0]:m[1]]...)
}
out = append(out, src[m[0]:m[2]]...)
out = append(out, `<a href="/`...)
out = append(out, path...)
out = append(out, `">`...)
out = append(out, path...)
out = append(out, `</a>`...)
out = append(out, src[m[2]+len(path):m[1]]...)
return out
})
return htemp.HTML(p)
}
// commentTextFn formats a source code comment as text.
func commentTextFn(v string) string {
const indent = " "
var buf bytes.Buffer
godoc.ToText(&buf, v, indent, "\t", 80-2*len(indent))
p := buf.Bytes()
return string(p)
}
var period = []byte{'.'}
func codeFn(c doc.Code, typ *doc.Type) htemp.HTML {
var buf bytes.Buffer
last := 0
src := []byte(c.Text)
for _, a := range c.Annotations {
htemp.HTMLEscape(&buf, src[last:a.Pos])
switch a.Kind {
case doc.PackageLinkAnnotation:
buf.WriteString(`<a href="`)
buf.WriteString(formatPathFrag(c.Paths[a.PathIndex], ""))
buf.WriteString(`">`)
htemp.HTMLEscape(&buf, src[a.Pos:a.End])
buf.WriteString(`</a>`)
case doc.LinkAnnotation, doc.BuiltinAnnotation:
var p string
if a.Kind == doc.BuiltinAnnotation {
p = "builtin"
} else if a.PathIndex >= 0 {
p = c.Paths[a.PathIndex]
}
n := src[a.Pos:a.End]
n = n[bytes.LastIndex(n, period)+1:]
buf.WriteString(`<a href="`)
buf.WriteString(formatPathFrag(p, string(n)))
buf.WriteString(`">`)
htemp.HTMLEscape(&buf, src[a.Pos:a.End])
buf.WriteString(`</a>`)
case doc.CommentAnnotation:
buf.WriteString(`<span class="com">`)
htemp.HTMLEscape(&buf, src[a.Pos:a.End])
buf.WriteString(`</span>`)
case doc.AnchorAnnotation:
buf.WriteString(`<span id="`)
if typ != nil {
htemp.HTMLEscape(&buf, []byte(typ.Name))
buf.WriteByte('.')
}
htemp.HTMLEscape(&buf, src[a.Pos:a.End])
buf.WriteString(`">`)
htemp.HTMLEscape(&buf, src[a.Pos:a.End])
buf.WriteString(`</span>`)
default:
htemp.HTMLEscape(&buf, src[a.Pos:a.End])
}
last = int(a.End)
}
htemp.HTMLEscape(&buf, src[last:])
return htemp.HTML(buf.String())
}
var isInterfacePat = regexp.MustCompile(`^type [^ ]+ interface`)
func isInterfaceFn(t *doc.Type) bool {
return isInterfacePat.MatchString(t.Decl.Text)
}
var gaAccount string
func gaAccountFn() string {
return gaAccount
}
func noteTitleFn(s string) string {
return strings.Title(strings.ToLower(s))
}
func htmlCommentFn(s string) htemp.HTML {
return htemp.HTML("<!-- " + s + " -->")
}
var mimeTypes = map[string]string{
".html": htmlMIMEType,
".txt": textMIMEType,
}
func executeTemplate(resp http.ResponseWriter, name string, status int, header http.Header, data interface{}) error {
for k, v := range header {
resp.Header()[k] = v
}
mimeType, ok := mimeTypes[path.Ext(name)]
if !ok {
mimeType = textMIMEType
}
resp.Header().Set("Content-Type", mimeType)
t := templates[name]
if t == nil {
return fmt.Errorf("template %s not found", name)
}
resp.WriteHeader(status)
if status == http.StatusNotModified {
return nil
}
return t.Execute(resp, data)
}
var templates = map[string]interface {
Execute(io.Writer, interface{}) error
}{}
func joinTemplateDir(base string, files []string) []string {
result := make([]string, len(files))
for i := range files {
result[i] = filepath.Join(base, "templates", files[i])
}
return result
}
func parseHTMLTemplates(sets [][]string) error {
for _, set := range sets {
templateName := set[0]
t := htemp.New("")
t.Funcs(htemp.FuncMap{
"code": codeFn,
"comment": commentFn,
"equal": reflect.DeepEqual,
"gaAccount": gaAccountFn,
"host": hostFn,
"htmlComment": htmlCommentFn,
"importPath": importPathFn,
"isInterface": isInterfaceFn,
"isValidImportPath": gosrc.IsValidPath,
"map": mapFn,
"noteTitle": noteTitleFn,
"relativePath": relativePathFn,
"sidebarEnabled": func() bool { return *sidebarEnabled },
"staticPath": func(p string) string { return cacheBusters.AppendQueryParam(p, "v") },
"templateName": func() string { return templateName },
})
if _, err := t.ParseFiles(joinTemplateDir(*assetsDir, set)...); err != nil {
return err
}
t = t.Lookup("ROOT")
if t == nil {
return fmt.Errorf("ROOT template not found in %v", set)
}
templates[set[0]] = t
}
return nil
}
func parseTextTemplates(sets [][]string) error {
for _, set := range sets {
t := ttemp.New("")
t.Funcs(ttemp.FuncMap{
"comment": commentTextFn,
})
if _, err := t.ParseFiles(joinTemplateDir(*assetsDir, set)...); err != nil {
return err
}
t = t.Lookup("ROOT")
if t == nil {
return fmt.Errorf("ROOT template not found in %v", set)
}
templates[set[0]] = t
}
return nil
}