Debian Codegraph @

hugofs/fileinfo.go

raw
1 // Copyright 2019 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 hugofs provides the file systems used by Hugo.
15 package hugofs
16
17 import (
18 "errors"
19 "fmt"
20 "io"
21 "io/fs"
22 "os"
23 "path/filepath"
24 "reflect"
25 "runtime"
26 "sort"
27 "sync"
28 "time"
29
30 "github.com/gohugoio/hugo/hugofs/hglob"
31 "github.com/gohugoio/hugo/hugolib/sitesmatrix"
32
33 "golang.org/x/text/unicode/norm"
34
35 "github.com/gohugoio/hugo/common/herrors"
36 "github.com/gohugoio/hugo/common/hreflect"
37 "github.com/gohugoio/hugo/common/htime"
38 "github.com/gohugoio/hugo/common/paths"
39
40 "github.com/spf13/afero"
41 )
42
43 func NewFileMeta() *FileMeta {
44 return &FileMeta{}
45 }
46
47 // A subset of modules.Module used to avoid circular dependencies.
48 // Note that it's safe to type assert to the full modules.Module when needed.
49 type Module interface {
50 // Returns the path to this module.
51 // This will either be the module path, e.g. "github.com/gohugoio/myshortcodes",
52 // or the path below your /theme folder, e.g. "mytheme".
53 Path() string
54
55 // Directory holding files for this module.
56 Dir() string
57
58 // Returns whether this is a Go Module.
59 IsGoMod() bool
60
61 // The module version.
62 Version() string
63 }
64
65 // FileMeta holds metadata about a file or directory.
66 type FileMeta struct {
67 PathInfo *paths.Path
68 Name string
69 Filename string
70
71 BaseDir string
72 SourceRoot string
73 Module Module
74 ModuleOrdinal int
75 Component string
76
77 Weight int
78 IsProject bool
79 Watch bool
80
81 // This file/directory will be built for these sites.
82 SitesMatrix sitesmatrix.VectorStore
83
84 // This file/directory complements these other sites.
85 SitesComplements sitesmatrix.VectorStore
86
87 OpenFunc func() (afero.File, error)
88 JoinStatFunc func(name string) (FileMetaInfo, error)
89
90 // Include only files or directories that match.
91 InclusionFilter *hglob.FilenameFilter
92
93 // Rename the name part of the file (not the directory).
94 // Returns the new name and a boolean indicating if the file
95 // should be included.
96 Rename func(name string, toFrom bool) (string, bool)
97 }
98
99 func (m *FileMeta) Copy() *FileMeta {
100 if m == nil {
101 return NewFileMeta()
102 }
103 c := *m
104 return &c
105 }
106
107 func (m *FileMeta) Merge(from *FileMeta) {
108 if m == nil || from == nil {
109 return
110 }
111 dstv := reflect.Indirect(reflect.ValueOf(m))
112 srcv := reflect.Indirect(reflect.ValueOf(from))
113
114 for i := range dstv.NumField() {
115 v := dstv.Field(i)
116 if !v.CanSet() {
117 continue
118 }
119 if !hreflect.IsTruthfulValue(v) {
120 v.Set(srcv.Field(i))
121 }
122 }
123
124 if m.InclusionFilter == nil {
125 m.InclusionFilter = from.InclusionFilter
126 }
127 }
128
129 func (f *FileMeta) Open() (afero.File, error) {
130 if f.OpenFunc == nil {
131 return nil, errors.New("OpenFunc not set")
132 }
133 return f.OpenFunc()
134 }
135
136 func (f *FileMeta) ReadAll() ([]byte, error) {
137 file, err := f.Open()
138 if err != nil {
139 return nil, err
140 }
141 defer file.Close()
142 return io.ReadAll(file)
143 }
144
145 func (f *FileMeta) JoinStat(name string) (FileMetaInfo, error) {
146 if f.JoinStatFunc == nil {
147 return nil, os.ErrNotExist
148 }
149 return f.JoinStatFunc(name)
150 }
151
152 func (m *FileMeta) ModulePath() string {
153 if m.Module == nil {
154 return ""
155 }
156 return m.Module.Path()
157 }
158
159 func (m *FileMeta) MatchSiteVectorCoarse(v sitesmatrix.Vector) bool {
160 language := v.Language()
161 if !(m.SitesMatrix.HasLanguage(language) || m.SitesComplements.HasLanguage(language)) {
162 return false
163 }
164
165 return m.MatchSiteVectorCoarseExcludeLanguage(v)
166 }
167
168 func (m *FileMeta) MatchSiteVectorCoarseExcludeLanguage(v sitesmatrix.Vector) bool {
169 version := v.Version()
170 if !(m.SitesMatrix.HasVersion(version) || m.SitesComplements.HasVersion(version)) {
171 return false
172 }
173
174 role := v.Role()
175 // lint:ignore S1008 preserve the symmetry from above.
176 if !(m.SitesMatrix.HasRole(role) || m.SitesComplements.HasRole(role)) {
177 return false
178 }
179
180 return true
181 }
182
183 type FileMetaInfo interface {
184 fs.DirEntry
185 MetaProvider
186
187 // This is a real hybrid as it also implements the fs.FileInfo interface.
188 FileInfoOptionals
189 }
190
191 type MetaProvider interface {
192 Meta() *FileMeta
193 }
194
195 type FileInfoOptionals interface {
196 Size() int64
197 Mode() fs.FileMode
198 ModTime() time.Time
199 Sys() any
200 }
201
202 type FileNameIsDir interface {
203 Name() string
204 IsDir() bool
205 }
206
207 type FileInfoProvider interface {
208 FileInfo() FileMetaInfo
209 }
210
211 // DirOnlyOps is a subset of the afero.File interface covering
212 // the methods needed for directory operations.
213 type DirOnlyOps interface {
214 io.Closer
215 Name() string
216 Readdir(count int) ([]os.FileInfo, error)
217 Readdirnames(n int) ([]string, error)
218 Stat() (os.FileInfo, error)
219 }
220
221 type dirEntryMeta struct {
222 fs.DirEntry
223 m *FileMeta
224
225 fi fs.FileInfo
226 fiInit sync.Once
227 }
228
229 func (fi *dirEntryMeta) Meta() *FileMeta {
230 return fi.m
231 }
232
233 // Filename returns the full filename.
234 func (fi *dirEntryMeta) Filename() string {
235 return fi.m.Filename
236 }
237
238 func (fi *dirEntryMeta) fileInfo() fs.FileInfo {
239 var err error
240 fi.fiInit.Do(func() {
241 fi.fi, err = fi.DirEntry.Info()
242 })
243 if err != nil {
244 panic(err)
245 }
246 return fi.fi
247 }
248
249 func (fi *dirEntryMeta) Size() int64 {
250 return fi.fileInfo().Size()
251 }
252
253 func (fi *dirEntryMeta) Mode() fs.FileMode {
254 return fi.fileInfo().Mode()
255 }
256
257 func (fi *dirEntryMeta) ModTime() time.Time {
258 return fi.fileInfo().ModTime()
259 }
260
261 func (fi *dirEntryMeta) Sys() any {
262 return fi.fileInfo().Sys()
263 }
264
265 // Name returns the file's name.
266 func (fi *dirEntryMeta) Name() string {
267 if name := fi.m.Name; name != "" {
268 return name
269 }
270 return fi.DirEntry.Name()
271 }
272
273 // dirEntry is an adapter from os.FileInfo to fs.DirEntry
274 type dirEntry struct {
275 fs.FileInfo
276 }
277
278 var _ fs.DirEntry = dirEntry{}
279
280 func (d dirEntry) Type() fs.FileMode { return d.FileInfo.Mode().Type() }
281
282 func (d dirEntry) Info() (fs.FileInfo, error) { return d.FileInfo, nil }
283
284 func NewFileMetaInfo(fi FileNameIsDir, m *FileMeta) FileMetaInfo {
285 if m == nil {
286 panic("FileMeta must be set")
287 }
288 if fim, ok := fi.(MetaProvider); ok {
289 m.Merge(fim.Meta())
290 }
291 switch v := fi.(type) {
292 case fs.DirEntry:
293 return &dirEntryMeta{DirEntry: v, m: m}
294 case fs.FileInfo:
295 return &dirEntryMeta{DirEntry: dirEntry{v}, m: m}
296 case nil:
297 return &dirEntryMeta{DirEntry: dirEntry{}, m: m}
298 default:
299 panic(fmt.Sprintf("Unsupported type: %T", fi))
300 }
301 }
302
303 type dirNameOnlyFileInfo struct {
304 name string
305 modTime time.Time
306 }
307
308 func (fi *dirNameOnlyFileInfo) Name() string {
309 return fi.name
310 }
311
312 func (fi *dirNameOnlyFileInfo) Size() int64 {
313 panic("not implemented")
314 }
315
316 func (fi *dirNameOnlyFileInfo) Mode() os.FileMode {
317 return os.ModeDir
318 }
319
320 func (fi *dirNameOnlyFileInfo) ModTime() time.Time {
321 return fi.modTime
322 }
323
324 func (fi *dirNameOnlyFileInfo) IsDir() bool {
325 return true
326 }
327
328 func (fi *dirNameOnlyFileInfo) Sys() any {
329 return nil
330 }
331
332 func newDirNameOnlyFileInfo(name string, meta *FileMeta, fileOpener func() (afero.File, error)) FileMetaInfo {
333 name = normalizeFilename(name)
334 _, base := filepath.Split(name)
335
336 m := meta.Copy()
337 if m.Filename == "" {
338 m.Filename = name
339 }
340 m.OpenFunc = fileOpener
341
342 return NewFileMetaInfo(
343 &dirNameOnlyFileInfo{name: base, modTime: htime.Now()},
344 m,
345 )
346 }
347
348 func decorateFileInfo(fi FileNameIsDir, opener func() (afero.File, error), filename string, inMeta *FileMeta) FileMetaInfo {
349 var meta *FileMeta
350 var fim FileMetaInfo
351
352 var ok bool
353 if fim, ok = fi.(FileMetaInfo); ok {
354 meta = fim.Meta()
355 } else {
356 meta = NewFileMeta()
357 fim = NewFileMetaInfo(fi, meta)
358 }
359
360 if opener != nil {
361 meta.OpenFunc = opener
362 }
363
364 nfilename := normalizeFilename(filename)
365 if nfilename != "" {
366 meta.Filename = nfilename
367 }
368
369 meta.Merge(inMeta)
370
371 return fim
372 }
373
374 func DirEntriesToFileMetaInfos(fis []fs.DirEntry) []FileMetaInfo {
375 fims := make([]FileMetaInfo, len(fis))
376 for i, v := range fis {
377 fim := v.(FileMetaInfo)
378 fims[i] = fim
379 }
380 return fims
381 }
382
383 func normalizeFilename(filename string) string {
384 if filename == "" {
385 return ""
386 }
387 if runtime.GOOS == "darwin" {
388 // When a file system is HFS+, its filepath is in NFD form.
389 return norm.NFC.String(filename)
390 }
391 return filename
392 }
393
394 func sortDirEntries(fis []fs.DirEntry) {
395 sort.Slice(fis, func(i, j int) bool {
396 fimi, fimj := fis[i].(FileMetaInfo), fis[j].(FileMetaInfo)
397 return fimi.Meta().Filename < fimj.Meta().Filename
398 })
399 }
400
401 // AddFileInfoToError adds file info to the given error.
402 func AddFileInfoToError(err error, fi FileMetaInfo, fs afero.Fs) error {
403 if err == nil {
404 return nil
405 }
406
407 meta := fi.Meta()
408 filename := meta.Filename
409
410 // Check if it's already added.
411 for _, ferr := range herrors.UnwrapFileErrors(err) {
412 pos := ferr.Position()
413 errfilename := pos.Filename
414 if errfilename == "" {
415 pos.Filename = filename
416 ferr.UpdatePosition(pos)
417 }
418
419 if errfilename == "" || errfilename == filename {
420 if filename != "" && ferr.ErrorContext() == nil {
421 f, ioerr := fs.Open(filename)
422 if ioerr != nil {
423 return err
424 }
425 defer f.Close()
426 ferr.UpdateContent(f, nil)
427 }
428 return err
429 }
430 }
431
432 lineMatcher := herrors.NopLineMatcher
433
434 if textSegmentErr, ok := err.(*herrors.TextSegmentError); ok {
435 lineMatcher = herrors.ContainsMatcher(textSegmentErr.Segment)
436 }
437
438 return herrors.NewFileErrorFromFile(err, filename, fs, lineMatcher)
439 }