summaryrefslogtreecommitdiffstats
path: root/internal/cms/section.go
blob: fbb9013c2f52b6e076804b0998b9c35043beb52e (plain) (blame)
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
package cms

import (
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
)

func LoadSections(root string) (map[string]Section, error) {
	dir := filepath.Join(root, "site/sections")
	sections := map[string]Section{}
	if _, err := os.Stat(dir); err != nil {
		if os.IsNotExist(err) {
			return sections, nil
		}
		return nil, err
	}
	err := filepath.WalkDir(dir, func(path string, entry fs.DirEntry, err error) error {
		if err != nil {
			return err
		}
		if entry.IsDir() || filepath.Ext(path) != ".toml" {
			return nil
		}
		section, err := loadSection(path)
		if err != nil {
			return err
		}
		sections[section.Name] = section
		return nil
	})
	return sections, err
}

func loadSection(path string) (Section, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		return Section{}, err
	}
	table, err := parseSimpleTable(string(data))
	if err != nil {
		return Section{}, fmt.Errorf("%s: %w", path, err)
	}
	name := table.values["name"]
	if name == "" {
		name = slugify(filepath.Base(path))
	}
	title := table.values["title"]
	if title == "" {
		title = titleize(name)
	}
	return Section{Name: name, Title: title}, nil
}