github.com/anakojm/hugo-katex@v0.0.0-20231023141351-42d6f5de9c0b/hugofs/hasbytes_fs.go (about) 1 // Copyright 2022 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 bool) 32 pattern []byte 33 } 34 35 func NewHasBytesReceiver(delegate afero.Fs, shouldCheck func(name string) bool, hasBytesCallback func(name string, match bool), pattern []byte) afero.Fs { 36 return &hasBytesFs{Fs: delegate, shouldCheck: shouldCheck, hasBytesCallback: hasBytesCallback, pattern: pattern} 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 return &hasBytesFile{ 64 File: f, 65 hbw: &hugio.HasBytesWriter{ 66 Pattern: fs.pattern, 67 }, 68 hasBytesCallback: fs.hasBytesCallback, 69 } 70 71 } 72 73 func (fs *hasBytesFs) Name() string { 74 return "hasBytesFs" 75 } 76 77 type hasBytesFile struct { 78 hasBytesCallback func(name string, match bool) 79 hbw *hugio.HasBytesWriter 80 afero.File 81 } 82 83 func (h *hasBytesFile) Write(p []byte) (n int, err error) { 84 n, err = h.File.Write(p) 85 if err != nil { 86 return 87 } 88 return h.hbw.Write(p) 89 } 90 91 func (h *hasBytesFile) Close() error { 92 h.hasBytesCallback(h.Name(), h.hbw.Match) 93 return h.File.Close() 94 }