zs/zs.go

318 lines
6.8 KiB
Go
Raw Normal View History

2014-12-05 19:59:56 +03:00
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path"
"path/filepath"
"strings"
2015-08-29 19:46:05 +03:00
"text/template"
2014-12-05 19:59:56 +03:00
"time"
"github.com/eknkc/amber"
2014-12-05 19:59:56 +03:00
"github.com/russross/blackfriday"
2015-08-29 18:47:16 +03:00
"github.com/yosssi/gcss"
2014-12-05 19:59:56 +03:00
)
const (
ZSDIR = ".zs"
PUBDIR = ".pub"
)
2015-08-29 18:47:16 +03:00
type Vars map[string]string
type Funcs template.FuncMap
2014-12-05 19:59:56 +03:00
2015-08-29 18:47:16 +03:00
// Parses markdown content. Returns parsed header variables and content
func md(path string, globals Vars) (Vars, string, error) {
2015-08-29 18:47:16 +03:00
b, err := ioutil.ReadFile(path)
if err != nil {
return nil, "", err
}
s := string(b)
2014-12-05 21:26:15 +03:00
url := path[:len(path)-len(filepath.Ext(path))] + ".html"
2015-08-29 18:47:16 +03:00
v := Vars{
"file": path,
"url": url,
"title": "",
"description": "",
"keywords": "",
"output": filepath.Join(PUBDIR, url),
2014-12-05 21:26:15 +03:00
}
if _, err := os.Stat(filepath.Join(ZSDIR, "layout.amber")); err == nil {
v["layout"] = "layout.amber"
} else {
v["layout"] = "layout.html"
}
for name, value := range globals {
v[name] = value
}
2014-12-05 20:09:10 +03:00
if strings.Index(s, "\n\n") == -1 {
return v, s, nil
2014-12-05 20:09:10 +03:00
}
2014-12-05 19:59:56 +03:00
header, body := split2(s, "\n\n")
for _, line := range strings.Split(header, "\n") {
key, value := split2(line, ":")
v[strings.ToLower(strings.TrimSpace(key))] = strings.TrimSpace(value)
}
2014-12-05 21:26:15 +03:00
if strings.HasPrefix(v["url"], "./") {
v["url"] = v["url"][2:]
}
2015-08-29 18:47:16 +03:00
return v, body, nil
2014-12-05 19:59:56 +03:00
}
2015-08-29 19:46:05 +03:00
// Use standard Go templates
func render(s string, funcs Funcs, vars Vars) (string, error) {
f := Funcs{}
2015-08-29 19:46:05 +03:00
for k, v := range funcs {
f[k] = v
}
for k, v := range vars {
f[k] = varFunc(v)
}
// Plugin functions
files, _ := ioutil.ReadDir(ZSDIR)
for _, file := range files {
if !file.IsDir() {
name := file.Name()
if !strings.HasSuffix(name, ".html") && !strings.HasSuffix(name, ".amber") {
f[strings.TrimSuffix(name, filepath.Ext(name))] = pluginFunc(name, vars)
}
}
}
tmpl, err := template.New("").Funcs(template.FuncMap(f)).Parse(s)
2015-08-29 19:46:05 +03:00
if err != nil {
return "", err
2014-12-05 19:59:56 +03:00
}
2015-08-29 19:46:05 +03:00
out := &bytes.Buffer{}
if err := tmpl.Execute(out, vars); err != nil {
return "", err
}
return string(out.Bytes()), nil
2014-12-05 19:59:56 +03:00
}
2015-08-29 19:46:05 +03:00
// Renders markdown with the given layout into html expanding all the macros
func buildMarkdown(path string, w io.Writer, funcs Funcs, vars Vars) error {
v, body, err := md(path, vars)
2014-12-05 19:59:56 +03:00
if err != nil {
return err
}
2015-08-29 19:46:05 +03:00
content, err := render(body, funcs, v)
2014-12-05 19:59:56 +03:00
if err != nil {
return err
}
v["content"] = string(blackfriday.MarkdownBasic([]byte(content)))
if w == nil {
out, err := os.Create(filepath.Join(PUBDIR, renameExt(path, "", ".html")))
if err != nil {
return err
}
defer out.Close()
w = out
}
2015-08-29 19:46:05 +03:00
if strings.HasSuffix(v["layout"], ".amber") {
return buildAmber(filepath.Join(ZSDIR, v["layout"]), w, funcs, v)
2015-08-29 19:46:05 +03:00
} else {
return buildHTML(filepath.Join(ZSDIR, v["layout"]), w, funcs, v)
2015-08-29 19:46:05 +03:00
}
}
2015-08-29 19:46:05 +03:00
// Renders text file expanding all variable macros inside it
func buildHTML(path string, w io.Writer, funcs Funcs, vars Vars) error {
b, err := ioutil.ReadFile(path)
2014-12-05 19:59:56 +03:00
if err != nil {
return err
}
2015-08-29 19:46:05 +03:00
content, err := render(string(b), funcs, vars)
2014-12-05 19:59:56 +03:00
if err != nil {
return err
}
if w == nil {
f, err := os.Create(filepath.Join(PUBDIR, path))
if err != nil {
return err
}
defer f.Close()
w = f
2014-12-05 19:59:56 +03:00
}
_, err = io.WriteString(w, content)
return err
2014-12-05 19:59:56 +03:00
}
2015-08-29 19:46:05 +03:00
// Renders .amber file into .html
func buildAmber(path string, w io.Writer, funcs Funcs, vars Vars) error {
2015-08-29 18:47:16 +03:00
a := amber.New()
err := a.ParseFile(path)
2015-08-29 18:47:16 +03:00
if err != nil {
return err
}
data := map[string]interface{}{}
for k, v := range vars {
data[k] = v
}
for k, v := range funcs {
data[k] = v
}
2015-08-29 18:47:16 +03:00
t, err := a.Compile()
if err != nil {
return err
}
if w == nil {
f, err := os.Create(filepath.Join(PUBDIR, renameExt(path, ".amber", ".html")))
if err != nil {
return err
}
defer f.Close()
w = f
2015-08-29 18:47:16 +03:00
}
return t.Execute(w, data)
2015-08-29 18:47:16 +03:00
}
2015-08-29 19:46:05 +03:00
// Compiles .gcss into .css
func buildGCSS(path string, w io.Writer) error {
2015-08-29 19:46:05 +03:00
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
if w == nil {
s := strings.TrimSuffix(path, ".gcss") + ".css"
css, err := os.Create(filepath.Join(PUBDIR, s))
if err != nil {
return err
2014-12-05 19:59:56 +03:00
}
defer css.Close()
w = css
2014-12-05 19:59:56 +03:00
}
_, err = gcss.Compile(w, f)
return err
2014-12-05 19:59:56 +03:00
}
// Copies file as is from path to writer
func buildRaw(path string, w io.Writer) error {
in, err := os.Open(path)
if err != nil {
return err
}
defer in.Close()
if w == nil {
if out, err := os.Create(filepath.Join(PUBDIR, path)); err != nil {
return err
} else {
defer out.Close()
w = out
2015-08-29 19:46:05 +03:00
}
}
_, err = io.Copy(w, in)
return err
}
func build(path string, w io.Writer, funcs Funcs, vars Vars) error {
ext := filepath.Ext(path)
if ext == ".md" || ext == ".mkd" {
return buildMarkdown(path, w, funcs, vars)
} else if ext == ".html" || ext == ".xml" {
return buildHTML(path, w, funcs, vars)
} else if ext == ".amber" {
return buildAmber(path, w, funcs, vars)
} else if ext == ".gcss" {
return buildGCSS(path, w)
} else {
return buildRaw(path, w)
2015-08-29 19:46:05 +03:00
}
}
func buildAll(watch bool) {
lastModified := time.Unix(0, 0)
modified := false
vars := globals()
2014-12-05 19:59:56 +03:00
for {
os.Mkdir(PUBDIR, 0755)
funcs := builtins()
2014-12-05 19:59:56 +03:00
err := filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
// ignore hidden files and directories
if filepath.Base(path)[0] == '.' || strings.HasPrefix(path, ".") {
return nil
}
if info.IsDir() {
os.Mkdir(filepath.Join(PUBDIR, path), 0755)
return nil
} else if info.ModTime().After(lastModified) {
if !modified {
// About to be modified, so run pre-build hook
2015-08-29 19:46:05 +03:00
// FIXME on windows it might not work well
run(filepath.Join(ZSDIR, "pre"), []string{}, nil, nil)
modified = true
}
log.Println("build: ", path)
return build(path, nil, funcs, vars)
2014-12-05 19:59:56 +03:00
}
return nil
})
if err != nil {
log.Println("ERROR:", err)
}
if modified {
// Something was modified, so post-build hook
2015-08-29 19:46:05 +03:00
// FIXME on windows it might not work well
run(filepath.Join(ZSDIR, "post"), []string{}, nil, nil)
modified = false
}
if !watch {
2014-12-05 19:59:56 +03:00
break
}
lastModified = time.Now()
2014-12-05 19:59:56 +03:00
time.Sleep(1 * time.Second)
}
}
func main() {
if len(os.Args) == 1 {
fmt.Println(os.Args[0], "<command> [args]")
return
}
cmd := os.Args[1]
args := os.Args[2:]
switch cmd {
case "build":
if len(args) == 0 {
buildAll(false)
} else if len(args) == 1 {
if err := build(args[0], os.Stdout, builtins(), globals()); err != nil {
fmt.Println("ERROR: " + err.Error())
}
2014-12-05 19:59:56 +03:00
} else {
fmt.Println("ERROR: too many arguments")
2014-12-05 19:59:56 +03:00
}
case "watch":
buildAll(true)
case "var":
fmt.Println(Var(args))
case "lorem":
fmt.Println(Lorem(args))
case "dateparse":
fmt.Println(DateParse(args))
case "datefmt":
fmt.Println(DateFmt(args))
case "wc":
fmt.Println(WordCount(args))
case "timetoread":
fmt.Println(TimeToRead(args))
2014-12-05 19:59:56 +03:00
default:
2015-08-30 16:29:12 +03:00
err := run(path.Join(ZSDIR, cmd), args, globals(), os.Stdout)
if err != nil {
log.Println("ERROR:", err)
2014-12-05 19:59:56 +03:00
}
}
}