Configurable extensions for template parser

This commit is contained in:
Katrina Verey
2022-04-21 18:28:13 -04:00
parent 9d5491c2e2
commit bcae65770a
5 changed files with 42 additions and 10 deletions

View File

@@ -13,9 +13,9 @@ import (
)
type parser struct {
fs iofs.FS
paths []string
extension string
fs iofs.FS
paths []string
extensions []string
}
type contentProcessor func(content []byte, name string) error
@@ -51,8 +51,8 @@ func (l parser) readPath(path string, processContent contentProcessor) error {
}
// Path is a file -- check extension and read it
if !strings.HasSuffix(path, l.extension) {
return errors.Errorf("file %s did not have required extension %s", path, l.extension)
if err := checkExtension(path, l.extensions); err != nil {
return err
}
b, err := ioutil.ReadAll(f)
if err != nil {
@@ -61,6 +61,15 @@ func (l parser) readPath(path string, processContent contentProcessor) error {
return processContent(b, path)
}
func checkExtension(path string, extensions []string) error {
for _, ext := range extensions {
if strings.HasSuffix(path, ext) {
return nil
}
}
return errors.Errorf("file %s does not have any of permitted extensions %s", path, extensions)
}
func (l parser) readDir(dir iofs.ReadDirFile, dirname string, processContent contentProcessor) error {
entries, err := dir.ReadDir(0)
if err != nil {
@@ -68,7 +77,7 @@ func (l parser) readDir(dir iofs.ReadDirFile, dirname string, processContent con
}
for _, entry := range entries {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), l.extension) {
if err := checkExtension(entry.Name(), l.extensions); err != nil || entry.IsDir() {
continue
}
// Note: using filepath.Join will break Windows, because io/fs.FS implementations require slashes on all OS.