Data files in folders under data/ #38
No files matched your search
@@ -216,6 +216,20 @@ text, ★★★★★, rounded to the nearest star.
|
||||
{{ range trail . }}<a href="{{ .Href }}">{{ .Title }}</a> › {{ end }}
|
||||
```
|
||||
|
||||
## Data files
|
||||
|
||||
`data "team"` reads `data/team.yaml` (or `.json`, or `.csv` as a list of
|
||||
rows of cells). Files can sit in folders: `data "exams/one"` reads
|
||||
`data/exams/one.yaml`, and `data "exams"` gives every file directly in
|
||||
`data/exams/`, by file name, so a page can list them all. A file and a
|
||||
folder with the same name are refused, since `data "exams"` would mean
|
||||
either. Folders starting with a dot are skipped. Anything that takes a data
|
||||
file's name, such as `nav` or a section's `from:`, takes a path the same way.
|
||||
|
||||
```
|
||||
{{ range $name, $exam := data "exams" }}<li>{{ $name }}: {{ $exam.questions }} questions</li>{{ end }}
|
||||
```
|
||||
|
||||
## Navigation trees
|
||||
|
||||
`nav "docs-nav" .` reads a navigation tree from `data/docs-nav.yaml` and
|
||||
|
||||
@@ -465,3 +465,22 @@ func TestContentFilesFollowThePath(t *testing.T) {
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// data reads files in folders under data/, one by path or a folder at once.
|
||||
func TestDataFolderFunc(t *testing.T) {
|
||||
dir := writeStarter(t)
|
||||
os.MkdirAll(filepath.Join(dir, "data", "exams"), 0o755)
|
||||
os.WriteFile(filepath.Join(dir, "data", "exams", "alpha.yaml"), []byte("questions: 60\n"), 0o644)
|
||||
os.WriteFile(filepath.Join(dir, "data", "exams", "beta.yaml"), []byte("questions: 40\n"), 0o644)
|
||||
os.WriteFile(filepath.Join(dir, "layouts", "exams.html"),
|
||||
[]byte(`{{ define "main" }}one={{ (data "exams/alpha").questions }};{{ range $k, $v := data "exams" }}{{ $k }}={{ $v.questions }};{{ end }}{{ end }}`), 0o644)
|
||||
os.WriteFile(filepath.Join(dir, "content", "exams.md"), []byte("---\ntitle: Exams\nlayout: exams\n---\n"), 0o644)
|
||||
res, err := Run(Options{SiteDir: dir})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out, _ := os.ReadFile(filepath.Join(res.Out, "exams", "index.html"))
|
||||
if !strings.Contains(string(out), "one=60;alpha=60;beta=40;") {
|
||||
t.Errorf("data folders: %s", out)
|
||||
}
|
||||
}
|
||||
@@ -83,12 +83,16 @@ func funcs(s *site.Site, a *Assets, md *site.Markdown, icons Icons) template.Fun
|
||||
// nav "docs-nav" .: the navigation tree in data/docs-nav.yaml as this
|
||||
// page sees it: .Items, .Here, .Trail, .Prev, .Next (site/nav.go).
|
||||
"nav": s.NavFor,
|
||||
// data "exams/one" is data/exams/one.yaml; data "exams" is a file of
|
||||
// that name or, failing that, the files in data/exams/ by name.
|
||||
"data": func(name string) (any, error) {
|
||||
v, ok := s.Data[name]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("no data/%s.yaml, data/%s.json or data/%s.csv", name, name, name)
|
||||
if v, ok := s.Data[name]; ok {
|
||||
return v, nil
|
||||
}
|
||||
return v, nil
|
||||
if v := s.DataFolder(name); v != nil {
|
||||
return v, nil
|
||||
}
|
||||
return nil, fmt.Errorf("no data/%s.yaml, data/%s.json or data/%s.csv", name, name, name)
|
||||
},
|
||||
"limit": func(n int, list any) (any, error) {
|
||||
v := reflect.ValueOf(list)
|
||||
|
||||
+57
-18
@@ -601,48 +601,87 @@ func sortPages(pages []*Page, by string) {
|
||||
})
|
||||
}
|
||||
|
||||
// loadData reads the files in data/ and in folders under it. A file in a
|
||||
// folder is named by its path without the extension: data/exams/one.yaml is
|
||||
// "exams/one". Folders whose names start with a dot are skipped.
|
||||
func loadData(dir string) (map[string]any, error) {
|
||||
out := map[string]any{}
|
||||
entries, err := os.ReadDir(dir)
|
||||
if os.IsNotExist(err) {
|
||||
if _, err := os.Stat(dir); os.IsNotExist(err) {
|
||||
return out, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, e := range entries {
|
||||
if e.IsDir() {
|
||||
continue
|
||||
}
|
||||
name := e.Name()
|
||||
ext := filepath.Ext(name)
|
||||
key := strings.TrimSuffix(name, ext)
|
||||
raw, err := os.ReadFile(filepath.Join(dir, name))
|
||||
err := filepath.WalkDir(dir, func(file string, e fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return err
|
||||
}
|
||||
if e.IsDir() {
|
||||
if file != dir && strings.HasPrefix(e.Name(), ".") {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
rel, _ := filepath.Rel(dir, file)
|
||||
rel = filepath.ToSlash(rel)
|
||||
ext := path.Ext(rel)
|
||||
key := strings.TrimSuffix(rel, ext)
|
||||
var v any
|
||||
switch ext {
|
||||
case ".yaml", ".yml", ".json", ".csv":
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
raw, err := os.ReadFile(file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch ext {
|
||||
case ".yaml", ".yml":
|
||||
err = yaml.Unmarshal(raw, &v)
|
||||
case ".json":
|
||||
err = json.Unmarshal(raw, &v)
|
||||
case ".csv":
|
||||
v, err = readCSV(raw)
|
||||
default:
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("data/%s: %w", name, err)
|
||||
return fmt.Errorf("data/%s: %w", rel, err)
|
||||
}
|
||||
if _, dup := out[key]; dup {
|
||||
return nil, fmt.Errorf("data/%s: another file is already named %s", name, key)
|
||||
return fmt.Errorf("data/%s: another file is already named %s", rel, key)
|
||||
}
|
||||
out[key] = v
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// A folder and a file with the same name would make "data name" mean two
|
||||
// things, so it's refused.
|
||||
for key := range out {
|
||||
for up := path.Dir(key); up != "."; up = path.Dir(up) {
|
||||
if _, clash := out[up]; clash {
|
||||
return nil, fmt.Errorf("data/%s: a folder data/%s/ has the same name", up, up)
|
||||
}
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// DataFolder is the files directly in data/<name>/, by file name without
|
||||
// the extension, or nil when there are none.
|
||||
func (s *Site) DataFolder(name string) map[string]any {
|
||||
var out map[string]any
|
||||
for key, v := range s.Data {
|
||||
rest, ok := strings.CutPrefix(key, name+"/")
|
||||
if !ok || strings.Contains(rest, "/") {
|
||||
continue
|
||||
}
|
||||
if out == nil {
|
||||
out = map[string]any{}
|
||||
}
|
||||
out[rest] = v
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// readCSV reads a spreadsheet saved as CSV into a list of rows, each a list
|
||||
// of cells, the way a YAML list of lists reads: the tables pack takes either.
|
||||
// Every row must have as many cells as the first. A byte order mark, which
|
||||
|
||||
@@ -111,3 +111,45 @@ func TestCSVData(t *testing.T) {
|
||||
t.Errorf("a row short of cells: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDataFolders(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
os.MkdirAll(filepath.Join(dir, "exams", "old"), 0o755)
|
||||
os.MkdirAll(filepath.Join(dir, ".cache"), 0o755)
|
||||
os.WriteFile(filepath.Join(dir, "team.yaml"), []byte("- Ana\n"), 0o644)
|
||||
os.WriteFile(filepath.Join(dir, "exams", "one.yaml"), []byte("questions: 60\n"), 0o644)
|
||||
os.WriteFile(filepath.Join(dir, "exams", "two.json"), []byte(`{"questions": 40}`), 0o644)
|
||||
os.WriteFile(filepath.Join(dir, "exams", "old", "zero.yaml"), []byte("questions: 10\n"), 0o644)
|
||||
os.WriteFile(filepath.Join(dir, "exams", "notes.txt"), []byte("not data"), 0o644)
|
||||
os.WriteFile(filepath.Join(dir, ".cache", "x.yaml"), []byte(": not yaml"), 0o644)
|
||||
data, err := loadData(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, key := range []string{"team", "exams/one", "exams/two", "exams/old/zero"} {
|
||||
if data[key] == nil {
|
||||
t.Errorf("%s not read", key)
|
||||
}
|
||||
}
|
||||
if len(data) != 4 {
|
||||
t.Errorf("read %d files, want 4: %v", len(data), data)
|
||||
}
|
||||
s := &Site{Data: data}
|
||||
folder := s.DataFolder("exams")
|
||||
if len(folder) != 2 || folder["one"] == nil || folder["two"] == nil {
|
||||
t.Errorf("exams folder: %v", folder)
|
||||
}
|
||||
if s.DataFolder("team") != nil || s.DataFolder("nothing") != nil {
|
||||
t.Error("a file or a missing name read as a folder")
|
||||
}
|
||||
// data/exams.yaml beside data/exams/ would make "exams" mean two things.
|
||||
os.WriteFile(filepath.Join(dir, "exams.yaml"), []byte("a: 1\n"), 0o644)
|
||||
if _, err := loadData(dir); err == nil || !strings.Contains(err.Error(), "data/exams/") {
|
||||
t.Errorf("a file and a folder with one name: %v", err)
|
||||
}
|
||||
os.Remove(filepath.Join(dir, "exams.yaml"))
|
||||
os.WriteFile(filepath.Join(dir, "exams", "one.json"), []byte(`{}`), 0o644)
|
||||
if _, err := loadData(dir); err == nil || !strings.Contains(err.Error(), "exams/one") {
|
||||
t.Errorf("two files named exams/one: %v", err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user