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 seenDirs: 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 seenDirs 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 string
227 if dirPath != nil {
228 if isDir {
229 dpath = filepath.FromSlash(dirPath.Unnormalized().Path())
230 } else {
231 dpath = filepath.FromSlash(dirPath.Unnormalized().Dir())
232 }
233 }
234
235 if c.seenDirs[dpath] {
236 return nil
237 }
238 c.seenDirs[dpath] = true
239
240 root, err := c.fs.Stat(dpath)
241 if err != nil {
242 if os.IsNotExist(err) {
243 return nil
244 }
245 return err
246 }
247
248 rootm := root.(hugofs.FileMetaInfo)
249
250 if err := c.collectDirDir(dpath, rootm, inFilter); err != nil {
251 return err
252 }
253
254 return nil
255 }
256
257 func (c *pagesCollector) collectDirDir(path string, root hugofs.FileMetaInfo, inFilter func(fim hugofs.FileMetaInfo) bool) error {
258 ctx := context.Background()
259
260 filter := func(fim hugofs.FileMetaInfo) bool {
261 if inFilter != nil {
262 return inFilter(fim)
263 }
264 return true
265 }
266
267 preHook := func(ctx context.Context, dir hugofs.FileMetaInfo, path string, readdir []hugofs.FileMetaInfo) ([]hugofs.FileMetaInfo, error) {
268 filtered := readdir[:0]
269 for _, fi := range readdir {
270 if filter(fi) {
271 filtered = append(filtered, fi)
272 }
273 }
274 readdir = filtered
275 if len(readdir) == 0 {
276 return nil, nil
277 }
278
279 n := 0
280 for _, fi := range readdir {
281 if fi.Meta().PathInfo.IsContentData() {
282 // _content.json
283 // These are not part of any bundle, so just add them directly and remove them from the readdir slice.
284 if err := c.g.Enqueue(fi); err != nil {
285 return nil, err
286 }
287 } else {
288 readdir[n] = fi
289 n++
290 }
291 }
292 readdir = readdir[:n]
293
294 // Pick the first regular file.
295 var first hugofs.FileMetaInfo
296 for _, fi := range readdir {
297 if fi.IsDir() {
298 continue
299 }
300 first = fi
301 break
302 }
303
304 if first == nil {
305 // Only dirs, keep walking.
306 return readdir, nil
307 }
308
309 // Any bundle file will always be first.
310 firstPi := first.Meta().PathInfo
311
312 if firstPi == nil {
313 panic(fmt.Sprintf("collectDirDir: no path info for %q", first.Meta().Filename))
314 }
315
316 if firstPi.IsLeafBundle() {
317 if err := c.handleBundleLeaf(ctx, dir, path, readdir); err != nil {
318 return nil, err
319 }
320 return nil, filepath.SkipDir
321 }
322
323 // seen := map[types.Strings2]hugofs.FileMetaInfo{}
324 for _, fi := range readdir {
325 if fi.IsDir() {
326 continue
327 }
328
329 pi := fi.Meta().PathInfo
330 meta := fi.Meta()
331
332 if pi == nil {
333 panic(fmt.Sprintf("no path info for %q", meta.Filename))
334 }
335
336 if err := c.g.Enqueue(fi); err != nil {
337 return nil, err
338 }
339 }
340
341 // Keep walking.
342 return readdir, nil
343 }
344
345 var postHook hugofs.WalkHook
346
347 wfn := func(ctx context.Context, path string, fi hugofs.FileMetaInfo) error {
348 return nil
349 }
350
351 w := hugofs.NewWalkway(
352 hugofs.WalkwayConfig{
353 Logger: c.logger,
354 Root: path,
355 Info: root,
356 Fs: c.fs,
357 IgnoreFile: c.h.SourceSpec.IgnoreFile,
358 Ctx: ctx,
359 PathParser: c.h.Conf.PathParser(),
360 HookPre: preHook,
361 HookPost: postHook,
362 WalkFn: wfn,
363 })
364
365 return w.Walk()
366 }
367
368 func (c *pagesCollector) handleBundleLeaf(ctx context.Context, dir hugofs.FileMetaInfo, inPath string, readdir []hugofs.FileMetaInfo) error {
369 walk := func(ctx context.Context, path string, info hugofs.FileMetaInfo) error {
370 if info.IsDir() {
371 return nil
372 }
373
374 return c.g.Enqueue(info)
375 }
376
377 // Start a new walker from the given path.
378 w := hugofs.NewWalkway(
379 hugofs.WalkwayConfig{
380 Root: inPath,
381 Fs: c.fs,
382 Logger: c.logger,
383 Info: dir,
384 DirEntries: readdir,
385 Ctx: ctx,
386 IgnoreFile: c.h.SourceSpec.IgnoreFile,
387 PathParser: c.h.Conf.PathParser(),
388 WalkFn: walk,
389 })
390
391 return w.Walk()
392 }