Debian Codegraph @

hugofs/hasbytes_fs.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 hugofs
15
16 import (
17 "os"
18
19 "github.com/gohugoio/hugo/common/hugio"
20 "github.com/spf13/afero"
21 )
22
23 var (
24 _ afero.Fs = (*hasBytesFs)(nil)
25 _ FilesystemUnwrapper = (*hasBytesFs)(nil)
26 )
27
28 type hasBytesFs struct {
29 afero.Fs
30 shouldCheck func(name string) bool
31 hasBytesCallback func(name string, match []byte)
32 patterns [][]byte
33 }
34
35 func NewHasBytesReceiver(delegate afero.Fs, shouldCheck func(name string) bool, hasBytesCallback func(name string, match []byte), patterns ...[]byte) afero.Fs {
36 return &hasBytesFs{Fs: delegate, shouldCheck: shouldCheck, hasBytesCallback: hasBytesCallback, patterns: patterns}
37 }
38
39 func (fs *hasBytesFs) UnwrapFilesystem() afero.Fs {
40 return fs.Fs
41 }
42
43 func (fs *hasBytesFs) Create(name string) (afero.File, error) {
44 f, err := fs.Fs.Create(name)
45 if err == nil {
46 f = fs.wrapFile(f)
47 }
48 return f, err
49 }
50
51 func (fs *hasBytesFs) OpenFile(name string, flag int, perm os.FileMode) (afero.File, error) {
52 f, err := fs.Fs.OpenFile(name, flag, perm)
53 if err == nil && isWrite(flag) {
54 f = fs.wrapFile(f)
55 }
56 return f, err
57 }
58
59 func (fs *hasBytesFs) wrapFile(f afero.File) afero.File {
60 if !fs.shouldCheck(f.Name()) {
61 return f
62 }
63 patterns := make([]*hugio.HasBytesPattern, len(fs.patterns))
64 for i, p := range fs.patterns {
65 patterns[i] = &hugio.HasBytesPattern{Pattern: p}
66 }
67
68 return &hasBytesFile{
69 File: f,
70 hbw: &hugio.HasBytesWriter{
71 Patterns: patterns,
72 },
73 hasBytesCallback: fs.hasBytesCallback,
74 }
75 }
76
77 func (fs *hasBytesFs) Name() string {
78 return "hasBytesFs"
79 }
80
81 type hasBytesFile struct {
82 hasBytesCallback func(name string, match []byte)
83 hbw *hugio.HasBytesWriter
84 afero.File
85 }
86
87 func (h *hasBytesFile) Write(p []byte) (n int, err error) {
88 n, err = h.File.Write(p)
89 if err != nil {
90 return
91 }
92 return h.hbw.Write(p)
93 }
94
95 func (h *hasBytesFile) Close() error {
96 for _, p := range h.hbw.Patterns {
97 if p.Match {
98 h.hasBytesCallback(h.Name(), p.Pattern)
99 }
100 }
101 return h.File.Close()
102 }