Debian Codegraph @

hugolib/pagesfromdata/pagesfromgotmpl.go

raw
1 // Copyright 2024 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package pagesfromdata
15
16 import (
17 "context"
18 "fmt"
19 "io"
20
21 "github.com/gohugoio/hugo/common/hashing"
22 "github.com/gohugoio/hugo/common/hmaps"
23 "github.com/gohugoio/hugo/common/hstore"
24 "github.com/gohugoio/hugo/common/paths"
25 "github.com/gohugoio/hugo/helpers"
26 "github.com/gohugoio/hugo/hugofs"
27 "github.com/gohugoio/hugo/identity"
28 "github.com/gohugoio/hugo/resources/page"
29 "github.com/gohugoio/hugo/resources/page/pagemeta"
30 "github.com/gohugoio/hugo/resources/resource"
31 "github.com/gohugoio/hugo/tpl"
32 "github.com/gohugoio/hugo/tpl/tplimpl"
33 "github.com/mitchellh/mapstructure"
34 "github.com/spf13/cast"
35 )
36
37 type PagesFromDataTemplateContext interface {
38 // AddPage adds a new page to the site.
39 // The first return value will always be an empty string.
40 AddPage(any) (string, error)
41
42 // AddResource adds a new resource to the site.
43 // The first return value will always be an empty string.
44 AddResource(any) (string, error)
45
46 // The site to which the pages will be added.
47 Site() page.Site
48
49 // The same template may be executed multiple times for multiple languages.
50 // The Store can be used to store state between these invocations.
51 Store() *hstore.Scratch
52
53 // By default, the template will be executed for the language
54 // defined by the _content.gotmpl file (e.g. its mount definition).
55 // This method can be used to activate the template for all languages.
56 // The return value will always be an empty string.
57 EnableAllLanguages() string
58 }
59
60 var _ PagesFromDataTemplateContext = (*pagesFromDataTemplateContext)(nil)
61
62 type pagesFromDataTemplateContext struct {
63 p *PagesFromTemplate
64 }
65
66 func (p *pagesFromDataTemplateContext) toPathSitesMap(v any) (string, map[string]any, map[string]any, error) {
67 m, err := hmaps.ToStringMapE(v)
68 if err != nil {
69 return "", nil, nil, err
70 }
71
72 path, err := cast.ToStringE(m["path"])
73 if err != nil {
74 return "", nil, nil, fmt.Errorf("invalid path %q", path)
75 }
76
77 sites := hmaps.ToStringMap(m["sites"])
78
79 return path, sites, m, nil
80 }
81
82 func (p *pagesFromDataTemplateContext) AddPage(v any) (string, error) {
83 path, sites, m, err := p.toPathSitesMap(v)
84 if err != nil {
85 return "", err
86 }
87
88 hash, hasChanged := p.p.buildState.checkHasChangedAndSetSourceInfo(path, sites, m)
89 if !hasChanged {
90 return "", nil
91 }
92
93 pe := &pagemeta.PageConfigEarly{
94 IsFromContentAdapter: true,
95 Frontmatter: m,
96 SourceEntryHash: hash,
97 }
98
99 // The rest will be handled after the cascade is calculated and applied.
100 if err := mapstructure.WeakDecode(pe.Frontmatter, pe); err != nil {
101 err = fmt.Errorf("failed to decode page map: %w", err)
102 return "", err
103 }
104
105 if err := pe.Init(true); err != nil {
106 return "", err
107 }
108
109 p.p.buildState.NumPagesAdded++
110
111 return "", p.p.HandlePage(p.p, pe)
112 }
113
114 func (p *pagesFromDataTemplateContext) AddResource(v any) (string, error) {
115 path, sites, m, err := p.toPathSitesMap(v)
116 if err != nil {
117 return "", err
118 }
119
120 hash, hasChanged := p.p.buildState.checkHasChangedAndSetSourceInfo(path, sites, m)
121 if !hasChanged {
122 return "", nil
123 }
124
125 var rd pagemeta.ResourceConfig
126 if err := mapstructure.WeakDecode(m, &rd); err != nil {
127 return "", err
128 }
129 rd.ContentAdapterSourceEntryHash = hash
130
131 p.p.buildState.NumResourcesAdded++
132
133 if err := rd.Validate(); err != nil {
134 return "", err
135 }
136
137 return "", p.p.HandleResource(p.p, &rd)
138 }
139
140 func (p *pagesFromDataTemplateContext) Site() page.Site {
141 return p.p.Site
142 }
143
144 func (p *pagesFromDataTemplateContext) Store() *hstore.Scratch {
145 return p.p.store
146 }
147
148 func (p *pagesFromDataTemplateContext) EnableAllLanguages() string {
149 p.p.buildState.EnableAllLanguages = true
150 return ""
151 }
152
153 func (p *pagesFromDataTemplateContext) EnableAllDimensions() string {
154 p.p.buildState.EnableAllDimensions = true
155 return ""
156 }
157
158 func NewPagesFromTemplate(opts PagesFromTemplateOptions) *PagesFromTemplate {
159 return &PagesFromTemplate{
160 PagesFromTemplateOptions: opts,
161 PagesFromTemplateDeps: opts.DepsFromSite(opts.Site),
162 buildState: &BuildState{
163 sourceInfosCurrent: hmaps.NewCache[string, *sourceInfo](),
164 },
165 store: hstore.NewScratch(),
166 }
167 }
168
169 type PagesFromTemplateOptions struct {
170 Site page.Site
171 DepsFromSite func(page.Site) PagesFromTemplateDeps
172
173 DependencyManager identity.Manager
174
175 Watching bool
176
177 HandlePage func(pt *PagesFromTemplate, p *pagemeta.PageConfigEarly) error
178 HandleResource func(pt *PagesFromTemplate, p *pagemeta.ResourceConfig) error
179
180 GoTmplFi hugofs.FileMetaInfo
181 }
182
183 type PagesFromTemplateDeps struct {
184 TemplateStore *tplimpl.TemplateStore
185 }
186
187 var _ resource.Staler = (*PagesFromTemplate)(nil)
188
189 type PagesFromTemplate struct {
190 PagesFromTemplateOptions
191 PagesFromTemplateDeps
192 buildState *BuildState
193 store *hstore.Scratch
194 }
195
196 func (b *PagesFromTemplate) AddChange(id identity.Identity) {
197 b.buildState.ChangedIdentities = append(b.buildState.ChangedIdentities, id)
198 }
199
200 func (b *PagesFromTemplate) MarkStale() {
201 b.buildState.StaleVersion++
202 }
203
204 func (b *PagesFromTemplate) StaleVersion() uint32 {
205 return b.buildState.StaleVersion
206 }
207
208 type BuildInfo struct {
209 NumPagesAdded uint64
210 NumResourcesAdded uint64
211 EnableAllLanguages bool
212 EnableAllDimensions bool
213 ChangedIdentities []identity.Identity
214 DeletedPaths []PathHashes
215 Path *paths.Path
216 }
217
218 type BuildState struct {
219 StaleVersion uint32
220
221 EnableAllLanguages bool
222 EnableAllDimensions bool
223
224 // PathHashes deleted in the current build.
225 DeletedPaths []PathHashes
226
227 // Changed identities in the current build.
228 ChangedIdentities []identity.Identity
229
230 NumPagesAdded uint64
231 NumResourcesAdded uint64
232
233 sourceInfosCurrent *hmaps.Cache[string, *sourceInfo]
234 sourceInfosPrevious *hmaps.Cache[string, *sourceInfo]
235 }
236
237 func (b *BuildState) hash(v any) uint64 {
238 return hashing.HashUint64(v)
239 }
240
241 type sourceInfo struct {
242 siteHashes map[uint64]uint64
243 }
244
245 func (b *BuildState) checkHasChangedAndSetSourceInfo(changedPath string, sites map[string]any, v any) (uint64, bool) {
246 hv := b.hash(v)
247 hsites := b.hash(sites)
248
249 si, _ := b.sourceInfosCurrent.GetOrCreate(changedPath, func() (*sourceInfo, error) {
250 return &sourceInfo{
251 siteHashes: make(map[uint64]uint64),
252 }, nil
253 })
254
255 if h, found := si.siteHashes[hsites]; found && h == hv {
256 return hv, false
257 }
258
259 if psi, found := b.sourceInfosPrevious.Get(changedPath); found {
260 if h, found := psi.siteHashes[hsites]; found && h == hv {
261 // Not changed.
262 si.siteHashes[hsites] = hv
263 return hv, false
264 }
265 }
266
267 // It has changed.
268 si.siteHashes[hsites] = hv
269 return hv, true
270 }
271
272 type PathHashes struct {
273 Path string
274 Hashes map[uint64]struct{}
275 }
276
277 func (b *BuildState) resolveDeletedPaths() {
278 if b.sourceInfosPrevious == nil {
279 b.DeletedPaths = nil
280 return
281 }
282 var pathsHashes []PathHashes
283 b.sourceInfosPrevious.ForEeach(func(k string, pv *sourceInfo) bool {
284 if cv, found := b.sourceInfosCurrent.Get(k); !found {
285 pathsHashes = append(pathsHashes, PathHashes{Path: k, Hashes: map[uint64]struct{}{}})
286 } else {
287 deleted := map[uint64]struct{}{}
288 for k, ph := range pv.siteHashes {
289 ch, found := cv.siteHashes[k]
290 if !found || ch != ph {
291 deleted[ph] = struct{}{}
292 }
293 }
294 if len(deleted) > 0 {
295 pathsHashes = append(pathsHashes, PathHashes{Path: k, Hashes: deleted})
296 }
297 }
298 return true
299 })
300
301 b.DeletedPaths = pathsHashes
302 }
303
304 func (b *BuildState) PrepareNextBuild() {
305 b.sourceInfosPrevious = b.sourceInfosCurrent
306 b.sourceInfosCurrent = hmaps.NewCache[string, *sourceInfo]()
307 b.StaleVersion = 0
308 b.DeletedPaths = nil
309 b.ChangedIdentities = nil
310 b.NumPagesAdded = 0
311 b.NumResourcesAdded = 0
312 }
313
314 func (p PagesFromTemplate) CloneForSite(s page.Site) *PagesFromTemplate {
315 // We deliberately make them share the same DependencyManager and Store.
316 p.PagesFromTemplateOptions.Site = s
317 p.PagesFromTemplateDeps = p.PagesFromTemplateOptions.DepsFromSite(s)
318 p.buildState = &BuildState{
319 sourceInfosCurrent: hmaps.NewCache[string, *sourceInfo](),
320 }
321 return &p
322 }
323
324 func (p PagesFromTemplate) CloneForGoTmpl(fi hugofs.FileMetaInfo) *PagesFromTemplate {
325 p.PagesFromTemplateOptions.GoTmplFi = fi
326 return &p
327 }
328
329 func (p *PagesFromTemplate) GetDependencyManagerForScope(scope int) identity.Manager {
330 return p.DependencyManager
331 }
332
333 func (p *PagesFromTemplate) GetDependencyManagerForScopesAll() []identity.Manager {
334 return []identity.Manager{p.DependencyManager}
335 }
336
337 func (p *PagesFromTemplate) Execute(ctx context.Context) (BuildInfo, error) {
338 defer func() {
339 p.buildState.PrepareNextBuild()
340 }()
341
342 f, err := p.GoTmplFi.Meta().Open()
343 if err != nil {
344 return BuildInfo{}, err
345 }
346 defer f.Close()
347
348 tmpl, err := p.TemplateStore.TextParse(p.GoTmplFi.Meta().PathInfo.Path(), helpers.ReaderToString(f))
349 if err != nil {
350 return BuildInfo{}, err
351 }
352
353 data := &pagesFromDataTemplateContext{
354 p: p,
355 }
356
357 ctx = tpl.Context.DependencyManagerScopedProvider.Set(ctx, p)
358
359 if err := p.TemplateStore.ExecuteWithContext(ctx, tmpl, io.Discard, data); err != nil {
360 return BuildInfo{}, err
361 }
362
363 if p.Watching {
364 p.buildState.resolveDeletedPaths()
365 }
366
367 bi := BuildInfo{
368 NumPagesAdded: p.buildState.NumPagesAdded,
369 NumResourcesAdded: p.buildState.NumResourcesAdded,
370 EnableAllLanguages: p.buildState.EnableAllLanguages,
371 EnableAllDimensions: p.buildState.EnableAllDimensions,
372 ChangedIdentities: p.buildState.ChangedIdentities,
373 DeletedPaths: p.buildState.DeletedPaths,
374 Path: p.GoTmplFi.Meta().PathInfo,
375 }
376
377 return bi, nil
378 }