From 08b4928c1071b05c1111639f47a7179dd3cfb1e6 Mon Sep 17 00:00:00 2001 From: "Serge A. Zaitsev" Date: Fri, 5 Dec 2014 20:26:15 +0200 Subject: [PATCH] rewritted default variables assignment --- zs.go | 41 ++++++++++++++--------------------------- zs_test.go | 6 +++--- 2 files changed, 17 insertions(+), 30 deletions(-) diff --git a/zs.go b/zs.go index 1db764c..bd80b31 100644 --- a/zs.go +++ b/zs.go @@ -32,8 +32,15 @@ func split2(s, delim string) (string, string) { } } -func md(s string) (map[string]string, string) { - v := map[string]string{} +func md(path, s string) (map[string]string, string) { + url := path[:len(path)-len(filepath.Ext(path))] + ".html" + v := map[string]string{ + "file": path, + "url": url, + "outdir": PUBDIR, + "output": filepath.Join(PUBDIR, url), + "layout": "index.html", + } if strings.Index(s, "\n\n") == -1 { return map[string]string{}, s } @@ -42,6 +49,9 @@ func md(s string) (map[string]string, string) { key, value := split2(line, ":") v[strings.ToLower(strings.TrimSpace(key))] = strings.TrimSpace(value) } + if strings.HasPrefix(v["url"], "./") { + v["url"] = v["url"][2:] + } return v, body } @@ -128,8 +138,7 @@ func buildMarkdown(path string) error { if err != nil { return err } - v, body := md(string(b)) - defaultVars(v, path) + v, body := md(path, string(b)) content, err := render(body, v, eval) if err != nil { return err @@ -150,27 +159,6 @@ func buildMarkdown(path string) error { return nil } -func defaultVars(vars map[string]string, path string) { - if _, ok := vars["file"]; !ok { - vars["file"] = path - } - if _, ok := vars["url"]; !ok { - vars["url"] = path[:len(path)-len(filepath.Ext(path))] + ".html" - if strings.HasPrefix(vars["url"], "./") { - vars["url"] = vars["url"][2:] - } - } - if _, ok := vars["outdir"]; !ok { - vars["outdir"] = PUBDIR - } - if _, ok := vars["output"]; !ok { - vars["output"] = filepath.Join(PUBDIR, vars["url"]) - } - if _, ok := vars["layout"]; !ok { - vars["layout"] = "index.html" - } -} - func copyFile(path string) error { if in, err := os.Open(path); err != nil { return err @@ -249,8 +237,7 @@ func main() { return } if b, err := ioutil.ReadFile(args[0]); err == nil { - vars, _ := md(string(b)) - defaultVars(vars, args[0]) + vars, _ := md(args[0], string(b)) if len(args) > 1 { for _, a := range args[1:] { fmt.Println(vars[a]) diff --git a/zs_test.go b/zs_test.go index 5aeb1c8..8333de2 100644 --- a/zs_test.go +++ b/zs_test.go @@ -32,7 +32,7 @@ func TestSplit2(t *testing.T) { } func TestMD(t *testing.T) { - v, body := md(` + v, body := md("foo.md", ` title: Hello, world! keywords: foo, bar, baz empty: @@ -56,13 +56,13 @@ this: is a content`) } // Test empty md - v, body = md("") + v, body = md("foo.md", "") if len(v) != 0 || len(body) != 0 { t.Error(v, body) } // Test empty header - v, body = md("Hello") + v, body = md("foo.md", "Hello") if len(v) != 0 || body != "Hello" { t.Error(v, body) } -- 2.43.0