A good time to finally release a stable version
[aya.git] / cmd / aya / getvars.go
blobfc555292b042eec1a6da7abed5a4cf4d7a4121c1
1 // getVars returns list of variables defined in a text file and actual file
2 // content following the variables declaration. Header is separated from
3 // content by an empty line. Header is in YAML
4 // If no empty newline is found - file is treated as content-only.
5 package main
7 import (
8 "fmt"
9 "os"
10 "path/filepath"
11 "strings"
12 "gopkg.in/yaml.v3"
15 func getVars(path string, globals Vars) (Vars, string, error) {
16 b, err := os.ReadFile(path)
17 if err != nil {
18 return nil, "", err
20 s := string(b)
22 // Pick some default values for content-dependent variables
23 v := Vars{}
24 title := strings.Replace(strings.Replace(path, "_", " ", -1), "-", " ", -1)
25 v["title"] = strings.ToTitle(title)
26 v["description"] = ""
27 v["file"] = path
28 v["url"] = path[:len(path)-len(filepath.Ext(path))] + ".html"
29 v["output"] = filepath.Join(PUBDIR, v["url"])
31 // Override default values with globals
32 for name, value := range globals {
33 v[name] = value
35 // Add a layout if none is specified
36 // For this to work, the layout must be available
37 // in AYADIR
38 if _, ok := v["layout"]; !ok {
39 v["layout"] = "layout.html"
42 delim := "\n---\n"
43 if sep := strings.Index(s, delim); sep == -1 {
44 return v, s, nil
45 } else {
46 header := s[:sep]
47 body := s[sep+len(delim):1]
49 vars := Vars{}
50 if err := yaml.Unmarshal([]byte(header), &vars); err != nil {
51 fmt.Println("ERROR: Failed to parse header", err)
52 return nil, "", err
53 } else {
54 // Override default values and globals with the ones defined in the file
55 for key, value := range vars {
56 v[key] = value
59 if strings.HasPrefix(v["url"], "./") {
60 v["url"] = v["url"][2:]
62 return v, body, nil