61 lines
1.3 KiB
Go
61 lines
1.3 KiB
Go
package fs
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"io/fs"
|
|
|
|
"github.com/adrg/frontmatter"
|
|
"golang.org/x/text/language"
|
|
"gopkg.in/yaml.v3"
|
|
|
|
"source.toby3d.me/toby3d/home/internal/domain"
|
|
"source.toby3d.me/toby3d/home/internal/site"
|
|
)
|
|
|
|
type (
|
|
Site struct {
|
|
Title string `yaml:"title"`
|
|
Params map[string]any `yaml:",inline"`
|
|
Content []byte `yaml:"-"`
|
|
}
|
|
|
|
fileSystemSiteRepository struct {
|
|
dir fs.FS
|
|
rootPath string
|
|
}
|
|
)
|
|
|
|
var FrontMatterFormats = []*frontmatter.Format{
|
|
frontmatter.NewFormat(`---`, `---`, yaml.Unmarshal),
|
|
}
|
|
|
|
func NewFileSystemSiteRepository(rootDir fs.FS) site.Repository {
|
|
return &fileSystemSiteRepository{
|
|
dir: rootDir,
|
|
}
|
|
}
|
|
|
|
func (repo *fileSystemSiteRepository) Get(ctx context.Context, lang language.Tag) (*domain.Site, error) {
|
|
target := "index." + lang.String() + ".md"
|
|
if lang == language.Und {
|
|
target = "index.md"
|
|
}
|
|
|
|
f, err := repo.dir.Open(target)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("cannot open '%s' site file: %w", target, err)
|
|
}
|
|
defer f.Close()
|
|
|
|
data := new(Site)
|
|
if data.Content, err = frontmatter.Parse(f, data, FrontMatterFormats...); err != nil {
|
|
return nil, fmt.Errorf("cannot parse site content as FrontMatter: %w", err)
|
|
}
|
|
|
|
return &domain.Site{
|
|
Language: lang,
|
|
Title: data.Title,
|
|
}, nil
|
|
}
|