|
1 | 1 | package config
|
2 | 2 |
|
3 | 3 | import (
|
4 |
| - "github.com/spf13/afero" |
| 4 | + "os" |
5 | 5 | "path/filepath"
|
| 6 | + "slices" |
| 7 | + |
| 8 | + "github.com/spf13/afero" |
6 | 9 | )
|
7 | 10 |
|
8 | 11 | var (
|
9 |
| - contentExts = []string{"md"} |
10 |
| - listExts = []string{"yaml"} |
| 12 | + contentExts = []string{".md"} |
| 13 | + listExts = []string{".yaml", ".yml"} |
11 | 14 | )
|
12 | 15 |
|
13 | 16 | type Fs struct {
|
@@ -51,14 +54,42 @@ func (f *Fs) findFileWithExtension(paths, exts []string) string {
|
51 | 54 | return p
|
52 | 55 | }
|
53 | 56 | for _, e := range exts {
|
54 |
| - if pe := p + "." + e; f.IsFile(pe) { |
| 57 | + if pe := p + e; f.IsFile(pe) { |
55 | 58 | return pe
|
56 | 59 | }
|
57 | 60 | }
|
58 | 61 | }
|
59 | 62 | return ""
|
60 | 63 | }
|
61 | 64 |
|
| 65 | +func (fs *Fs) WalkContent(walkFn func(path, key string, fi os.FileInfo, err error)) error { |
| 66 | + return fs.walkFilesByExts(fs.Config.ContentDir, contentExts, walkFn) |
| 67 | +} |
| 68 | + |
| 69 | +func (fs *Fs) WalkLists(walkFn func(path, key string, fi os.FileInfo, err error)) error { |
| 70 | + return fs.walkFilesByExts(fs.Config.ListDir, listExts, walkFn) |
| 71 | +} |
| 72 | + |
| 73 | +// Iteration helper to find all files with multiple possible extensions in a directory |
| 74 | +func (fs *Fs) walkFilesByExts(dir string, exts []string, walkFn func(path, key string, fi os.FileInfo, err error)) error { |
| 75 | + return afero.Walk(fs, dir, func(path string, fi os.FileInfo, err error) error { |
| 76 | + if err != nil || fi.IsDir() { |
| 77 | + return nil |
| 78 | + } |
| 79 | + |
| 80 | + pathExt := filepath.Ext(path) |
| 81 | + if !slices.Contains(exts, pathExt) { |
| 82 | + return nil |
| 83 | + } |
| 84 | + |
| 85 | + // Remove dir prefix and extension |
| 86 | + key, _ := filepath.Rel(dir, path) |
| 87 | + key = key[:len(key)-len(pathExt)] |
| 88 | + walkFn(path, key, fi, nil) |
| 89 | + return nil |
| 90 | + }) |
| 91 | +} |
| 92 | + |
62 | 93 | func (f *Fs) IsFile(path string) bool {
|
63 | 94 | s, err := f.Stat(path)
|
64 | 95 | return err == nil && !s.IsDir()
|
|
0 commit comments