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