github.com/kovansky/hugo@v0.92.3-0.20220224232819-63076e4ff19f/hugofs/createcounting_fs.go (about) 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 15 16 import ( 17 "fmt" 18 "os" 19 "sort" 20 "strings" 21 "sync" 22 23 "github.com/spf13/afero" 24 ) 25 26 // Reseter is implemented by some of the stateful filesystems. 27 type Reseter interface { 28 Reset() 29 } 30 31 // DuplicatesReporter reports about duplicate filenames. 32 type DuplicatesReporter interface { 33 ReportDuplicates() string 34 } 35 36 func NewCreateCountingFs(fs afero.Fs) afero.Fs { 37 return &createCountingFs{Fs: fs, fileCount: make(map[string]int)} 38 } 39 40 // ReportDuplicates reports filenames written more than once. 41 func (c *createCountingFs) ReportDuplicates() string { 42 c.mu.Lock() 43 defer c.mu.Unlock() 44 45 var dupes []string 46 47 for k, v := range c.fileCount { 48 if v > 1 { 49 dupes = append(dupes, fmt.Sprintf("%s (%d)", k, v)) 50 } 51 } 52 53 if len(dupes) == 0 { 54 return "" 55 } 56 57 sort.Strings(dupes) 58 59 return strings.Join(dupes, ", ") 60 } 61 62 // createCountingFs counts filenames of created files or files opened 63 // for writing. 64 type createCountingFs struct { 65 afero.Fs 66 67 mu sync.Mutex 68 fileCount map[string]int 69 } 70 71 func (c *createCountingFs) Reset() { 72 c.mu.Lock() 73 defer c.mu.Unlock() 74 75 c.fileCount = make(map[string]int) 76 } 77 78 func (fs *createCountingFs) onCreate(filename string) { 79 fs.mu.Lock() 80 defer fs.mu.Unlock() 81 82 fs.fileCount[filename] = fs.fileCount[filename] + 1 83 } 84 85 func (fs *createCountingFs) Create(name string) (afero.File, error) { 86 f, err := fs.Fs.Create(name) 87 if err == nil { 88 fs.onCreate(name) 89 } 90 return f, err 91 } 92 93 func (fs *createCountingFs) OpenFile(name string, flag int, perm os.FileMode) (afero.File, error) { 94 f, err := fs.Fs.OpenFile(name, flag, perm) 95 if err == nil && isWrite(flag) { 96 fs.onCreate(name) 97 } 98 return f, err 99 }