blogposts: handle file type

This commit is contained in:
vinchent 2024-09-24 22:13:33 +02:00
parent e8b8166ae9
commit 3cdca7cc94
2 changed files with 30 additions and 1 deletions

View File

@ -1,9 +1,17 @@
package blogposts
import (
"errors"
"io/fs"
"strings"
)
var markdownSuffix = map[string]struct{}{
"md": {},
}
var ErrUnknownFileType = errors.New("unknown file type, must be markdown")
func NewPostsFromFS(fileSystem fs.FS) ([]Post, error) {
dir, err := fs.ReadDir(fileSystem, ".")
if err != nil {
@ -11,7 +19,11 @@ func NewPostsFromFS(fileSystem fs.FS) ([]Post, error) {
}
var posts []Post
for _, f := range dir {
post, err := getPost(fileSystem, f.Name())
fileName := f.Name()
if !isMarkdownFile(fileName) {
return nil, ErrUnknownFileType
}
post, err := getPost(fileSystem, fileName)
if err != nil {
return nil, err
}
@ -19,3 +31,9 @@ func NewPostsFromFS(fileSystem fs.FS) ([]Post, error) {
}
return posts, nil
}
func isMarkdownFile(fileName string) bool {
splitted := strings.Split(fileName, ".")
_, ok := markdownSuffix[splitted[len(splitted)-1:][0]]
return ok
}

View File

@ -56,6 +56,17 @@ World`,
})
}
func TestWrongFile(t *testing.T) {
fs := fstest.MapFS{
"hello world.txt": {Data: []byte("Yolo")},
}
_, err := NewPostsFromFS(fs)
if err == nil {
t.Errorf("should be an error but not")
}
}
func assertPost(t testing.TB, got Post, want Post) {
t.Helper()
if !reflect.DeepEqual(got, want) {