Debian Codegraph @

hugolib/pages_capture.go

raw
1 // Copyright 2021 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 hugolib
15
16 import (
17 "context"
18 "fmt"
19 "os"
20 "path/filepath"
21 "strings"
22 "sync"
23 "sync/atomic"
24 "time"
25
26 "github.com/bep/logg"
27 "github.com/gohugoio/hugo/common/paths"
28 "github.com/gohugoio/hugo/common/rungroup"
29 "github.com/spf13/afero"
30
31 "github.com/gohugoio/hugo/source"
32
33 "github.com/gohugoio/hugo/common/loggers"
34 "github.com/gohugoio/hugo/hugofs"
35 )
36
37 func newPagesCollector(
38 ctx context.Context,
39 h *HugoSites,
40 sp *source.SourceSpec,
41 logger loggers.Logger,
42 infoLogger logg.LevelLogger,
43 m *pageMap,
44 buildConfig *BuildCfg,
45 ids []pathChange,
46 ) *pagesCollector {
47 return &pagesCollector{
48 ctx: ctx,
49 h: h,
50 fs: sp.BaseFs.Content.Fs,
51 m: m,
52 sp: sp,
53 logger: logger,
54 infoLogger: infoLogger,
55 buildConfig: buildConfig,
56 ids: ids,
57 seen: make(map[string]bool),
58 }
59 }
60
61 type pagesCollector struct {
62 ctx context.Context
63 h *HugoSites
64 sp *source.SourceSpec
65 logger loggers.Logger
66 infoLogger logg.LevelLogger
67
68 m *pageMap
69
70 fs afero.Fs
71
72 buildConfig *BuildCfg
73
74 // List of paths that have changed. Used in partial builds.
75 ids []pathChange
76 seen map[string]bool
77
78 g rungroup.Group[hugofs.FileMetaInfo]
79 }
80
81 // Collect collects content by walking the file system and storing
82 // it in the content tree.
83 // It may be restricted by filenames set on the collector (partial build).
84 func (c *pagesCollector) Collect() (collectErr error) {
85 var (
86 numWorkers = c.h.numWorkers
87 numFilesProcessedTotal atomic.Uint64
88 numPageSourcesProcessedTotal atomic.Uint64
89 numResourceSourcesProcessed atomic.Uint64
90 numFilesProcessedLast uint64
91 fileBatchTimer = time.Now()
92 fileBatchTimerMu sync.Mutex
93 )
94
95 l := c.infoLogger.WithField("substep", "collect")
96
97 logFilesProcessed := func(force bool) {
98 fileBatchTimerMu.Lock()
99 if force || time.Since(fileBatchTimer) > 3*time.Second {
100 numFilesProcessedBatch := numFilesProcessedTotal.Load() - numFilesProcessedLast
101 numFilesProcessedLast = numFilesProcessedTotal.Load()
102 loggers.TimeTrackf(l, fileBatchTimer,
103 logg.Fields{
104 logg.Field{Name: "files", Value: numFilesProcessedBatch},
105 logg.Field{Name: "files_total", Value: numFilesProcessedTotal.Load()},
106 logg.Field{Name: "pagesources_total", Value: numPageSourcesProcessedTotal.Load()},
107 logg.Field{Name: "resourcesources_total", Value: numResourceSourcesProcessed.Load()},
108 },
109 "",
110 )
111 fileBatchTimer = time.Now()
112 }
113 fileBatchTimerMu.Unlock()
114 }
115
116 defer func() {
117 logFilesProcessed(true)
118 }()
119
120 c.g = rungroup.Run(c.ctx, rungroup.Config[hugofs.FileMetaInfo]{
121 NumWorkers: numWorkers,
122 Handle: func(ctx context.Context, fi hugofs.FileMetaInfo) error {
123 numPageSources, numResourceSources, err := c.m.AddFi(fi, c.buildConfig)
124 if err != nil {
125 return hugofs.AddFileInfoToError(err, fi, c.h.SourceFs)
126 }
127 numFilesProcessedTotal.Add(1)
128 numPageSourcesProcessedTotal.Add(numPageSources)
129 numResourceSourcesProcessed.Add(numResourceSources)
130 if numFilesProcessedTotal.Load()%1000 == 0 {
131 logFilesProcessed(false)
132 }
133
134 return nil
135 },
136 })
137
138 if c.ids == nil {
139 // Collect everything.
140 collectErr = c.collectDir(nil, false, nil)
141 } else {
142 for _, s := range c.h.Sites {
143 s.pageMap.cfg.isRebuild = true
144 }
145
146 var hasStructuralChange bool
147 for _, id := range c.ids {
148 if id.isStructuralChange() {
149 hasStructuralChange = true
150 break
151 }
152 }
153
154 for _, id := range c.ids {
155 if id.p.IsLeafBundle() {
156 collectErr = c.collectDir(
157 id.p,
158 false,
159 func(fim hugofs.FileMetaInfo) bool {
160 if hasStructuralChange {
161 return true
162 }
163 fimp := fim.Meta().PathInfo
164 if fimp == nil {
165 return true
166 }
167
168 return fimp.Path() == id.p.Path()
169 },
170 )
171 } else if id.p.IsBranchBundle() {
172 collectErr = c.collectDir(
173 id.p,
174 false,
175 func(fim hugofs.FileMetaInfo) bool {
176 if fim.IsDir() {
177 return id.isStructuralChange()
178 }
179 fimp := fim.Meta().PathInfo
180 if fimp == nil {
181 return false
182 }
183
184 return strings.HasPrefix(fimp.Path(), paths.AddTrailingSlash(id.p.Dir()))
185 },
186 )
187 } else {
188 // We always start from a directory.
189 collectErr = c.collectDir(id.p, id.isDir, func(fim hugofs.FileMetaInfo) bool {
190 if id.isStructuralChange() {
191 if id.isDir && fim.Meta().PathInfo.IsLeafBundle() {
192 return strings.HasPrefix(fim.Meta().PathInfo.Path(), paths.AddTrailingSlash(id.p.Path()))
193 }
194
195 if id.p.IsContentData() {
196 return strings.HasPrefix(fim.Meta().PathInfo.Path(), paths.AddTrailingSlash(id.p.Dir()))
197 }
198
199 return id.p.Dir() == fim.Meta().PathInfo.Dir()
200 }
201
202 if fim.Meta().PathInfo.IsLeafBundle() && id.p.Type() == paths.TypeContentSingle {
203 return id.p.Dir() == fim.Meta().PathInfo.Dir()
204 }
205
206 return id.p.Path() == fim.Meta().PathInfo.Path()
207 })
208 }
209
210 if collectErr != nil {
211 break
212 }
213 }
214
215 }
216
217 werr := c.g.Wait()
218 if collectErr == nil {
219 collectErr = werr
220 }
221
222 return
223 }
224
225 func (c *pagesCollector) collectDir(dirPath *paths.Path, isDir bool, inFilter func(fim hugofs.FileMetaInfo) bool) error {
226 var dpath, key string
227 if dirPath != nil {
228 // Several changed files may live in the same directory, each collected
229 // with its own filter, so dedupe on the path, not the directory.
230 key = dirPath.Path()
231 if isDir {
232 dpath = filepath.FromSlash(dirPath.Unnormalized().Path())
233 } else {
234 dpath = filepath.FromSlash(dirPath.Unnormalized().Dir())
235 }
236 }
237
238 if c.seen[key] {
239 return nil
240 }
241 c.seen[key] = true
242
243 root, err := c.fs.Stat(dpath)
244 if err != nil {
245 if os.IsNotExist(err) {
246 return nil
247 }
248 return err
249 }
250
251 rootm := root.(hugofs.FileMetaInfo)
252
253 if err := c.collectDirDir(dpath, rootm, inFilter); err != nil {
254 return err
255 }
256
257 return nil
258 }
259
260 func (c *pagesCollector) collectDirDir(path string, root hugofs.FileMetaInfo, inFilter func(fim hugofs.FileMetaInfo) bool) error {
261 ctx := context.Background()
262
263 filter := func(fim hugofs.FileMetaInfo) bool {
264 if inFilter != nil {
265 return inFilter(fim)
266 }
267 return true
268 }
269
270 preHook := func(ctx context.Context, dir hugofs.FileMetaInfo, path string, readdir []hugofs.FileMetaInfo) ([]hugofs.FileMetaInfo, error) {
271 filtered := readdir[:0]
272 for _, fi := range readdir {
273 if filter(fi) {
274 filtered = append(filtered, fi)
275 }
276 }
277 readdir = filtered
278 if len(readdir) == 0 {
279 return nil, nil
280 }
281
282 n := 0
283 for _, fi := range readdir {
284 if fi.Meta().PathInfo.IsContentData() {
285 // _content.json
286 // These are not part of any bundle, so just add them directly and remove them from the readdir slice.
287 if err := c.g.Enqueue(fi); err != nil {
288 return nil, err
289 }
290 } else {
291 readdir[n] = fi
292 n++
293 }
294 }
295 readdir = readdir[:n]
296
297 // Pick the first regular file.
298 var first hugofs.FileMetaInfo
299 for _, fi := range readdir {
300 if fi.IsDir() {
301 continue
302 }
303 first = fi
304 break
305 }
306
307 if first == nil {
308 // Only dirs, keep walking.
309 return readdir, nil
310 }
311
312 // Any bundle file will always be first.
313 firstPi := first.Meta().PathInfo
314
315 if firstPi == nil {
316 panic(fmt.Sprintf("collectDirDir: no path info for %q", first.Meta().Filename))
317 }
318
319 if firstPi.IsLeafBundle() {
320 if err := c.handleBundleLeaf(ctx, dir, path, readdir); err != nil {
321 return nil, err
322 }
323 return nil, filepath.SkipDir
324 }
325
326 // seen := map[types.Strings2]hugofs.FileMetaInfo{}
327 for _, fi := range readdir {
328 if fi.IsDir() {
329 continue
330 }
331
332 pi := fi.Meta().PathInfo
333 meta := fi.Meta()
334
335 if pi == nil {
336 panic(fmt.Sprintf("no path info for %q", meta.Filename))
337 }
338
339 if err := c.g.Enqueue(fi); err != nil {
340 return nil, err
341 }
342 }
343
344 // Keep walking.
345 return readdir, nil
346 }
347
348 var postHook hugofs.WalkHook
349
350 wfn := func(ctx context.Context, path string, fi hugofs.FileMetaInfo) error {
351 return nil
352 }
353
354 w := hugofs.NewWalkway(
355 hugofs.WalkwayConfig{
356 Logger: c.logger,
357 Root: path,
358 Info: root,
359 Fs: c.fs,
360 IgnoreFile: c.h.SourceSpec.IgnoreFile,
361 Ctx: ctx,
362 PathParser: c.h.Conf.PathParser(),
363 HookPre: preHook,
364 HookPost: postHook,
365 WalkFn: wfn,
366 })
367
368 return w.Walk()
369 }
370
371 func (c *pagesCollector) handleBundleLeaf(ctx context.Context, dir hugofs.FileMetaInfo, inPath string, readdir []hugofs.FileMetaInfo) error {
372 walk := func(ctx context.Context, path string, info hugofs.FileMetaInfo) error {
373 if info.IsDir() {
374 return nil
375 }
376
377 return c.g.Enqueue(info)
378 }
379
380 // Start a new walker from the given path.
381 w := hugofs.NewWalkway(
382 hugofs.WalkwayConfig{
383 Root: inPath,
384 Fs: c.fs,
385 Logger: c.logger,
386 Info: dir,
387 DirEntries: readdir,
388 Ctx: ctx,
389 IgnoreFile: c.h.SourceSpec.IgnoreFile,
390 PathParser: c.h.Conf.PathParser(),
391 WalkFn: walk,
392 })
393
394 return w.Walk()
395 }