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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
|
// Copyright 2019 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tplimpl
import (
"fmt"
"html/template"
"strings"
texttemplate "text/template"
"text/template/parse"
"github.com/gohugoio/hugo/hugofs"
"github.com/gohugoio/hugo/tpl/tplimpl/embedded"
"github.com/pkg/errors"
"github.com/eknkc/amber"
"os"
"github.com/gohugoio/hugo/output"
"path/filepath"
"sync"
"github.com/gohugoio/hugo/deps"
"github.com/gohugoio/hugo/helpers"
"github.com/gohugoio/hugo/tpl"
"github.com/spf13/afero"
)
const (
textTmplNamePrefix = "_text/"
)
var (
_ tpl.TemplateHandler = (*templateHandler)(nil)
_ tpl.TemplateDebugger = (*templateHandler)(nil)
_ tpl.TemplateFuncsGetter = (*templateHandler)(nil)
_ tpl.TemplateTestMocker = (*templateHandler)(nil)
_ tpl.TemplateFinder = (*htmlTemplates)(nil)
_ tpl.TemplateFinder = (*textTemplates)(nil)
_ templateLoader = (*htmlTemplates)(nil)
_ templateLoader = (*textTemplates)(nil)
_ templateFuncsterTemplater = (*htmlTemplates)(nil)
_ templateFuncsterTemplater = (*textTemplates)(nil)
)
// Protecting global map access (Amber)
var amberMu sync.Mutex
type templateErr struct {
name string
err error
}
type templateLoader interface {
handleMaster(name, overlayFilename, masterFilename string, onMissing func(filename string) (templateInfo, error)) error
addTemplate(name, tpl string) (*templateContext, error)
addLateTemplate(name, tpl string) error
}
type templateFuncsterTemplater interface {
templateFuncsterSetter
tpl.TemplateFinder
setFuncs(funcMap map[string]interface{})
}
type templateFuncsterSetter interface {
setTemplateFuncster(f *templateFuncster)
}
// templateHandler holds the templates in play.
// It implements the templateLoader and tpl.TemplateHandler interfaces.
type templateHandler struct {
mu sync.Mutex
// shortcodes maps shortcode name to template variants
// (language, output format etc.) of that shortcode.
shortcodes map[string]*shortcodeTemplates
// templateInfo maps template name to some additional information about that template.
// Note that for shortcodes that same information is embedded in the
// shortcodeTemplates type.
templateInfo map[string]tpl.Info
// text holds all the pure text templates.
text *textTemplates
html *htmlTemplates
amberFuncMap template.FuncMap
errors []*templateErr
// This is the filesystem to load the templates from. All the templates are
// stored in the root of this filesystem.
layoutsFs afero.Fs
*deps.Deps
}
const (
shortcodesPathPrefix = "shortcodes/"
internalPathPrefix = "_internal/"
)
// resolves _internal/shortcodes/param.html => param.html etc.
func templateBaseName(typ templateType, name string) string {
name = strings.TrimPrefix(name, internalPathPrefix)
switch typ {
case templateShortcode:
return strings.TrimPrefix(name, shortcodesPathPrefix)
default:
panic("not implemented")
}
}
func (t *templateHandler) addShortcodeVariant(name string, info tpl.Info, templ tpl.Template) {
base := templateBaseName(templateShortcode, name)
shortcodename, variants := templateNameAndVariants(base)
templs, found := t.shortcodes[shortcodename]
if !found {
templs = &shortcodeTemplates{}
t.shortcodes[shortcodename] = templs
}
sv := shortcodeVariant{variants: variants, info: info, templ: templ}
i := templs.indexOf(variants)
if i != -1 {
// Only replace if it's an override of an internal template.
if !isInternal(name) {
templs.variants[i] = sv
}
} else {
templs.variants = append(templs.variants, sv)
}
}
func (t *templateHandler) wrapTextTemplate(tt *textTemplate) tpl.TemplateParseFinder {
return struct {
tpl.TemplateParser
tpl.TemplateLookup
tpl.TemplateLookupVariant
}{
tt,
tt,
new(nopLookupVariant),
}
}
type nopLookupVariant int
func (l nopLookupVariant) LookupVariant(name string, variants tpl.TemplateVariants) (tpl.Template, bool, bool) {
return nil, false, false
}
func (t *templateHandler) Debug() {
fmt.Println("HTML templates:\n", t.html.t.DefinedTemplates())
fmt.Println("\n\nText templates:\n", t.text.t.DefinedTemplates())
}
// Lookup tries to find a template with the given name in both template
// collections: First HTML, then the plain text template collection.
func (t *templateHandler) Lookup(name string) (tpl.Template, bool) {
if strings.HasPrefix(name, textTmplNamePrefix) {
// The caller has explicitly asked for a text template, so only look
// in the text template collection.
// The templates are stored without the prefix identificator.
name = strings.TrimPrefix(name, textTmplNamePrefix)
return t.applyTemplateInfo(t.text.Lookup(name))
}
// Look in both
if te, found := t.html.Lookup(name); found {
return t.applyTemplateInfo(te, true)
}
return t.applyTemplateInfo(t.text.Lookup(name))
}
func (t *templateHandler) applyTemplateInfo(templ tpl.Template, found bool) (tpl.Template, bool) {
if adapter, ok := templ.(*tpl.TemplateAdapter); ok {
if adapter.Info.IsZero() {
if info, found := t.templateInfo[templ.Name()]; found {
adapter.Info = info
}
}
}
return templ, found
}
// This currently only applies to shortcodes and what we get here is the
// shortcode name.
func (t *templateHandler) LookupVariant(name string, variants tpl.TemplateVariants) (tpl.Template, bool, bool) {
name = templateBaseName(templateShortcode, name)
s, found := t.shortcodes[name]
if !found {
return nil, false, false
}
sv, found := s.fromVariants(variants)
if !found {
return nil, false, false
}
more := len(s.variants) > 1
return &tpl.TemplateAdapter{
Template: sv.templ,
Info: sv.info,
Metrics: t.Deps.Metrics,
Fs: t.layoutsFs,
NameBaseTemplateName: t.html.nameBaseTemplateName}, true, more
}
func (t *textTemplates) LookupVariant(name string, variants tpl.TemplateVariants) (tpl.Template, bool, bool) {
return t.handler.LookupVariant(name, variants)
}
func (t *htmlTemplates) LookupVariant(name string, variants tpl.TemplateVariants) (tpl.Template, bool, bool) {
return t.handler.LookupVariant(name, variants)
}
func (t *templateHandler) lookupTemplate(in interface{}) tpl.Template {
switch templ := in.(type) {
case *texttemplate.Template:
return t.text.lookup(templ.Name())
case *template.Template:
return t.html.lookup(templ.Name())
}
panic(fmt.Sprintf("%T is not a template", in))
}
func (t *templateHandler) setFuncMapInTemplate(in interface{}, funcs map[string]interface{}) {
switch templ := in.(type) {
case *texttemplate.Template:
templ.Funcs(funcs)
return
case *template.Template:
templ.Funcs(funcs)
return
}
panic(fmt.Sprintf("%T is not a template", in))
}
func (t *templateHandler) clone(d *deps.Deps) *templateHandler {
c := &templateHandler{
Deps: d,
layoutsFs: d.BaseFs.Layouts.Fs,
shortcodes: make(map[string]*shortcodeTemplates),
templateInfo: t.templateInfo,
html: &htmlTemplates{t: template.Must(t.html.t.Clone()), overlays: make(map[string]*template.Template), templatesCommon: t.html.templatesCommon},
text: &textTemplates{
textTemplate: &textTemplate{t: texttemplate.Must(t.text.t.Clone())},
standalone: &textTemplate{t: texttemplate.New("")},
overlays: make(map[string]*texttemplate.Template), templatesCommon: t.text.templatesCommon},
errors: make([]*templateErr, 0),
}
for k, v := range t.shortcodes {
other := *v
variantsc := make([]shortcodeVariant, len(v.variants))
for i, variant := range v.variants {
variantsc[i] = shortcodeVariant{
info: variant.info,
variants: variant.variants,
templ: c.lookupTemplate(variant.templ),
}
}
other.variants = variantsc
c.shortcodes[k] = &other
}
d.Tmpl = c
d.TextTmpl = c.wrapTextTemplate(c.text.standalone)
c.initFuncs()
for k, v := range t.html.overlays {
vc := template.Must(v.Clone())
// The extra lookup is a workaround, see
// * https://github.com/golang/go/issues/16101
// * https://github.com/gohugoio/hugo/issues/2549
vc = vc.Lookup(vc.Name())
vc.Funcs(c.html.funcster.funcMap)
c.html.overlays[k] = vc
}
for k, v := range t.text.overlays {
vc := texttemplate.Must(v.Clone())
vc = vc.Lookup(vc.Name())
vc.Funcs(texttemplate.FuncMap(c.text.funcster.funcMap))
c.text.overlays[k] = vc
}
return c
}
func newTemplateAdapter(deps *deps.Deps) *templateHandler {
common := &templatesCommon{
nameBaseTemplateName: make(map[string]string),
transformNotFound: make(map[string]bool),
}
htmlT := &htmlTemplates{
t: template.New(""),
overlays: make(map[string]*template.Template),
templatesCommon: common,
}
textT := &textTemplates{
textTemplate: &textTemplate{t: texttemplate.New("")},
standalone: &textTemplate{t: texttemplate.New("")},
overlays: make(map[string]*texttemplate.Template),
templatesCommon: common,
}
h := &templateHandler{
Deps: deps,
layoutsFs: deps.BaseFs.Layouts.Fs,
shortcodes: make(map[string]*shortcodeTemplates),
templateInfo: make(map[string]tpl.Info),
html: htmlT,
text: textT,
errors: make([]*templateErr, 0),
}
common.handler = h
return h
}
// Shared by both HTML and text templates.
type templatesCommon struct {
handler *templateHandler
funcster *templateFuncster
// Used to get proper filenames in errors
nameBaseTemplateName map[string]string
// Holds names of the templates not found during the first AST transformation
// pass.
transformNotFound map[string]bool
}
type htmlTemplates struct {
mu sync.RWMutex
*templatesCommon
t *template.Template
// This looks, and is, strange.
// The clone is used by non-renderable content pages, and these need to be
// re-parsed on content change, and to avoid the
// "cannot Parse after Execute" error, we need to re-clone it from the original clone.
clone *template.Template
cloneClone *template.Template
// a separate storage for the overlays created from cloned master templates.
// note: No mutex protection, so we add these in one Go routine, then just read.
overlays map[string]*template.Template
}
func (t *htmlTemplates) setTemplateFuncster(f *templateFuncster) {
t.funcster = f
}
func (t *htmlTemplates) Lookup(name string) (tpl.Template, bool) {
templ := t.lookup(name)
if templ == nil {
return nil, false
}
return &tpl.TemplateAdapter{Template: templ, Metrics: t.funcster.Deps.Metrics, Fs: t.handler.layoutsFs, NameBaseTemplateName: t.nameBaseTemplateName}, true
}
func (t *htmlTemplates) lookup(name string) *template.Template {
t.mu.RLock()
defer t.mu.RUnlock()
// Need to check in the overlay registry first as it will also be found below.
if t.overlays != nil {
if templ, ok := t.overlays[name]; ok {
return templ
}
}
if templ := t.t.Lookup(name); templ != nil {
return templ
}
if t.clone != nil {
return t.clone.Lookup(name)
}
return nil
}
func (t *textTemplates) setTemplateFuncster(f *templateFuncster) {
t.funcster = f
}
type textTemplates struct {
*templatesCommon
*textTemplate
standalone *textTemplate
clone *texttemplate.Template
cloneClone *texttemplate.Template
overlays map[string]*texttemplate.Template
}
func (t *textTemplates) Lookup(name string) (tpl.Template, bool) {
templ := t.lookup(name)
if templ == nil {
return nil, false
}
return &tpl.TemplateAdapter{Template: templ, Metrics: t.funcster.Deps.Metrics, Fs: t.handler.layoutsFs, NameBaseTemplateName: t.nameBaseTemplateName}, true
}
func (t *textTemplates) lookup(name string) *texttemplate.Template {
// Need to check in the overlay registry first as it will also be found below.
if t.overlays != nil {
if templ, ok := t.overlays[name]; ok {
return templ
}
}
if templ := t.t.Lookup(name); templ != nil {
return templ
}
if t.clone != nil {
return t.clone.Lookup(name)
}
return nil
}
func (t *templateHandler) setFuncs(funcMap map[string]interface{}) {
t.html.setFuncs(funcMap)
t.text.setFuncs(funcMap)
t.setFuncMapInTemplate(t.text.standalone.t, funcMap)
}
// SetFuncs replaces the funcs in the func maps with new definitions.
// This is only used in tests.
func (t *templateHandler) SetFuncs(funcMap map[string]interface{}) {
t.setFuncs(funcMap)
}
func (t *templateHandler) GetFuncs() map[string]interface{} {
return t.html.funcster.funcMap
}
func (t *htmlTemplates) setFuncs(funcMap map[string]interface{}) {
t.t.Funcs(funcMap)
}
func (t *textTemplates) setFuncs(funcMap map[string]interface{}) {
t.t.Funcs(funcMap)
}
// LoadTemplates loads the templates from the layouts filesystem.
// A prefix can be given to indicate a template namespace to load the templates
// into, i.e. "_internal" etc.
func (t *templateHandler) LoadTemplates(prefix string) error {
return t.loadTemplates(prefix)
}
func (t *htmlTemplates) addTemplateIn(tt *template.Template, name, tpl string) (*templateContext, error) {
t.mu.Lock()
defer t.mu.Unlock()
templ, err := tt.New(name).Parse(tpl)
if err != nil {
return nil, err
}
typ := resolveTemplateType(name)
c, err := applyTemplateTransformersToHMLTTemplate(typ, templ)
if err != nil {
return nil, err
}
for k := range c.notFound {
t.transformNotFound[k] = true
}
if typ == templateShortcode {
t.handler.addShortcodeVariant(name, c.Info, templ)
} else {
t.handler.templateInfo[name] = c.Info
}
return c, nil
}
func (t *htmlTemplates) addTemplate(name, tpl string) (*templateContext, error) {
return t.addTemplateIn(t.t, name, tpl)
}
func (t *htmlTemplates) addLateTemplate(name, tpl string) error {
_, err := t.addTemplateIn(t.clone, name, tpl)
return err
}
type textTemplate struct {
mu sync.RWMutex
t *texttemplate.Template
}
func (t *textTemplate) Parse(name, tpl string) (tpl.Template, error) {
return t.parseIn(t.t, name, tpl)
}
func (t *textTemplate) Lookup(name string) (tpl.Template, bool) {
t.mu.RLock()
defer t.mu.RUnlock()
tpl := t.t.Lookup(name)
return tpl, tpl != nil
}
func (t *textTemplate) parseIn(tt *texttemplate.Template, name, tpl string) (*texttemplate.Template, error) {
t.mu.Lock()
defer t.mu.Unlock()
templ, err := tt.New(name).Parse(tpl)
if err != nil {
return nil, err
}
if _, err := applyTemplateTransformersToTextTemplate(templateUndefined, templ); err != nil {
return nil, err
}
return templ, nil
}
func (t *textTemplates) addTemplateIn(tt *texttemplate.Template, name, tpl string) (*templateContext, error) {
name = strings.TrimPrefix(name, textTmplNamePrefix)
templ, err := t.parseIn(tt, name, tpl)
if err != nil {
return nil, err
}
typ := resolveTemplateType(name)
c, err := applyTemplateTransformersToTextTemplate(typ, templ)
if err != nil {
return nil, err
}
for k := range c.notFound {
t.transformNotFound[k] = true
}
if typ == templateShortcode {
t.handler.addShortcodeVariant(name, c.Info, templ)
} else {
t.handler.templateInfo[name] = c.Info
}
return c, nil
}
func (t *textTemplates) addTemplate(name, tpl string) (*templateContext, error) {
return t.addTemplateIn(t.t, name, tpl)
}
func (t *textTemplates) addLateTemplate(name, tpl string) error {
_, err := t.addTemplateIn(t.clone, name, tpl)
return err
}
func (t *templateHandler) addTemplate(name, tpl string) error {
return t.AddTemplate(name, tpl)
}
func (t *templateHandler) postTransform() error {
if len(t.html.transformNotFound) == 0 && len(t.text.transformNotFound) == 0 {
return nil
}
defer func() {
t.text.transformNotFound = make(map[string]bool)
t.html.transformNotFound = make(map[string]bool)
}()
for _, s := range []struct {
lookup func(name string) *parse.Tree
transformNotFound map[string]bool
}{
// html templates
{func(name string) *parse.Tree {
templ := t.html.lookup(name)
if templ == nil {
return nil
}
return templ.Tree
}, t.html.transformNotFound},
// text templates
{func(name string) *parse.Tree {
templT := t.text.lookup(name)
if templT == nil {
return nil
}
return templT.Tree
}, t.text.transformNotFound},
} {
for name := range s.transformNotFound {
templ := s.lookup(name)
if templ != nil {
_, err := applyTemplateTransformers(templateUndefined, templ, s.lookup)
if err != nil {
return err
}
}
}
}
return nil
}
func (t *templateHandler) addLateTemplate(name, tpl string) error {
return t.AddLateTemplate(name, tpl)
}
// AddLateTemplate is used to add a template late, i.e. after the
// regular templates have started its execution.
func (t *templateHandler) AddLateTemplate(name, tpl string) error {
h := t.getTemplateHandler(name)
if err := h.addLateTemplate(name, tpl); err != nil {
return err
}
return nil
}
// AddTemplate parses and adds a template to the collection.
// Templates with name prefixed with "_text" will be handled as plain
// text templates.
// TODO(bep) clean up these addTemplate variants
func (t *templateHandler) AddTemplate(name, tpl string) error {
h := t.getTemplateHandler(name)
_, err := h.addTemplate(name, tpl)
if err != nil {
return err
}
return nil
}
// MarkReady marks the templates as "ready for execution". No changes allowed
// after this is set.
// TODO(bep) if this proves to be resource heavy, we could detect
// earlier if we really need this, or make it lazy.
func (t *templateHandler) MarkReady() error {
if err := t.postTransform(); err != nil {
return err
}
if t.html.clone == nil {
t.html.clone = template.Must(t.html.t.Clone())
t.html.cloneClone = template.Must(t.html.clone.Clone())
}
if t.text.clone == nil {
t.text.clone = texttemplate.Must(t.text.t.Clone())
t.text.cloneClone = texttemplate.Must(t.text.clone.Clone())
}
return nil
}
// RebuildClone rebuilds the cloned templates. Used for live-reloads.
func (t *templateHandler) RebuildClone() {
if t.html != nil && t.html.cloneClone != nil {
t.html.clone = template.Must(t.html.cloneClone.Clone())
}
if t.text != nil && t.text.cloneClone != nil {
t.text.clone = texttemplate.Must(t.text.cloneClone.Clone())
}
}
func (t *templateHandler) loadTemplates(prefix string) error {
walker := func(path string, fi hugofs.FileMetaInfo, err error) error {
if err != nil || fi.IsDir() {
return err
}
if isDotFile(path) || isBackupFile(path) || isBaseTemplate(path) {
return nil
}
workingDir := t.PathSpec.WorkingDir
descriptor := output.TemplateLookupDescriptor{
WorkingDir: workingDir,
RelPath: path,
Prefix: prefix,
OutputFormats: t.OutputFormatsConfig,
FileExists: func(filename string) (bool, error) {
return helpers.Exists(filename, t.Layouts.Fs)
},
ContainsAny: func(filename string, subslices [][]byte) (bool, error) {
return helpers.FileContainsAny(filename, subslices, t.Layouts.Fs)
},
}
tplID, err := output.CreateTemplateNames(descriptor)
if err != nil {
t.Log.ERROR.Printf("Failed to resolve template in path %q: %s", path, err)
return nil
}
if err := t.addTemplateFile(tplID.Name, tplID.MasterFilename, tplID.OverlayFilename); err != nil {
return err
}
return nil
}
if err := helpers.SymbolicWalk(t.Layouts.Fs, "", walker); err != nil {
if !os.IsNotExist(err) {
return err
}
return nil
}
return nil
}
func (t *templateHandler) initFuncs() {
// Both template types will get their own funcster instance, which
// in the current case contains the same set of funcs.
funcMap := createFuncMap(t.Deps)
for _, funcsterHolder := range []templateFuncsterSetter{t.html, t.text} {
funcster := newTemplateFuncster(t.Deps)
// The URL funcs in the funcMap is somewhat language dependent,
// so we need to wait until the language and site config is loaded.
funcster.initFuncMap(funcMap)
funcsterHolder.setTemplateFuncster(funcster)
}
for _, v := range t.shortcodes {
for _, variant := range v.variants {
t.setFuncMapInTemplate(variant.templ, funcMap)
}
}
// Amber is HTML only.
t.amberFuncMap = template.FuncMap{}
amberMu.Lock()
for k, v := range amber.FuncMap {
t.amberFuncMap[k] = v
}
for k, v := range t.html.funcster.funcMap {
t.amberFuncMap[k] = v
// Hacky, but we need to make sure that the func names are in the global map.
amber.FuncMap[k] = func() string {
panic("should never be invoked")
}
}
amberMu.Unlock()
}
func (t *templateHandler) getTemplateHandler(name string) templateLoader {
if strings.HasPrefix(name, textTmplNamePrefix) {
return t.text
}
return t.html
}
func (t *templateHandler) handleMaster(name, overlayFilename, masterFilename string, onMissing func(filename string) (templateInfo, error)) error {
h := t.getTemplateHandler(name)
return h.handleMaster(name, overlayFilename, masterFilename, onMissing)
}
func (t *htmlTemplates) handleMaster(name, overlayFilename, masterFilename string, onMissing func(filename string) (templateInfo, error)) error {
masterTpl := t.lookup(masterFilename)
if masterTpl == nil {
templ, err := onMissing(masterFilename)
if err != nil {
return err
}
masterTpl, err = t.t.New(overlayFilename).Parse(templ.template)
if err != nil {
return templ.errWithFileContext("parse master failed", err)
}
}
templ, err := onMissing(overlayFilename)
if err != nil {
return err
}
overlayTpl, err := template.Must(masterTpl.Clone()).Parse(templ.template)
if err != nil {
return templ.errWithFileContext("parse failed", err)
}
// The extra lookup is a workaround, see
// * https://github.com/golang/go/issues/16101
// * https://github.com/gohugoio/hugo/issues/2549
overlayTpl = overlayTpl.Lookup(overlayTpl.Name())
if _, err := applyTemplateTransformersToHMLTTemplate(templateUndefined, overlayTpl); err != nil {
return err
}
t.overlays[name] = overlayTpl
t.nameBaseTemplateName[name] = masterFilename
return err
}
func (t *textTemplates) handleMaster(name, overlayFilename, masterFilename string, onMissing func(filename string) (templateInfo, error)) error {
name = strings.TrimPrefix(name, textTmplNamePrefix)
masterTpl := t.lookup(masterFilename)
if masterTpl == nil {
templ, err := onMissing(masterFilename)
if err != nil {
return err
}
masterTpl, err = t.t.New(masterFilename).Parse(templ.template)
if err != nil {
return errors.Wrapf(err, "failed to parse %q:", templ.filename)
}
t.nameBaseTemplateName[masterFilename] = templ.filename
}
templ, err := onMissing(overlayFilename)
if err != nil {
return err
}
overlayTpl, err := texttemplate.Must(masterTpl.Clone()).Parse(templ.template)
if err != nil {
return errors.Wrapf(err, "failed to parse %q:", templ.filename)
}
overlayTpl = overlayTpl.Lookup(overlayTpl.Name())
if _, err := applyTemplateTransformersToTextTemplate(templateUndefined, overlayTpl); err != nil {
return err
}
t.overlays[name] = overlayTpl
t.nameBaseTemplateName[name] = templ.filename
return err
}
func removeLeadingBOM(s string) string {
const bom = '\ufeff'
for i, r := range s {
if i == 0 && r != bom {
return s
}
if i > 0 {
return s[i:]
}
}
return s
}
func (t *templateHandler) addTemplateFile(name, baseTemplatePath, path string) error {
t.checkState()
t.Log.DEBUG.Printf("Add template file: name %q, baseTemplatePath %q, path %q", name, baseTemplatePath, path)
getTemplate := func(filename string) (templateInfo, error) {
fs := t.Layouts.Fs
b, err := afero.ReadFile(fs, filename)
if err != nil {
return templateInfo{filename: filename, fs: fs}, err
}
s := removeLeadingBOM(string(b))
realFilename := filename
if fi, err := fs.Stat(filename); err == nil {
if fim, ok := fi.(hugofs.FileMetaInfo); ok {
realFilename = fim.Meta().Filename()
}
}
return templateInfo{template: s, filename: filename, realFilename: realFilename, fs: fs}, nil
}
// get the suffix and switch on that
ext := filepath.Ext(path)
switch ext {
case ".amber":
// Only HTML support for Amber
withoutExt := strings.TrimSuffix(name, filepath.Ext(name))
templateName := withoutExt + ".html"
b, err := afero.ReadFile(t.Layouts.Fs, path)
if err != nil {
return err
}
amberMu.Lock()
templ, err := t.compileAmberWithTemplate(b, path, t.html.t.New(templateName))
amberMu.Unlock()
if err != nil {
return err
}
typ := resolveTemplateType(name)
c, err := applyTemplateTransformersToHMLTTemplate(typ, templ)
if err != nil {
return err
}
if typ == templateShortcode {
t.addShortcodeVariant(templateName, c.Info, templ)
} else {
t.templateInfo[name] = c.Info
}
return nil
case ".ace":
// Only HTML support for Ace
var innerContent, baseContent []byte
innerContent, err := afero.ReadFile(t.Layouts.Fs, path)
if err != nil {
return err
}
if baseTemplatePath != "" {
baseContent, err = afero.ReadFile(t.Layouts.Fs, baseTemplatePath)
if err != nil {
return err
}
}
return t.addAceTemplate(name, baseTemplatePath, path, baseContent, innerContent)
default:
if baseTemplatePath != "" {
return t.handleMaster(name, path, baseTemplatePath, getTemplate)
}
templ, err := getTemplate(path)
if err != nil {
return err
}
err = t.AddTemplate(name, templ.template)
if err != nil {
return templ.errWithFileContext("parse failed", err)
}
return nil
}
}
var embeddedTemplatesAliases = map[string][]string{
"shortcodes/twitter.html": {"shortcodes/tweet.html"},
}
func (t *templateHandler) loadEmbedded() error {
for _, kv := range embedded.EmbeddedTemplates {
name, templ := kv[0], kv[1]
if err := t.addInternalTemplate(name, templ); err != nil {
return err
}
if aliases, found := embeddedTemplatesAliases[name]; found {
for _, alias := range aliases {
if err := t.addInternalTemplate(alias, templ); err != nil {
return err
}
}
}
}
return nil
}
func (t *templateHandler) addInternalTemplate(name, tpl string) error {
return t.AddTemplate("_internal/"+name, tpl)
}
func (t *templateHandler) checkState() {
if t.html.clone != nil || t.text.clone != nil {
panic("template is cloned and cannot be modfified")
}
}
func isDotFile(path string) bool {
return filepath.Base(path)[0] == '.'
}
func isBackupFile(path string) bool {
return path[len(path)-1] == '~'
}
const baseFileBase = "baseof"
func isBaseTemplate(path string) bool {
return strings.Contains(filepath.Base(path), baseFileBase)
}
|