internal/storage/files/reader.go (view raw)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | package files
import (
"io/fs"
"path/filepath"
"strings"
"go.alanpearce.eu/homestead/internal/storage"
"go.alanpearce.eu/x/log"
"gitlab.com/tozd/go/errors"
)
type Reader struct {
root string
log *log.Logger
files map[string]*storage.File
}
func NewReader(path string, log *log.Logger) (*Reader, errors.E) {
r := &Reader{
root: path,
log: log,
files: make(map[string]*storage.File),
}
if err := r.registerContentFiles(); err != nil {
return nil, errors.WithMessagef(err, "registering content files")
}
return r, nil
}
func (r *Reader) registerFile(urlpath string, filepath string) errors.E {
file, err := r.OpenFile(urlpath, filepath)
if err != nil {
return errors.WithMessagef(err, "could not register file %s", filepath)
}
r.files[urlpath] = file
return nil
}
func (r *Reader) registerContentFiles() errors.E {
err := filepath.WalkDir(r.root, func(filePath string, f fs.DirEntry, err error) error {
if err != nil {
return errors.WithMessagef(err, "failed to access path %s", filePath)
}
if f.IsDir() {
return nil
}
relPath, err := filepath.Rel(r.root, filePath)
if err != nil {
return errors.WithMessagef(err, "failed to make path relative, path: %s", filePath)
}
urlPath := fileNameToPathName("/" + relPath)
switch filepath.Ext(relPath) {
case ".br", ".gz", ".zstd":
return nil
}
r.log.Debug("registering file", "url", urlPath, "filename", relPath)
return r.registerFile(urlPath, filePath)
})
if err != nil {
return errors.WithMessage(err, "could not walk directory")
}
return nil
}
func (r *Reader) GetFile(urlPath string) (*storage.File, errors.E) {
return r.files[urlPath], nil
}
func (r *Reader) CanonicalisePath(path string) (cPath string, differs bool) {
cPath = path
switch {
case strings.HasSuffix(path, "/index.html"):
cPath, differs = strings.CutSuffix(path, "index.html")
case strings.HasSuffix(path, ".html"):
cPath, differs = strings.CutSuffix(path, ".html")
case !strings.HasSuffix(path, "/") && r.files[path+"/"] != nil:
cPath, differs = path+"/", true
case strings.HasSuffix(path, "/"):
if cPath, differs := strings.CutSuffix(path, "/"); differs && r.files[cPath] != nil {
return cPath, differs
}
}
return cPath, differs
}
|