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
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
|
// Copyright 2017 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 hugolib
import (
"errors"
"fmt"
"html/template"
"io"
"mime"
"net/url"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"github.com/gohugoio/hugo/common/maps"
"github.com/gohugoio/hugo/resource"
"github.com/gohugoio/hugo/langs"
src "github.com/gohugoio/hugo/source"
"golang.org/x/sync/errgroup"
"github.com/gohugoio/hugo/config"
"github.com/gohugoio/hugo/media"
"github.com/markbates/inflect"
"golang.org/x/net/context"
"github.com/fsnotify/fsnotify"
bp "github.com/gohugoio/hugo/bufferpool"
"github.com/gohugoio/hugo/deps"
"github.com/gohugoio/hugo/helpers"
"github.com/gohugoio/hugo/hugolib/pagemeta"
"github.com/gohugoio/hugo/output"
"github.com/gohugoio/hugo/parser"
"github.com/gohugoio/hugo/related"
"github.com/gohugoio/hugo/source"
"github.com/gohugoio/hugo/tpl"
"github.com/gohugoio/hugo/transform"
"github.com/spf13/afero"
"github.com/spf13/cast"
"github.com/spf13/nitro"
"github.com/spf13/viper"
)
var _ = transform.AbsURL
// used to indicate if run as a test.
var testMode bool
var defaultTimer *nitro.B
// Site contains all the information relevant for constructing a static
// site. The basic flow of information is as follows:
//
// 1. A list of Files is parsed and then converted into Pages.
//
// 2. Pages contain sections (based on the file they were generated from),
// aliases and slugs (included in a pages frontmatter) which are the
// various targets that will get generated. There will be canonical
// listing. The canonical path can be overruled based on a pattern.
//
// 3. Taxonomies are created via configuration and will present some aspect of
// the final page and typically a perm url.
//
// 4. All Pages are passed through a template based on their desired
// layout based on numerous different elements.
//
// 5. The entire collection of files is written to disk.
type Site struct {
owner *HugoSites
*PageCollections
Taxonomies TaxonomyList
// Plural is what we get in the folder, so keep track of this mapping
// to get the singular form from that value.
taxonomiesPluralSingular map[string]string
// This is temporary, see https://github.com/gohugoio/hugo/issues/2835
// Maps "actors-gerard-depardieu" to "Gérard Depardieu" when preserveTaxonomyNames
// is set.
taxonomiesOrigKey map[string]string
Sections Taxonomy
Info SiteInfo
Menus Menus
timer *nitro.B
layoutHandler *output.LayoutHandler
draftCount int
futureCount int
expiredCount int
Data map[string]interface{}
Language *langs.Language
disabledKinds map[string]bool
// Output formats defined in site config per Page Kind, or some defaults
// if not set.
// Output formats defined in Page front matter will override these.
outputFormats map[string]output.Formats
// All the output formats and media types available for this site.
// These values will be merged from the Hugo defaults, the site config and,
// finally, the language settings.
outputFormatsConfig output.Formats
mediaTypesConfig media.Types
// How to handle page front matter.
frontmatterHandler pagemeta.FrontMatterHandler
// We render each site for all the relevant output formats in serial with
// this rendering context pointing to the current one.
rc *siteRenderingContext
// The output formats that we need to render this site in. This slice
// will be fixed once set.
// This will be the union of Site.Pages' outputFormats.
// This slice will be sorted.
renderFormats output.Formats
// Logger etc.
*deps.Deps `json:"-"`
// The func used to title case titles.
titleFunc func(s string) string
relatedDocsHandler *relatedDocsHandler
}
type siteRenderingContext struct {
output.Format
}
func (s *Site) initRenderFormats() {
formatSet := make(map[string]bool)
formats := output.Formats{}
for _, p := range s.Pages {
for _, f := range p.outputFormats {
if !formatSet[f.Name] {
formats = append(formats, f)
formatSet[f.Name] = true
}
}
}
sort.Sort(formats)
s.renderFormats = formats
}
func (s *Site) isEnabled(kind string) bool {
if kind == kindUnknown {
panic("Unknown kind")
}
return !s.disabledKinds[kind]
}
// reset returns a new Site prepared for rebuild.
func (s *Site) reset() *Site {
return &Site{Deps: s.Deps,
layoutHandler: output.NewLayoutHandler(),
disabledKinds: s.disabledKinds,
titleFunc: s.titleFunc,
relatedDocsHandler: newSearchIndexHandler(s.relatedDocsHandler.cfg),
outputFormats: s.outputFormats,
rc: s.rc,
outputFormatsConfig: s.outputFormatsConfig,
frontmatterHandler: s.frontmatterHandler,
mediaTypesConfig: s.mediaTypesConfig,
Language: s.Language,
owner: s.owner,
PageCollections: newPageCollections()}
}
// newSite creates a new site with the given configuration.
func newSite(cfg deps.DepsCfg) (*Site, error) {
c := newPageCollections()
if cfg.Language == nil {
cfg.Language = langs.NewDefaultLanguage(cfg.Cfg)
}
disabledKinds := make(map[string]bool)
for _, disabled := range cast.ToStringSlice(cfg.Language.Get("disableKinds")) {
disabledKinds[disabled] = true
}
var (
mediaTypesConfig []map[string]interface{}
outputFormatsConfig []map[string]interface{}
siteOutputFormatsConfig output.Formats
siteMediaTypesConfig media.Types
err error
)
// Add language last, if set, so it gets precedence.
for _, cfg := range []config.Provider{cfg.Cfg, cfg.Language} {
if cfg.IsSet("mediaTypes") {
mediaTypesConfig = append(mediaTypesConfig, cfg.GetStringMap("mediaTypes"))
}
if cfg.IsSet("outputFormats") {
outputFormatsConfig = append(outputFormatsConfig, cfg.GetStringMap("outputFormats"))
}
}
siteMediaTypesConfig, err = media.DecodeTypes(mediaTypesConfig...)
if err != nil {
return nil, err
}
siteOutputFormatsConfig, err = output.DecodeFormats(siteMediaTypesConfig, outputFormatsConfig...)
if err != nil {
return nil, err
}
outputFormats, err := createSiteOutputFormats(siteOutputFormatsConfig, cfg.Language)
if err != nil {
return nil, err
}
var relatedContentConfig related.Config
if cfg.Language.IsSet("related") {
relatedContentConfig, err = related.DecodeConfig(cfg.Language.Get("related"))
if err != nil {
return nil, err
}
} else {
relatedContentConfig = related.DefaultConfig
taxonomies := cfg.Language.GetStringMapString("taxonomies")
if _, found := taxonomies["tag"]; found {
relatedContentConfig.Add(related.IndexConfig{Name: "tags", Weight: 80})
}
}
titleFunc := helpers.GetTitleFunc(cfg.Language.GetString("titleCaseStyle"))
frontMatterHandler, err := pagemeta.NewFrontmatterHandler(cfg.Logger, cfg.Cfg)
if err != nil {
return nil, err
}
s := &Site{
PageCollections: c,
layoutHandler: output.NewLayoutHandler(),
Language: cfg.Language,
disabledKinds: disabledKinds,
titleFunc: titleFunc,
relatedDocsHandler: newSearchIndexHandler(relatedContentConfig),
outputFormats: outputFormats,
rc: &siteRenderingContext{output.HTMLFormat},
outputFormatsConfig: siteOutputFormatsConfig,
mediaTypesConfig: siteMediaTypesConfig,
frontmatterHandler: frontMatterHandler,
}
s.Info = newSiteInfo(siteBuilderCfg{s: s, pageCollections: c, language: s.Language})
return s, nil
}
// NewSite creates a new site with the given dependency configuration.
// The site will have a template system loaded and ready to use.
// Note: This is mainly used in single site tests.
func NewSite(cfg deps.DepsCfg) (*Site, error) {
s, err := newSite(cfg)
if err != nil {
return nil, err
}
if err = applyDepsIfNeeded(cfg, s); err != nil {
return nil, err
}
return s, nil
}
// NewSiteDefaultLang creates a new site in the default language.
// The site will have a template system loaded and ready to use.
// Note: This is mainly used in single site tests.
// TODO(bep) test refactor -- remove
func NewSiteDefaultLang(withTemplate ...func(templ tpl.TemplateHandler) error) (*Site, error) {
v := viper.New()
if err := loadDefaultSettingsFor(v); err != nil {
return nil, err
}
return newSiteForLang(langs.NewDefaultLanguage(v), withTemplate...)
}
// NewEnglishSite creates a new site in English language.
// The site will have a template system loaded and ready to use.
// Note: This is mainly used in single site tests.
// TODO(bep) test refactor -- remove
func NewEnglishSite(withTemplate ...func(templ tpl.TemplateHandler) error) (*Site, error) {
v := viper.New()
if err := loadDefaultSettingsFor(v); err != nil {
return nil, err
}
return newSiteForLang(langs.NewLanguage("en", v), withTemplate...)
}
// newSiteForLang creates a new site in the given language.
func newSiteForLang(lang *langs.Language, withTemplate ...func(templ tpl.TemplateHandler) error) (*Site, error) {
withTemplates := func(templ tpl.TemplateHandler) error {
for _, wt := range withTemplate {
if err := wt(templ); err != nil {
return err
}
}
return nil
}
cfg := deps.DepsCfg{WithTemplate: withTemplates, Language: lang, Cfg: lang}
return NewSiteForCfg(cfg)
}
// NewSiteForCfg creates a new site for the given configuration.
// The site will have a template system loaded and ready to use.
// Note: This is mainly used in single site tests.
func NewSiteForCfg(cfg deps.DepsCfg) (*Site, error) {
s, err := newSite(cfg)
if err != nil {
return nil, err
}
if err := applyDepsIfNeeded(cfg, s); err != nil {
return nil, err
}
return s, nil
}
type SiteInfos []*SiteInfo
// First is a convenience method to get the first Site, i.e. the main language.
func (s SiteInfos) First() *SiteInfo {
if len(s) == 0 {
return nil
}
return s[0]
}
type SiteInfo struct {
Taxonomies TaxonomyList
Authors AuthorList
Social SiteSocial
*PageCollections
Menus *Menus
Hugo *HugoInfo
Title string
RSSLink string
Author map[string]interface{}
LanguageCode string
Copyright string
LastChange time.Time
Permalinks PermalinkOverrides
Params map[string]interface{}
BuildDrafts bool
canonifyURLs bool
relativeURLs bool
uglyURLs func(p *Page) bool
preserveTaxonomyNames bool
Data *map[string]interface{}
Config SiteConfig
owner *HugoSites
s *Site
multilingual *Multilingual
Language *langs.Language
LanguagePrefix string
Languages langs.Languages
defaultContentLanguageInSubdir bool
sectionPagesMenu string
}
func (s *SiteInfo) String() string {
return fmt.Sprintf("Site(%q)", s.Title)
}
func (s *SiteInfo) BaseURL() template.URL {
return template.URL(s.s.PathSpec.BaseURL.String())
}
// ServerPort returns the port part of the BaseURL, 0 if none found.
func (s *SiteInfo) ServerPort() int {
ps := s.s.PathSpec.BaseURL.URL().Port()
if ps == "" {
return 0
}
p, err := strconv.Atoi(ps)
if err != nil {
return 0
}
return p
}
// GoogleAnalytics is kept here for historic reasons.
func (s *SiteInfo) GoogleAnalytics() string {
return s.Config.Services.GoogleAnalytics.ID
}
// DisqusShortname is kept here for historic reasons.
func (s *SiteInfo) DisqusShortname() string {
return s.Config.Services.Disqus.Shortname
}
// Used in tests.
type siteBuilderCfg struct {
language *langs.Language
s *Site
pageCollections *PageCollections
}
// TODO(bep) get rid of this
func newSiteInfo(cfg siteBuilderCfg) SiteInfo {
return SiteInfo{
s: cfg.s,
multilingual: newMultiLingualForLanguage(cfg.language),
PageCollections: cfg.pageCollections,
Params: make(map[string]interface{}),
uglyURLs: func(p *Page) bool {
return false
},
}
}
// SiteSocial is a place to put social details on a site level. These are the
// standard keys that themes will expect to have available, but can be
// expanded to any others on a per site basis
// github
// facebook
// facebook_admin
// twitter
// twitter_domain
// googleplus
// pinterest
// instagram
// youtube
// linkedin
type SiteSocial map[string]string
// Param is a convenience method to do lookups in SiteInfo's Params map.
//
// This method is also implemented on Page and Node.
func (s *SiteInfo) Param(key interface{}) (interface{}, error) {
keyStr, err := cast.ToStringE(key)
if err != nil {
return nil, err
}
keyStr = strings.ToLower(keyStr)
return s.Params[keyStr], nil
}
func (s *SiteInfo) IsMultiLingual() bool {
return len(s.Languages) > 1
}
func (s *SiteInfo) IsServer() bool {
return s.owner.running
}
func (s *SiteInfo) refLink(ref string, page *Page, relative bool, outputFormat string) (string, error) {
var refURL *url.URL
var err error
ref = filepath.ToSlash(ref)
refURL, err = url.Parse(ref)
if err != nil {
return "", err
}
var target *Page
var link string
if refURL.Path != "" {
target, err := s.getPageNew(page, refURL.Path)
if err != nil {
return "", err
}
if target == nil {
return "", fmt.Errorf("No page found with path or logical name \"%s\".\n", refURL.Path)
}
var permalinker Permalinker = target
if outputFormat != "" {
o := target.OutputFormats().Get(outputFormat)
if o == nil {
return "", fmt.Errorf("Output format %q not found for page %q", outputFormat, refURL.Path)
}
permalinker = o
}
if relative {
link = permalinker.RelPermalink()
} else {
link = permalinker.Permalink()
}
}
if refURL.Fragment != "" {
link = link + "#" + refURL.Fragment
if refURL.Path != "" && target != nil && !target.getRenderingConfig().PlainIDAnchors {
link = link + ":" + target.UniqueID()
} else if page != nil && !page.getRenderingConfig().PlainIDAnchors {
link = link + ":" + page.UniqueID()
}
}
return link, nil
}
// Ref will give an absolute URL to ref in the given Page.
func (s *SiteInfo) Ref(ref string, page *Page, options ...string) (string, error) {
outputFormat := ""
if len(options) > 0 {
outputFormat = options[0]
}
return s.refLink(ref, page, false, outputFormat)
}
// RelRef will give an relative URL to ref in the given Page.
func (s *SiteInfo) RelRef(ref string, page *Page, options ...string) (string, error) {
outputFormat := ""
if len(options) > 0 {
outputFormat = options[0]
}
return s.refLink(ref, page, true, outputFormat)
}
func (s *Site) running() bool {
return s.owner != nil && s.owner.running
}
func init() {
defaultTimer = nitro.Initalize()
}
func (s *Site) timerStep(step string) {
if s.timer == nil {
s.timer = defaultTimer
}
s.timer.Step(step)
}
type whatChanged struct {
source bool
other bool
files map[string]bool
}
// RegisterMediaTypes will register the Site's media types in the mime
// package, so it will behave correctly with Hugo's built-in server.
func (s *Site) RegisterMediaTypes() {
for _, mt := range s.mediaTypesConfig {
for _, suffix := range mt.Suffixes {
_ = mime.AddExtensionType(mt.Delimiter+suffix, mt.Type()+"; charset=utf-8")
}
}
}
func (s *Site) filterFileEvents(events []fsnotify.Event) []fsnotify.Event {
var filtered []fsnotify.Event
seen := make(map[fsnotify.Event]bool)
for _, ev := range events {
// Avoid processing the same event twice.
if seen[ev] {
continue
}
seen[ev] = true
if s.SourceSpec.IgnoreFile(ev.Name) {
continue
}
// Throw away any directories
isRegular, err := s.SourceSpec.IsRegularSourceFile(ev.Name)
if err != nil && os.IsNotExist(err) && (ev.Op&fsnotify.Remove == fsnotify.Remove || ev.Op&fsnotify.Rename == fsnotify.Rename) {
// Force keep of event
isRegular = true
}
if !isRegular {
continue
}
filtered = append(filtered, ev)
}
return filtered
}
func (s *Site) translateFileEvents(events []fsnotify.Event) []fsnotify.Event {
var filtered []fsnotify.Event
eventMap := make(map[string][]fsnotify.Event)
// We often get a Remove etc. followed by a Create, a Create followed by a Write.
// Remove the superflous events to mage the update logic simpler.
for _, ev := range events {
eventMap[ev.Name] = append(eventMap[ev.Name], ev)
}
for _, ev := range events {
mapped := eventMap[ev.Name]
// Keep one
found := false
var kept fsnotify.Event
for i, ev2 := range mapped {
if i == 0 {
kept = ev2
}
if ev2.Op&fsnotify.Write == fsnotify.Write {
kept = ev2
found = true
}
if !found && ev2.Op&fsnotify.Create == fsnotify.Create {
kept = ev2
}
}
filtered = append(filtered, kept)
}
return filtered
}
// reBuild partially rebuilds a site given the filesystem events.
// It returns whetever the content source was changed.
// TODO(bep) clean up/rewrite this method.
func (s *Site) processPartial(events []fsnotify.Event) (whatChanged, error) {
events = s.filterFileEvents(events)
events = s.translateFileEvents(events)
s.Log.DEBUG.Printf("Rebuild for events %q", events)
h := s.owner
s.timerStep("initialize rebuild")
// First we need to determine what changed
var (
sourceChanged = []fsnotify.Event{}
sourceReallyChanged = []fsnotify.Event{}
contentFilesChanged []string
tmplChanged = []fsnotify.Event{}
dataChanged = []fsnotify.Event{}
i18nChanged = []fsnotify.Event{}
shortcodesChanged = make(map[string]bool)
sourceFilesChanged = make(map[string]bool)
// prevent spamming the log on changes
logger = helpers.NewDistinctFeedbackLogger()
)
cachePartitions := make([]string, len(events))
for i, ev := range events {
cachePartitions[i] = resource.ResourceKeyPartition(ev.Name)
if s.isContentDirEvent(ev) {
logger.Println("Source changed", ev)
sourceChanged = append(sourceChanged, ev)
}
if s.isLayoutDirEvent(ev) {
logger.Println("Template changed", ev)
tmplChanged = append(tmplChanged, ev)
if strings.Contains(ev.Name, "shortcodes") {
clearIsInnerShortcodeCache()
shortcode := filepath.Base(ev.Name)
shortcode = strings.TrimSuffix(shortcode, filepath.Ext(shortcode))
shortcodesChanged[shortcode] = true
}
}
if s.isDataDirEvent(ev) {
logger.Println("Data changed", ev)
dataChanged = append(dataChanged, ev)
}
if s.isI18nEvent(ev) {
logger.Println("i18n changed", ev)
i18nChanged = append(dataChanged, ev)
}
}
// These in memory resource caches will be rebuilt on demand.
for _, s := range s.owner.Sites {
s.ResourceSpec.ResourceCache.DeletePartitions(cachePartitions...)
}
if len(tmplChanged) > 0 || len(i18nChanged) > 0 {
sites := s.owner.Sites
first := sites[0]
// TOD(bep) globals clean
if err := first.Deps.LoadResources(); err != nil {
return whatChanged{}, err
}
s.TemplateHandler().PrintErrors()
for i := 1; i < len(sites); i++ {
site := sites[i]
var err error
depsCfg := deps.DepsCfg{
Language: site.Language,
MediaTypes: site.mediaTypesConfig,
}
site.Deps, err = first.Deps.ForLanguage(depsCfg)
if err != nil {
return whatChanged{}, err
}
}
s.timerStep("template prep")
}
if len(dataChanged) > 0 {
if err := s.readDataFromSourceFS(); err != nil {
s.Log.ERROR.Println(err)
}
}
for _, ev := range sourceChanged {
removed := false
if ev.Op&fsnotify.Remove == fsnotify.Remove {
removed = true
}
// Some editors (Vim) sometimes issue only a Rename operation when writing an existing file
// Sometimes a rename operation means that file has been renamed other times it means
// it's been updated
if ev.Op&fsnotify.Rename == fsnotify.Rename {
// If the file is still on disk, it's only been updated, if it's not, it's been moved
if ex, err := afero.Exists(s.Fs.Source, ev.Name); !ex || err != nil {
removed = true
}
}
if removed && isContentFile(ev.Name) {
h.removePageByFilename(ev.Name)
}
sourceReallyChanged = append(sourceReallyChanged, ev)
sourceFilesChanged[ev.Name] = true
}
for shortcode := range shortcodesChanged {
// There are certain scenarios that, when a shortcode changes,
// it isn't sufficient to just rerender the already parsed shortcode.
// One example is if the user adds a new shortcode to the content file first,
// and then creates the shortcode on the file system.
// To handle these scenarios, we must do a full reprocessing of the
// pages that keeps a reference to the changed shortcode.
pagesWithShortcode := h.findPagesByShortcode(shortcode)
for _, p := range pagesWithShortcode {
contentFilesChanged = append(contentFilesChanged, p.File.Filename())
}
}
if len(sourceReallyChanged) > 0 || len(contentFilesChanged) > 0 {
var filenamesChanged []string
for _, e := range sourceReallyChanged {
filenamesChanged = append(filenamesChanged, e.Name)
}
if len(contentFilesChanged) > 0 {
filenamesChanged = append(filenamesChanged, contentFilesChanged...)
}
filenamesChanged = helpers.UniqueStrings(filenamesChanged)
if err := s.readAndProcessContent(filenamesChanged...); err != nil {
return whatChanged{}, err
}
}
changed := whatChanged{
source: len(sourceChanged) > 0 || len(shortcodesChanged) > 0,
other: len(tmplChanged) > 0 || len(i18nChanged) > 0 || len(dataChanged) > 0,
files: sourceFilesChanged,
}
return changed, nil
}
func (s *Site) loadData(fs afero.Fs) (err error) {
spec := src.NewSourceSpec(s.PathSpec, fs)
fileSystem := spec.NewFilesystem("")
s.Data = make(map[string]interface{})
for _, r := range fileSystem.Files() {
if err := s.handleDataFile(r); err != nil {
return err
}
}
return
}
func (s *Site) handleDataFile(r source.ReadableFile) error {
var current map[string]interface{}
f, err := r.Open()
if err != nil {
return fmt.Errorf("Failed to open data file %q: %s", r.LogicalName(), err)
}
defer f.Close()
// Crawl in data tree to insert data
current = s.Data
keyParts := strings.Split(r.Dir(), helpers.FilePathSeparator)
// The first path element is the virtual folder (typically theme name), which is
// not part of the key.
if len(keyParts) > 1 {
for _, key := range keyParts[1:] {
if key != "" {
if _, ok := current[key]; !ok {
current[key] = make(map[string]interface{})
}
current = current[key].(map[string]interface{})
}
}
}
data, err := s.readData(r)
if err != nil {
s.Log.ERROR.Printf("Failed to read data from %s: %s", filepath.Join(r.Path(), r.LogicalName()), err)
return nil
}
if data == nil {
return nil
}
// filepath.Walk walks the files in lexical order, '/' comes before '.'
// this warning could happen if
// 1. A theme uses the same key; the main data folder wins
// 2. A sub folder uses the same key: the sub folder wins
higherPrecedentData := current[r.BaseFileName()]
switch data.(type) {
case nil:
// hear the crickets?
case map[string]interface{}:
switch higherPrecedentData.(type) {
case nil:
current[r.BaseFileName()] = data
case map[string]interface{}:
// merge maps: insert entries from data for keys that
// don't already exist in higherPrecedentData
higherPrecedentMap := higherPrecedentData.(map[string]interface{})
for key, value := range data.(map[string]interface{}) {
if _, exists := higherPrecedentMap[key]; exists {
s.Log.WARN.Printf("Data for key '%s' in path '%s' is overridden higher precedence data already in the data tree", key, r.Path())
} else {
higherPrecedentMap[key] = value
}
}
default:
// can't merge: higherPrecedentData is not a map
s.Log.WARN.Printf("The %T data from '%s' overridden by "+
"higher precedence %T data already in the data tree", data, r.Path(), higherPrecedentData)
}
case []interface{}:
if higherPrecedentData == nil {
current[r.BaseFileName()] = data
} else {
// we don't merge array data
s.Log.WARN.Printf("The %T data from '%s' overridden by "+
"higher precedence %T data already in the data tree", data, r.Path(), higherPrecedentData)
}
default:
s.Log.ERROR.Printf("unexpected data type %T in file %s", data, r.LogicalName())
}
return nil
}
func (s *Site) readData(f source.ReadableFile) (interface{}, error) {
file, err := f.Open()
if err != nil {
return nil, fmt.Errorf("readData: failed to open data file: %s", err)
}
defer file.Close()
content := helpers.ReaderToBytes(file)
switch f.Extension() {
case "yaml", "yml":
return parser.HandleYAMLData(content)
case "json":
return parser.HandleJSONData(content)
case "toml":
return parser.HandleTOMLMetaData(content)
default:
return nil, fmt.Errorf("Data not supported for extension '%s'", f.Extension())
}
}
func (s *Site) readDataFromSourceFS() error {
err := s.loadData(s.PathSpec.BaseFs.Data.Fs)
s.timerStep("load data")
return err
}
func (s *Site) process(config BuildCfg) (err error) {
if err = s.initialize(); err != nil {
return
}
s.timerStep("initialize")
if err = s.readDataFromSourceFS(); err != nil {
return
}
s.timerStep("load i18n")
if err := s.readAndProcessContent(); err != nil {
return err
}
s.timerStep("read and convert pages from source")
return err
}
func (s *Site) setupSitePages() {
var siteLastChange time.Time
for i, page := range s.RegularPages {
if i < len(s.RegularPages)-1 {
page.Next = s.RegularPages[i+1]
}
if i > 0 {
page.Prev = s.RegularPages[i-1]
}
// Determine Site.Info.LastChange
// Note that the logic to determine which date to use for Lastmod
// is already applied, so this is *the* date to use.
// We cannot just pick the last page in the default sort, because
// that may not be ordered by date.
if page.Lastmod.After(siteLastChange) {
siteLastChange = page.Lastmod
}
}
s.Info.LastChange = siteLastChange
}
func (s *Site) render(config *BuildCfg, outFormatIdx int) (err error) {
if outFormatIdx == 0 {
if err = s.preparePages(); err != nil {
return
}
s.timerStep("prepare pages")
// Note that even if disableAliases is set, the aliases themselves are
// preserved on page. The motivation with this is to be able to generate
// 301 redirects in a .htacess file and similar using a custom output format.
if !s.Cfg.GetBool("disableAliases") {
// Aliases must be rendered before pages.
// Some sites, Hugo docs included, have faulty alias definitions that point
// to itself or another real page. These will be overwritten in the next
// step.
if err = s.renderAliases(); err != nil {
return
}
s.timerStep("render and write aliases")
}
}
if err = s.renderPages(config); err != nil {
return
}
s.timerStep("render and write pages")
// TODO(bep) render consider this, ref. render404 etc.
if outFormatIdx > 0 {
return
}
if err = s.renderSitemap(); err != nil {
return
}
s.timerStep("render and write Sitemap")
if err = s.renderRobotsTXT(); err != nil {
return
}
s.timerStep("render and write robots.txt")
if err = s.render404(); err != nil {
return
}
s.timerStep("render and write 404")
return
}
func (s *Site) Initialise() (err error) {
return s.initialize()
}
func (s *Site) initialize() (err error) {
s.Menus = Menus{}
return s.initializeSiteInfo()
}
// HomeAbsURL is a convenience method giving the absolute URL to the home page.
func (s *SiteInfo) HomeAbsURL() string {
base := ""
if s.IsMultiLingual() {
base = s.Language.Lang
}
return s.owner.AbsURL(base, false)
}
// SitemapAbsURL is a convenience method giving the absolute URL to the sitemap.
func (s *SiteInfo) SitemapAbsURL() string {
sitemapDefault := parseSitemap(s.s.Cfg.GetStringMap("sitemap"))
p := s.HomeAbsURL()
if !strings.HasSuffix(p, "/") {
p += "/"
}
p += sitemapDefault.Filename
return p
}
func (s *Site) initializeSiteInfo() error {
var (
lang = s.Language
languages langs.Languages
)
if s.owner != nil && s.owner.multilingual != nil {
languages = s.owner.multilingual.Languages
}
params := lang.Params()
permalinks := make(PermalinkOverrides)
for k, v := range s.Cfg.GetStringMapString("permalinks") {
permalinks[k] = pathPattern(v)
}
defaultContentInSubDir := s.Cfg.GetBool("defaultContentLanguageInSubdir")
defaultContentLanguage := s.Cfg.GetString("defaultContentLanguage")
languagePrefix := ""
if s.multilingualEnabled() && (defaultContentInSubDir || lang.Lang != defaultContentLanguage) {
languagePrefix = "/" + lang.Lang
}
var multilingual *Multilingual
if s.owner != nil {
multilingual = s.owner.multilingual
}
var uglyURLs = func(p *Page) bool {
return false
}
v := s.Cfg.Get("uglyURLs")
if v != nil {
switch vv := v.(type) {
case bool:
uglyURLs = func(p *Page) bool {
return vv
}
case string:
// Is what be get from CLI (--uglyURLs)
vvv := cast.ToBool(vv)
uglyURLs = func(p *Page) bool {
return vvv
}
default:
m := cast.ToStringMapBool(v)
uglyURLs = func(p *Page) bool {
return m[p.Section()]
}
}
}
siteConfig, err := loadSiteConfig(lang)
if err != nil {
return err
}
s.Info = SiteInfo{
Title: lang.GetString("title"),
Author: lang.GetStringMap("author"),
Social: lang.GetStringMapString("social"),
LanguageCode: lang.GetString("languageCode"),
Copyright: lang.GetString("copyright"),
multilingual: multilingual,
Language: lang,
LanguagePrefix: languagePrefix,
Languages: languages,
defaultContentLanguageInSubdir: defaultContentInSubDir,
sectionPagesMenu: lang.GetString("sectionPagesMenu"),
BuildDrafts: s.Cfg.GetBool("buildDrafts"),
canonifyURLs: s.Cfg.GetBool("canonifyURLs"),
relativeURLs: s.Cfg.GetBool("relativeURLs"),
uglyURLs: uglyURLs,
preserveTaxonomyNames: lang.GetBool("preserveTaxonomyNames"),
PageCollections: s.PageCollections,
Menus: &s.Menus,
Params: params,
Permalinks: permalinks,
Data: &s.Data,
owner: s.owner,
s: s,
Config: siteConfig,
// TODO(bep) make this Menu and similar into delegate methods on SiteInfo
Taxonomies: s.Taxonomies,
}
rssOutputFormat, found := s.outputFormats[KindHome].GetByName(output.RSSFormat.Name)
if found {
s.Info.RSSLink = s.permalink(rssOutputFormat.BaseFilename())
}
return nil
}
func (s *Site) isI18nEvent(e fsnotify.Event) bool {
return s.BaseFs.SourceFilesystems.IsI18n(e.Name)
}
func (s *Site) isDataDirEvent(e fsnotify.Event) bool {
return s.BaseFs.SourceFilesystems.IsData(e.Name)
}
func (s *Site) isLayoutDirEvent(e fsnotify.Event) bool {
return s.BaseFs.SourceFilesystems.IsLayout(e.Name)
}
func (s *Site) absContentDir() string {
return s.PathSpec.AbsPathify(s.PathSpec.ContentDir)
}
func (s *Site) isContentDirEvent(e fsnotify.Event) bool {
return s.BaseFs.IsContent(e.Name)
}
type contentCaptureResultHandler struct {
defaultContentProcessor *siteContentProcessor
contentProcessors map[string]*siteContentProcessor
}
func (c *contentCaptureResultHandler) getContentProcessor(lang string) *siteContentProcessor {
proc, found := c.contentProcessors[lang]
if found {
return proc
}
return c.defaultContentProcessor
}
func (c *contentCaptureResultHandler) handleSingles(fis ...*fileInfo) {
for _, fi := range fis {
proc := c.getContentProcessor(fi.Lang())
proc.processSingle(fi)
}
}
func (c *contentCaptureResultHandler) handleBundles(d *bundleDirs) {
for _, b := range d.bundles {
proc := c.getContentProcessor(b.fi.Lang())
proc.processBundle(b)
}
}
func (c *contentCaptureResultHandler) handleCopyFiles(files ...pathLangFile) {
for _, proc := range c.contentProcessors {
proc.processAssets(files)
}
}
func (s *Site) readAndProcessContent(filenames ...string) error {
ctx := context.Background()
g, ctx := errgroup.WithContext(ctx)
defaultContentLanguage := s.SourceSpec.DefaultContentLanguage
contentProcessors := make(map[string]*siteContentProcessor)
var defaultContentProcessor *siteContentProcessor
sites := s.owner.langSite()
for k, v := range sites {
if v.Language.Disabled {
continue
}
proc := newSiteContentProcessor(ctx, len(filenames) > 0, v)
contentProcessors[k] = proc
if k == defaultContentLanguage {
defaultContentProcessor = proc
}
g.Go(func() error {
return proc.process(ctx)
})
}
var (
handler captureResultHandler
bundleMap *contentChangeMap
)
mainHandler := &contentCaptureResultHandler{contentProcessors: contentProcessors, defaultContentProcessor: defaultContentProcessor}
sourceSpec := source.NewSourceSpec(s.PathSpec, s.BaseFs.Content.Fs)
if s.running() {
// Need to track changes.
bundleMap = s.owner.ContentChanges
handler = &captureResultHandlerChain{handlers: []captureBundlesHandler{mainHandler, bundleMap}}
} else {
handler = mainHandler
}
c := newCapturer(s.Log, sourceSpec, handler, bundleMap, filenames...)
err1 := c.capture()
for _, proc := range contentProcessors {
proc.closeInput()
}
err2 := g.Wait()
if err1 != nil {
return err1
}
return err2
}
func (s *Site) buildSiteMeta() (err error) {
defer s.timerStep("build Site meta")
if len(s.Pages) == 0 {
return
}
s.assembleTaxonomies()
for _, p := range s.AllPages {
// this depends on taxonomies
p.setValuesForKind(s)
}
return
}
func (s *Site) getMenusFromConfig() Menus {
ret := Menus{}
if menus := s.Language.GetStringMap("menu"); menus != nil {
for name, menu := range menus {
m, err := cast.ToSliceE(menu)
if err != nil {
s.Log.ERROR.Printf("unable to process menus in site config\n")
s.Log.ERROR.Println(err)
} else {
for _, entry := range m {
s.Log.DEBUG.Printf("found menu: %q, in site config\n", name)
menuEntry := MenuEntry{Menu: name}
ime, err := cast.ToStringMapE(entry)
if err != nil {
s.Log.ERROR.Printf("unable to process menus in site config\n")
s.Log.ERROR.Println(err)
}
menuEntry.marshallMap(ime)
menuEntry.URL = s.Info.createNodeMenuEntryURL(menuEntry.URL)
if ret[name] == nil {
ret[name] = &Menu{}
}
*ret[name] = ret[name].add(&menuEntry)
}
}
}
return ret
}
return ret
}
func (s *SiteInfo) createNodeMenuEntryURL(in string) string {
if !strings.HasPrefix(in, "/") {
return in
}
// make it match the nodes
menuEntryURL := in
menuEntryURL = helpers.SanitizeURLKeepTrailingSlash(s.s.PathSpec.URLize(menuEntryURL))
if !s.canonifyURLs {
menuEntryURL = helpers.AddContextRoot(s.s.PathSpec.BaseURL.String(), menuEntryURL)
}
return menuEntryURL
}
func (s *Site) assembleMenus() {
s.Menus = Menus{}
type twoD struct {
MenuName, EntryName string
}
flat := map[twoD]*MenuEntry{}
children := map[twoD]Menu{}
// add menu entries from config to flat hash
menuConfig := s.getMenusFromConfig()
for name, menu := range menuConfig {
for _, me := range *menu {
flat[twoD{name, me.KeyName()}] = me
}
}
sectionPagesMenu := s.Info.sectionPagesMenu
pages := s.Pages
if sectionPagesMenu != "" {
for _, p := range pages {
if p.Kind == KindSection {
// From Hugo 0.22 we have nested sections, but until we get a
// feel of how that would work in this setting, let us keep
// this menu for the top level only.
id := p.Section()
if _, ok := flat[twoD{sectionPagesMenu, id}]; ok {
continue
}
me := MenuEntry{Identifier: id,
Name: p.LinkTitle(),
Weight: p.Weight,
URL: p.RelPermalink()}
flat[twoD{sectionPagesMenu, me.KeyName()}] = &me
}
}
}
// Add menu entries provided by pages
for _, p := range pages {
for name, me := range p.Menus() {
if _, ok := flat[twoD{name, me.KeyName()}]; ok {
s.Log.ERROR.Printf("Two or more menu items have the same name/identifier in Menu %q: %q.\nRename or set an unique identifier.\n", name, me.KeyName())
continue
}
flat[twoD{name, me.KeyName()}] = me
}
}
// Create Children Menus First
for _, e := range flat {
if e.Parent != "" {
children[twoD{e.Menu, e.Parent}] = children[twoD{e.Menu, e.Parent}].add(e)
}
}
// Placing Children in Parents (in flat)
for p, childmenu := range children {
_, ok := flat[twoD{p.MenuName, p.EntryName}]
if !ok {
// if parent does not exist, create one without a URL
flat[twoD{p.MenuName, p.EntryName}] = &MenuEntry{Name: p.EntryName, URL: ""}
}
flat[twoD{p.MenuName, p.EntryName}].Children = childmenu
}
// Assembling Top Level of Tree
for menu, e := range flat {
if e.Parent == "" {
_, ok := s.Menus[menu.MenuName]
if !ok {
s.Menus[menu.MenuName] = &Menu{}
}
*s.Menus[menu.MenuName] = s.Menus[menu.MenuName].add(e)
}
}
}
func (s *Site) getTaxonomyKey(key string) string {
if s.Info.preserveTaxonomyNames {
// Keep as is
return key
}
return s.PathSpec.MakePathSanitized(key)
}
// We need to create the top level taxonomy early in the build process
// to be able to determine the page Kind correctly.
func (s *Site) createTaxonomiesEntries() {
s.Taxonomies = make(TaxonomyList)
taxonomies := s.Language.GetStringMapString("taxonomies")
for _, plural := range taxonomies {
s.Taxonomies[plural] = make(Taxonomy)
}
}
func (s *Site) assembleTaxonomies() {
s.taxonomiesPluralSingular = make(map[string]string)
s.taxonomiesOrigKey = make(map[string]string)
taxonomies := s.Language.GetStringMapString("taxonomies")
s.Log.INFO.Printf("found taxonomies: %#v\n", taxonomies)
for singular, plural := range taxonomies {
s.taxonomiesPluralSingular[plural] = singular
for _, p := range s.Pages {
vals := p.getParam(plural, !s.Info.preserveTaxonomyNames)
weight := p.getParamToLower(plural + "_weight")
if weight == nil {
weight = 0
}
if vals != nil {
if v, ok := vals.([]string); ok {
for _, idx := range v {
x := WeightedPage{weight.(int), p}
s.Taxonomies[plural].add(s.getTaxonomyKey(idx), x)
if s.Info.preserveTaxonomyNames {
// Need to track the original
s.taxonomiesOrigKey[fmt.Sprintf("%s-%s", plural, s.PathSpec.MakePathSanitized(idx))] = idx
}
}
} else if v, ok := vals.(string); ok {
x := WeightedPage{weight.(int), p}
s.Taxonomies[plural].add(s.getTaxonomyKey(v), x)
if s.Info.preserveTaxonomyNames {
// Need to track the original
s.taxonomiesOrigKey[fmt.Sprintf("%s-%s", plural, s.PathSpec.MakePathSanitized(v))] = v
}
} else {
s.Log.ERROR.Printf("Invalid %s in %s\n", plural, p.File.Path())
}
}
}
for k := range s.Taxonomies[plural] {
s.Taxonomies[plural][k].Sort()
}
}
s.Info.Taxonomies = s.Taxonomies
}
// Prepare site for a new full build.
func (s *Site) resetBuildState() {
s.relatedDocsHandler = newSearchIndexHandler(s.relatedDocsHandler.cfg)
s.PageCollections = newPageCollectionsFromPages(s.rawAllPages)
// TODO(bep) get rid of this double
s.Info.PageCollections = s.PageCollections
s.draftCount = 0
s.futureCount = 0
s.expiredCount = 0
spc = newPageCache()
for _, p := range s.rawAllPages {
p.subSections = Pages{}
p.parent = nil
p.scratch = maps.NewScratch()
p.mainPageOutput = nil
}
}
func (s *Site) kindFromSections(sections []string) string {
if len(sections) == 0 {
return KindSection
}
if _, isTaxonomy := s.Taxonomies[sections[0]]; isTaxonomy {
if len(sections) == 1 {
return KindTaxonomyTerm
}
return KindTaxonomy
}
return KindSection
}
func (s *Site) layouts(p *PageOutput) ([]string, error) {
return s.layoutHandler.For(p.layoutDescriptor, p.outputFormat)
}
func (s *Site) preparePages() error {
var errors []error
for _, p := range s.Pages {
if err := p.prepareLayouts(); err != nil {
errors = append(errors, err)
}
if err := p.prepareData(s); err != nil {
errors = append(errors, err)
}
}
if len(errors) != 0 {
return fmt.Errorf("Prepare pages failed: %.100q…", errors)
}
return nil
}
func errorCollator(results <-chan error, errs chan<- error) {
errMsgs := []string{}
for err := range results {
if err != nil {
errMsgs = append(errMsgs, err.Error())
}
}
if len(errMsgs) == 0 {
errs <- nil
} else {
errs <- errors.New(strings.Join(errMsgs, "\n"))
}
close(errs)
}
func (s *Site) appendThemeTemplates(in []string) []string {
if !s.PathSpec.ThemeSet() {
return in
}
out := []string{}
// First place all non internal templates
for _, t := range in {
if !strings.HasPrefix(t, "_internal/") {
out = append(out, t)
}
}
// Then place theme templates with the same names
for _, t := range in {
if !strings.HasPrefix(t, "_internal/") {
out = append(out, "theme/"+t)
}
}
// Lastly place internal templates
for _, t := range in {
if strings.HasPrefix(t, "_internal/") {
out = append(out, t)
}
}
return out
}
// GetPage looks up a page of a given type for the given ref.
// In Hugo <= 0.44 you had to add Page Kind (section, home) etc. as the first
// argument and then either a unix styled path (with or without a leading slash))
// or path elements separated.
// When we now remove the Kind from this API, we need to make the transition as painless
// as possible for existing sites. Most sites will use {{ .Site.GetPage "section" "my/section" }},
// i.e. 2 arguments, so we test for that.
func (s *SiteInfo) GetPage(ref ...string) (*Page, error) {
var refs []string
for _, r := range ref {
// A common construct in the wild is
// .Site.GetPage "home" "" or
// .Site.GetPage "home" "/"
if r != "" && r != "/" {
refs = append(refs, r)
}
}
var key string
if len(refs) > 2 {
// This was allowed in Hugo <= 0.44, but we cannot support this with the
// new API. This should be the most unusual case.
return nil, fmt.Errorf(`too many arguments to .Site.GetPage: %v. Use lookups on the form {{ .Site.GetPage "/posts/mypage-md" }}`, ref)
}
if len(refs) == 0 || refs[0] == KindHome {
key = "/"
} else if len(refs) == 1 {
key = refs[0]
} else {
key = refs[1]
}
key = filepath.ToSlash(key)
if !strings.HasPrefix(key, "/") {
key = "/" + key
}
return s.getPageNew(nil, key)
}
func (s *Site) permalinkForOutputFormat(link string, f output.Format) (string, error) {
var (
baseURL string
err error
)
if f.Protocol != "" {
baseURL, err = s.PathSpec.BaseURL.WithProtocol(f.Protocol)
if err != nil {
return "", err
}
} else {
baseURL = s.PathSpec.BaseURL.String()
}
return s.PathSpec.PermalinkForBaseURL(link, baseURL), nil
}
func (s *Site) permalink(link string) string {
return s.PathSpec.PermalinkForBaseURL(link, s.PathSpec.BaseURL.String())
}
func (s *Site) renderAndWriteXML(statCounter *uint64, name string, dest string, d interface{}, layouts ...string) error {
s.Log.DEBUG.Printf("Render XML for %q to %q", name, dest)
renderBuffer := bp.GetBuffer()
defer bp.PutBuffer(renderBuffer)
renderBuffer.WriteString("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\" ?>\n")
if err := s.renderForLayouts(name, d, renderBuffer, layouts...); err != nil {
helpers.DistinctWarnLog.Println(err)
return nil
}
outBuffer := bp.GetBuffer()
defer bp.PutBuffer(outBuffer)
var path []byte
if s.Info.relativeURLs {
path = []byte(helpers.GetDottedRelativePath(dest))
} else {
s := s.PathSpec.BaseURL.String()
if !strings.HasSuffix(s, "/") {
s += "/"
}
path = []byte(s)
}
transformer := transform.NewChain(transform.AbsURLInXML)
if err := transformer.Apply(outBuffer, renderBuffer, path); err != nil {
s.DistinctErrorLog.Println(err)
return nil
}
return s.publish(statCounter, dest, outBuffer)
}
func (s *Site) renderAndWritePage(statCounter *uint64, name string, dest string, p *PageOutput, layouts ...string) error {
renderBuffer := bp.GetBuffer()
defer bp.PutBuffer(renderBuffer)
if err := s.renderForLayouts(p.Kind, p, renderBuffer, layouts...); err != nil {
helpers.DistinctWarnLog.Println(err)
return nil
}
if renderBuffer.Len() == 0 {
return nil
}
outBuffer := bp.GetBuffer()
defer bp.PutBuffer(outBuffer)
transformLinks := transform.NewEmptyTransforms()
isHTML := p.outputFormat.IsHTML
if isHTML {
if s.Info.relativeURLs || s.Info.canonifyURLs {
transformLinks = append(transformLinks, transform.AbsURL)
}
if s.running() && s.Cfg.GetBool("watch") && !s.Cfg.GetBool("disableLiveReload") {
transformLinks = append(transformLinks, transform.LiveReloadInject(s.Cfg.GetInt("liveReloadPort")))
}
// For performance reasons we only inject the Hugo generator tag on the home page.
if p.IsHome() {
if !s.Cfg.GetBool("disableHugoGeneratorInject") {
transformLinks = append(transformLinks, transform.HugoGeneratorInject)
}
}
}
var path []byte
if s.Info.relativeURLs {
path = []byte(helpers.GetDottedRelativePath(dest))
} else if s.Info.canonifyURLs {
url := s.PathSpec.BaseURL.String()
if !strings.HasSuffix(url, "/") {
url += "/"
}
path = []byte(url)
}
transformer := transform.NewChain(transformLinks...)
if err := transformer.Apply(outBuffer, renderBuffer, path); err != nil {
s.DistinctErrorLog.Println(err)
return nil
}
return s.publish(statCounter, dest, outBuffer)
}
func (s *Site) renderForLayouts(name string, d interface{}, w io.Writer, layouts ...string) (err error) {
var templ tpl.Template
defer func() {
if r := recover(); r != nil {
templName := ""
if templ != nil {
templName = templ.Name()
}
s.DistinctErrorLog.Printf("Failed to render %q: %s", templName, r)
s.DistinctErrorLog.Printf("Stack Trace:\n%s", stackTrace(1200))
// TOD(bep) we really need to fix this. Also see below.
if !s.running() && !testMode {
os.Exit(-1)
}
}
}()
templ = s.findFirstTemplate(layouts...)
if templ == nil {
return fmt.Errorf("[%s] Unable to locate layout for %q: %s\n", s.Language.Lang, name, layouts)
}
if err = templ.Execute(w, d); err != nil {
// Behavior here should be dependent on if running in server or watch mode.
if p, ok := d.(*PageOutput); ok {
if p.File != nil {
s.DistinctErrorLog.Printf("Error while rendering %q in %q: %s", name, p.File.Dir(), err)
} else {
s.DistinctErrorLog.Printf("Error while rendering %q: %s", name, err)
}
} else {
s.DistinctErrorLog.Printf("Error while rendering %q: %s", name, err)
}
if !s.running() && !testMode {
// TODO(bep) check if this can be propagated
os.Exit(-1)
} else if testMode {
return
}
}
return
}
func (s *Site) findFirstTemplate(layouts ...string) tpl.Template {
for _, layout := range layouts {
if templ, found := s.Tmpl.Lookup(layout); found {
return templ
}
}
return nil
}
func (s *Site) publish(statCounter *uint64, path string, r io.Reader) (err error) {
s.PathSpec.ProcessingStats.Incr(statCounter)
return helpers.WriteToDisk(filepath.Clean(path), r, s.BaseFs.PublishFs)
}
func getGoMaxProcs() int {
if gmp := os.Getenv("GOMAXPROCS"); gmp != "" {
if p, err := strconv.Atoi(gmp); err != nil {
return p
}
}
return 1
}
func (s *Site) newNodePage(typ string, sections ...string) *Page {
p := &Page{
language: s.Language,
pageInit: &pageInit{},
pageContentInit: &pageContentInit{},
Kind: typ,
Source: Source{File: &source.FileInfo{}},
data: make(map[string]interface{}),
Site: &s.Info,
sections: sections,
s: s}
p.outputFormats = p.s.outputFormats[p.Kind]
return p
}
func (s *Site) newHomePage() *Page {
p := s.newNodePage(KindHome)
p.title = s.Info.Title
pages := Pages{}
p.data["Pages"] = pages
p.Pages = pages
return p
}
func (s *Site) newTaxonomyPage(plural, key string) *Page {
p := s.newNodePage(KindTaxonomy, plural, key)
if s.Info.preserveTaxonomyNames {
// Keep (mostly) as is in the title
// We make the first character upper case, mostly because
// it is easier to reason about in the tests.
p.title = helpers.FirstUpper(key)
key = s.PathSpec.MakePathSanitized(key)
} else {
p.title = strings.Replace(s.titleFunc(key), "-", " ", -1)
}
return p
}
func (s *Site) newSectionPage(name string) *Page {
p := s.newNodePage(KindSection, name)
sectionName := helpers.FirstUpper(name)
if s.Cfg.GetBool("pluralizeListTitles") {
p.title = inflect.Pluralize(sectionName)
} else {
p.title = sectionName
}
return p
}
func (s *Site) newTaxonomyTermsPage(plural string) *Page {
p := s.newNodePage(KindTaxonomyTerm, plural)
p.title = s.titleFunc(plural)
return p
}
|