forked from gohugoio/hugo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
site.go
2141 lines (1764 loc) · 54.1 KB
/
site.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
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
// Copyright 2016 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"
"strconv"
"strings"
"sync"
"time"
"github.com/spf13/hugo/config"
"github.com/spf13/hugo/media"
"github.com/bep/inflect"
"sync/atomic"
"github.com/fsnotify/fsnotify"
"github.com/spf13/afero"
"github.com/spf13/cast"
bp "github.com/spf13/hugo/bufferpool"
"github.com/spf13/hugo/deps"
"github.com/spf13/hugo/helpers"
"github.com/spf13/hugo/output"
"github.com/spf13/hugo/parser"
"github.com/spf13/hugo/source"
"github.com/spf13/hugo/tpl"
"github.com/spf13/hugo/transform"
"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
Files []*source.File
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/spf13/hugo/issues/2835
// Maps "actors-gerard-depardieu" to "Gérard Depardieu" when preserveTaxonomyNames
// is set.
taxonomiesOrigKey map[string]string
Source source.Input
Sections Taxonomy
Info SiteInfo
Menus Menus
timer *nitro.B
layoutHandler *output.LayoutHandler
draftCount int
futureCount int
expiredCount int
Data map[string]interface{}
Language *helpers.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
// Logger etc.
*deps.Deps `json:"-"`
siteStats *siteStats
}
type siteStats struct {
pageCount int
pageCountRegular int
}
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(s.PathSpec.ThemeSet()),
disabledKinds: s.disabledKinds,
outputFormats: s.outputFormats,
outputFormatsConfig: s.outputFormatsConfig,
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 = helpers.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
}
s := &Site{
PageCollections: c,
layoutHandler: output.NewLayoutHandler(cfg.Cfg.GetString("themesDir") != ""),
Language: cfg.Language,
disabledKinds: disabledKinds,
outputFormats: outputFormats,
outputFormatsConfig: siteOutputFormatsConfig,
mediaTypesConfig: siteMediaTypesConfig,
}
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.
func NewSiteDefaultLang(withTemplate ...func(templ tpl.TemplateHandler) error) (*Site, error) {
v := viper.New()
loadDefaultSettingsFor(v)
return newSiteForLang(helpers.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.
func NewEnglishSite(withTemplate ...func(templ tpl.TemplateHandler) error) (*Site, error) {
v := viper.New()
loadDefaultSettingsFor(v)
return newSiteForLang(helpers.NewLanguage("en", v), withTemplate...)
}
// newSiteForLang creates a new site in the given language.
func newSiteForLang(lang *helpers.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 SiteInfo struct {
// atomic requires 64-bit alignment for struct field access
// According to the docs, " The first word in a global variable or in an
// allocated struct or slice can be relied upon to be 64-bit aligned."
// Moving paginationPageCount to the top of this struct didn't do the
// magic, maybe due to the way SiteInfo is embedded.
// Adding the 4 byte padding below does the trick.
_ [4]byte
paginationPageCount uint64
Taxonomies TaxonomyList
Authors AuthorList
Social SiteSocial
Sections Taxonomy
*PageCollections
Files *[]*source.File
Menus *Menus
Hugo *HugoInfo
Title string
RSSLink string
Author map[string]interface{}
LanguageCode string
DisqusShortname string
GoogleAnalytics string
Copyright string
LastChange time.Time
Permalinks PermalinkOverrides
Params map[string]interface{}
BuildDrafts bool
canonifyURLs bool
relativeURLs bool
uglyURLs bool
preserveTaxonomyNames bool
Data *map[string]interface{}
owner *HugoSites
s *Site
multilingual *Multilingual
Language *helpers.Language
LanguagePrefix string
Languages helpers.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())
}
// Used in tests.
type siteBuilderCfg struct {
language *helpers.Language
s *Site
pageCollections *PageCollections
baseURL string
}
// 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{}),
}
}
// 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) refLink(ref string, page *Page, relative bool, outputFormat string) (string, error) {
var refURL *url.URL
var err error
refURL, err = url.Parse(ref)
if err != nil {
return "", err
}
var target *Page
var link string
if refURL.Path != "" {
for _, page := range s.AllRegularPages {
refPath := filepath.FromSlash(refURL.Path)
if page.Source.Path() == refPath || page.Source.LogicalName() == refPath {
target = page
break
}
}
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)
}
// SourceRelativeLink attempts to convert any source page relative links (like [../another.md]) into absolute links
func (s *SiteInfo) SourceRelativeLink(ref string, currentPage *Page) (string, error) {
var refURL *url.URL
var err error
refURL, err = url.Parse(strings.TrimPrefix(ref, currentPage.getRenderingConfig().SourceRelativeLinksProjectFolder))
if err != nil {
return "", err
}
if refURL.Scheme != "" {
// Not a relative source level path
return ref, nil
}
var target *Page
var link string
if refURL.Path != "" {
refPath := filepath.Clean(filepath.FromSlash(refURL.Path))
if strings.IndexRune(refPath, os.PathSeparator) == 0 { // filepath.IsAbs fails to me.
refPath = refPath[1:]
} else {
if currentPage != nil {
refPath = filepath.Join(currentPage.Source.Dir(), refURL.Path)
}
}
for _, page := range s.AllRegularPages {
if page.Source.Path() == refPath {
target = page
break
}
}
// need to exhaust the test, then try with the others :/
// if the refPath doesn't end in a filename with extension `.md`, then try with `.md` , and then `/index.md`
mdPath := strings.TrimSuffix(refPath, string(os.PathSeparator)) + ".md"
for _, page := range s.AllRegularPages {
if page.Source.Path() == mdPath {
target = page
break
}
}
indexPath := filepath.Join(refPath, "index.md")
for _, page := range s.AllRegularPages {
if page.Source.Path() == indexPath {
target = page
break
}
}
if target == nil {
return "", fmt.Errorf("No page found for \"%s\" on page \"%s\".\n", ref, currentPage.Source.Path())
}
link = target.RelPermalink()
}
if refURL.Fragment != "" {
link = link + "#" + refURL.Fragment
if refURL.Path != "" && target != nil && !target.getRenderingConfig().PlainIDAnchors {
link = link + ":" + target.UniqueID()
} else if currentPage != nil && !currentPage.getRenderingConfig().PlainIDAnchors {
link = link + ":" + currentPage.UniqueID()
}
}
return link, nil
}
// SourceRelativeLinkFile attempts to convert any non-md source relative links (like [../another.gif]) into absolute links
func (s *SiteInfo) SourceRelativeLinkFile(ref string, currentPage *Page) (string, error) {
var refURL *url.URL
var err error
refURL, err = url.Parse(strings.TrimPrefix(ref, currentPage.getRenderingConfig().SourceRelativeLinksProjectFolder))
if err != nil {
return "", err
}
if refURL.Scheme != "" {
// Not a relative source level path
return ref, nil
}
var target *source.File
var link string
if refURL.Path != "" {
refPath := filepath.Clean(filepath.FromSlash(refURL.Path))
if strings.IndexRune(refPath, os.PathSeparator) == 0 { // filepath.IsAbs fails to me.
refPath = refPath[1:]
} else {
if currentPage != nil {
refPath = filepath.Join(currentPage.Source.Dir(), refURL.Path)
}
}
for _, file := range *s.Files {
if file.Path() == refPath {
target = file
break
}
}
if target == nil {
return "", fmt.Errorf("No file found for \"%s\" on page \"%s\".\n", ref, currentPage.Source.Path())
}
link = target.Path()
return "/" + filepath.ToSlash(link), nil
}
return "", fmt.Errorf("failed to find a file to match \"%s\" on page \"%s\"", ref, currentPage.Source.Path())
}
func (s *SiteInfo) addToPaginationPageCount(cnt uint64) {
atomic.AddUint64(&s.paginationPageCount, cnt)
}
type runmode struct {
Watching bool
}
func (s *Site) running() bool {
return s.owner.runMode.Watching
}
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
}
// 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 {
// The last one will win if there are any duplicates.
_ = mime.AddExtensionType("."+mt.Suffix, mt.Type()+"; charset=utf-8")
}
}
// reBuild partially rebuilds a site given the filesystem events.
// It returns whetever the content source was changed.
func (s *Site) reProcess(events []fsnotify.Event) (whatChanged, error) {
s.Log.DEBUG.Printf("Rebuild for events %q", events)
s.timerStep("initialize rebuild")
// First we need to determine what changed
sourceChanged := []fsnotify.Event{}
sourceReallyChanged := []fsnotify.Event{}
tmplChanged := []fsnotify.Event{}
dataChanged := []fsnotify.Event{}
i18nChanged := []fsnotify.Event{}
shortcodesChanged := make(map[string]bool)
// prevent spamming the log on changes
logger := helpers.NewDistinctFeedbackLogger()
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.isContentDirEvent(ev) {
logger.Println("Source changed", ev.Name)
sourceChanged = append(sourceChanged, ev)
}
if s.isLayoutDirEvent(ev) {
logger.Println("Template changed", ev.Name)
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.Name)
dataChanged = append(dataChanged, ev)
}
if s.isI18nEvent(ev) {
logger.Println("i18n changed", ev.Name)
i18nChanged = append(dataChanged, ev)
}
}
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 {
s.Log.ERROR.Println(err)
}
s.Tmpl.PrintErrors()
for i := 1; i < len(sites); i++ {
site := sites[i]
var err error
site.Deps, err = first.Deps.ForLanguage(site.Language)
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)
}
}
// If a content file changes, we need to reload only it and re-render the entire site.
// First step is to read the changed files and (re)place them in site.AllPages
// This includes processing any meta-data for that content
// The second step is to convert the content into HTML
// This includes processing any shortcodes that may be present.
// We do this in parallel... even though it's likely only one file at a time.
// We need to process the reading prior to the conversion for each file, but
// we can convert one file while another one is still reading.
errs := make(chan error, 2)
readResults := make(chan HandledResult)
filechan := make(chan *source.File)
convertResults := make(chan HandledResult)
pageChan := make(chan *Page)
fileConvChan := make(chan *source.File)
coordinator := make(chan bool)
wg := &sync.WaitGroup{}
wg.Add(2)
for i := 0; i < 2; i++ {
go sourceReader(s, filechan, readResults, wg)
}
wg2 := &sync.WaitGroup{}
wg2.Add(4)
for i := 0; i < 2; i++ {
go fileConverter(s, fileConvChan, convertResults, wg2)
go pageConverter(pageChan, convertResults, wg2)
}
for _, ev := range sourceChanged {
// The incrementalReadCollator below will also make changes to the site's pages,
// so we do this first to prevent races.
if ev.Op&fsnotify.Remove == fsnotify.Remove {
//remove the file & a create will follow
path, _ := helpers.GetRelativePath(ev.Name, s.getContentDir(ev.Name))
s.removePageByPath(path)
continue
}
// 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 {
path, _ := helpers.GetRelativePath(ev.Name, s.getContentDir(ev.Name))
s.removePageByPath(path)
continue
}
}
sourceReallyChanged = append(sourceReallyChanged, ev)
}
go incrementalReadCollator(s, readResults, pageChan, fileConvChan, coordinator, errs)
go converterCollator(convertResults, errs)
for _, ev := range sourceReallyChanged {
file, err := s.reReadFile(ev.Name)
if err != nil {
s.Log.ERROR.Println("Error reading file", ev.Name, ";", err)
}
if file != nil {
filechan <- file
}
}
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 := s.findPagesByShortcode(shortcode)
for _, p := range pagesWithShortcode {
p.rendered = false
pageChan <- p
}
}
// we close the filechan as we have sent everything we want to send to it.
// this will tell the sourceReaders to stop iterating on that channel
close(filechan)
// waiting for the sourceReaders to all finish
wg.Wait()
// Now closing readResults as this will tell the incrementalReadCollator to
// stop iterating over that.
close(readResults)
// once readResults is finished it will close coordinator and move along
<-coordinator
// allow that routine to finish, then close page & fileconvchan as we've sent
// everything to them we need to.
close(pageChan)
close(fileConvChan)
wg2.Wait()
close(convertResults)
s.timerStep("read & convert pages from source")
for i := 0; i < 2; i++ {
err := <-errs
if err != nil {
s.Log.ERROR.Println(err)
}
}
changed := whatChanged{
source: len(sourceChanged) > 0,
other: len(tmplChanged) > 0 || len(i18nChanged) > 0 || len(dataChanged) > 0,
}
return changed, nil
}
func (s *Site) loadData(sources []source.Input) (err error) {
s.Log.DEBUG.Printf("Load Data from %d source(s)", len(sources))
s.Data = make(map[string]interface{})
var current map[string]interface{}
for _, currentSource := range sources {
for _, r := range currentSource.Files() {
// Crawl in data tree to insert data
current = s.Data
for _, key := range strings.Split(r.Dir(), helpers.FilePathSeparator) {
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 {
return fmt.Errorf("Failed to read data from %s: %s", filepath.Join(r.Path(), r.LogicalName()), err)
}
if data == nil {
continue
}
// Copy content from current to data when needed
if _, ok := current[r.BaseFileName()]; ok {
data := data.(map[string]interface{})
for key, value := range current[r.BaseFileName()].(map[string]interface{}) {
if _, override := data[key]; override {
// 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
s.Log.WARN.Printf("Data for key '%s' in path '%s' is overridden in subfolder", key, r.Path())
}
data[key] = value
}
}
// Insert data
current[r.BaseFileName()] = data
}
}
return
}
func (s *Site) readData(f *source.File) (interface{}, error) {
switch f.Extension() {
case "yaml", "yml":
return parser.HandleYAMLMetaData(f.Bytes())
case "json":
return parser.HandleJSONMetaData(f.Bytes())
case "toml":
return parser.HandleTOMLMetaData(f.Bytes())
default:
return nil, fmt.Errorf("Data not supported for extension '%s'", f.Extension())
}
}
func (s *Site) readDataFromSourceFS() error {
sp := source.NewSourceSpec(s.Cfg, s.Fs)
dataSources := make([]source.Input, 0, 2)
dataSources = append(dataSources, sp.NewFilesystem(s.absDataDir()))
// have to be last - duplicate keys in earlier entries will win
themeDataDir, err := s.PathSpec.GetThemeDataDirPath()
if err == nil {
dataSources = append(dataSources, sp.NewFilesystem(themeDataDir))
}
err = s.loadData(dataSources)
s.timerStep("load data")
return err
}
func (s *Site) process(config BuildCfg) (err error) {
s.timerStep("Go initialization")
if err = s.initialize(); err != nil {
return
}
s.timerStep("initialize")
if err = s.readDataFromSourceFS(); err != nil {
return
}
s.timerStep("load i18n")
return s.createPages()
}
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() (err error) {
if err = s.preparePages(); err != nil {
return
}
s.timerStep("prepare pages")
// 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(); err != nil {
return
}
s.timerStep("render and write pages")
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) {
defer s.initializeSiteInfo()
s.Menus = Menus{}
// May be supplied in tests.
if s.Source != nil && len(s.Source.Files()) > 0 {
s.Log.DEBUG.Println("initialize: Source is already set")
return
}
if err = s.checkDirectories(); err != nil {
return err
}