source: code/trunk/zs.go@ 39

Last change on this file since 39 was 37, checked in by zaitsev.serge, 10 years ago

fixed variable override order

File size: 9.6 KB
Line 
1package main
2
3import (
4 "bytes"
5 "fmt"
6 "io"
7 "io/ioutil"
8 "log"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "strings"
13 "text/template"
14 "time"
15
16 "github.com/eknkc/amber"
17 "github.com/russross/blackfriday"
18 "github.com/yosssi/gcss"
19 "gopkg.in/yaml.v2"
20)
21
22const (
23 ZSDIR = ".zs"
24 PUBDIR = ".pub"
25)
26
27type Vars map[string]string
28
29// renameExt renames extension (if any) from oldext to newext
30// If oldext is an empty string - extension is extracted automatically.
31// If path has no extension - new extension is appended
32func renameExt(path, oldext, newext string) string {
33 if oldext == "" {
34 oldext = filepath.Ext(path)
35 }
36 if oldext == "" || strings.HasSuffix(path, oldext) {
37 return strings.TrimSuffix(path, oldext) + newext
38 } else {
39 return path
40 }
41}
42
43// globals returns list of global OS environment variables that start
44// with ZS_ prefix as Vars, so the values can be used inside templates
45func globals() Vars {
46 vars := Vars{}
47 for _, e := range os.Environ() {
48 pair := strings.Split(e, "=")
49 if strings.HasPrefix(pair[0], "ZS_") {
50 vars[strings.ToLower(pair[0][3:])] = pair[1]
51 }
52 }
53 return vars
54}
55
56// run executes a command or a script. Vars define the command environment,
57// each zs var is converted into OS environemnt variable with ZS_ prefix
58// prepended. Additional variable $ZS contains path to the zs binary. Command
59// stderr is printed to zs stderr, command output is returned as a string.
60func run(vars Vars, cmd string, args ...string) (string, error) {
61 // First check if partial exists (.amber or .html)
62 if b, err := ioutil.ReadFile(filepath.Join(ZSDIR, cmd+".amber")); err == nil {
63 return string(b), nil
64 }
65 if b, err := ioutil.ReadFile(filepath.Join(ZSDIR, cmd+".html")); err == nil {
66 return string(b), nil
67 }
68
69 var errbuf, outbuf bytes.Buffer
70 c := exec.Command(cmd, args...)
71 env := []string{"ZS=" + os.Args[0], "ZS_OUTDIR=" + PUBDIR}
72 env = append(env, os.Environ()...)
73 for k, v := range vars {
74 env = append(env, "ZS_"+strings.ToUpper(k)+"="+v)
75 }
76 c.Env = env
77 c.Stdout = &outbuf
78 c.Stderr = &errbuf
79
80 err := c.Run()
81
82 if errbuf.Len() > 0 {
83 log.Println("ERROR:", errbuf.String())
84 }
85 if err != nil {
86 return "", err
87 }
88 return string(outbuf.Bytes()), nil
89}
90
91// getVars returns list of variables defined in a text file and actual file
92// content following the variables declaration. Header is separated from
93// content by an empty line. Header can be either YAML or JSON.
94// If no empty newline is found - file is treated as content-only.
95func getVars(path string, globals Vars) (Vars, string, error) {
96 b, err := ioutil.ReadFile(path)
97 if err != nil {
98 return nil, "", err
99 }
100 s := string(b)
101
102 // Pick some default values for content-dependent variables
103 v := Vars{}
104 title := strings.Replace(strings.Replace(path, "_", " ", -1), "-", " ", -1)
105 v["title"] = strings.ToTitle(title)
106 v["description"] = ""
107
108 // Copy globals (will override title and description for markdown layouts
109 for name, value := range globals {
110 v[name] = value
111 }
112
113 // Add default values extracted from file name/path
114 if _, err := os.Stat(filepath.Join(ZSDIR, "layout.amber")); err == nil {
115 v["layout"] = "layout.amber"
116 } else {
117 v["layout"] = "layout.html"
118 }
119 v["file"] = path
120 v["url"] = path[:len(path)-len(filepath.Ext(path))] + ".html"
121 v["output"] = filepath.Join(PUBDIR, v["url"])
122
123 delim := "\n---\n"
124 if sep := strings.Index(s, delim); sep == -1 {
125 return v, s, nil
126 } else {
127 header := s[:sep]
128 body := s[sep+len(delim):]
129
130 vars := Vars{}
131 if err := yaml.Unmarshal([]byte(header), &vars); err != nil {
132 fmt.Println("ERROR: failed to parse header", err)
133 return nil, "", err
134 } else {
135 for key, value := range vars {
136 v[key] = value
137 }
138 }
139 if strings.HasPrefix(v["url"], "./") {
140 v["url"] = v["url"][2:]
141 }
142 return v, body, nil
143 }
144}
145
146// Render expanding zs plugins and variables
147func render(s string, vars Vars) (string, error) {
148 delim_open := "{{"
149 delim_close := "}}"
150
151 out := &bytes.Buffer{}
152 for {
153 if from := strings.Index(s, delim_open); from == -1 {
154 out.WriteString(s)
155 return out.String(), nil
156 } else {
157 if to := strings.Index(s, delim_close); to == -1 {
158 return "", fmt.Errorf("Close delim not found")
159 } else {
160 out.WriteString(s[:from])
161 cmd := s[from+len(delim_open) : to]
162 s = s[to+len(delim_close):]
163 m := strings.Fields(cmd)
164 if len(m) == 1 {
165 if v, ok := vars[m[0]]; ok {
166 out.WriteString(v)
167 continue
168 }
169 }
170 if res, err := run(vars, m[0], m[1:]...); err == nil {
171 out.WriteString(res)
172 } else {
173 fmt.Println(err)
174 }
175 }
176 }
177 }
178 return s, nil
179}
180
181// Renders markdown with the given layout into html expanding all the macros
182func buildMarkdown(path string, w io.Writer, vars Vars) error {
183 v, body, err := getVars(path, vars)
184 if err != nil {
185 return err
186 }
187 content, err := render(body, v)
188 if err != nil {
189 return err
190 }
191 v["content"] = string(blackfriday.MarkdownCommon([]byte(content)))
192 if w == nil {
193 out, err := os.Create(filepath.Join(PUBDIR, renameExt(path, "", ".html")))
194 if err != nil {
195 return err
196 }
197 defer out.Close()
198 w = out
199 }
200 if strings.HasSuffix(v["layout"], ".amber") {
201 return buildAmber(filepath.Join(ZSDIR, v["layout"]), w, v)
202 } else {
203 return buildHTML(filepath.Join(ZSDIR, v["layout"]), w, v)
204 }
205}
206
207// Renders text file expanding all variable macros inside it
208func buildHTML(path string, w io.Writer, vars Vars) error {
209 v, body, err := getVars(path, vars)
210 if err != nil {
211 return err
212 }
213 if body, err = render(body, v); err != nil {
214 return err
215 }
216 tmpl, err := template.New("").Delims("<%", "%>").Parse(body)
217 if err != nil {
218 return err
219 }
220 if w == nil {
221 f, err := os.Create(filepath.Join(PUBDIR, path))
222 if err != nil {
223 return err
224 }
225 defer f.Close()
226 w = f
227 }
228 return tmpl.Execute(w, vars)
229}
230
231// Renders .amber file into .html
232func buildAmber(path string, w io.Writer, vars Vars) error {
233 v, body, err := getVars(path, vars)
234 if err != nil {
235 return err
236 }
237 a := amber.New()
238 if err := a.Parse(body); err != nil {
239 fmt.Println(body)
240 return err
241 }
242
243 t, err := a.Compile()
244 if err != nil {
245 return err
246 }
247
248 htmlBuf := &bytes.Buffer{}
249 if err := t.Execute(htmlBuf, v); err != nil {
250 return err
251 }
252
253 if body, err = render(string(htmlBuf.Bytes()), v); err != nil {
254 return err
255 }
256
257 if w == nil {
258 f, err := os.Create(filepath.Join(PUBDIR, renameExt(path, ".amber", ".html")))
259 if err != nil {
260 return err
261 }
262 defer f.Close()
263 w = f
264 }
265 _, err = io.WriteString(w, body)
266 return err
267}
268
269// Compiles .gcss into .css
270func buildGCSS(path string, w io.Writer) error {
271 f, err := os.Open(path)
272 if err != nil {
273 return err
274 }
275 defer f.Close()
276
277 if w == nil {
278 s := strings.TrimSuffix(path, ".gcss") + ".css"
279 css, err := os.Create(filepath.Join(PUBDIR, s))
280 if err != nil {
281 return err
282 }
283 defer css.Close()
284 w = css
285 }
286 _, err = gcss.Compile(w, f)
287 return err
288}
289
290// Copies file as is from path to writer
291func buildRaw(path string, w io.Writer) error {
292 in, err := os.Open(path)
293 if err != nil {
294 return err
295 }
296 defer in.Close()
297 if w == nil {
298 if out, err := os.Create(filepath.Join(PUBDIR, path)); err != nil {
299 return err
300 } else {
301 defer out.Close()
302 w = out
303 }
304 }
305 _, err = io.Copy(w, in)
306 return err
307}
308
309func build(path string, w io.Writer, vars Vars) error {
310 ext := filepath.Ext(path)
311 if ext == ".md" || ext == ".mkd" {
312 return buildMarkdown(path, w, vars)
313 } else if ext == ".html" || ext == ".xml" {
314 return buildHTML(path, w, vars)
315 } else if ext == ".amber" {
316 return buildAmber(path, w, vars)
317 } else if ext == ".gcss" {
318 return buildGCSS(path, w)
319 } else {
320 return buildRaw(path, w)
321 }
322}
323
324func buildAll(watch bool) {
325 lastModified := time.Unix(0, 0)
326 modified := false
327
328 vars := globals()
329 for {
330 os.Mkdir(PUBDIR, 0755)
331 filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
332 // ignore hidden files and directories
333 if filepath.Base(path)[0] == '.' || strings.HasPrefix(path, ".") {
334 return nil
335 }
336 // inform user about fs walk errors, but continue iteration
337 if err != nil {
338 fmt.Println("error:", err)
339 return nil
340 }
341
342 if info.IsDir() {
343 os.Mkdir(filepath.Join(PUBDIR, path), 0755)
344 return nil
345 } else if info.ModTime().After(lastModified) {
346 if !modified {
347 // First file in this build cycle is about to be modified
348 run(vars, "prehook")
349 modified = true
350 }
351 log.Println("build:", path)
352 return build(path, nil, vars)
353 }
354 return nil
355 })
356 if modified {
357 // At least one file in this build cycle has been modified
358 run(vars, "posthook")
359 modified = false
360 }
361 if !watch {
362 break
363 }
364 lastModified = time.Now()
365 time.Sleep(1 * time.Second)
366 }
367}
368
369func init() {
370 // prepend .zs to $PATH, so plugins will be found before OS commands
371 p := os.Getenv("PATH")
372 p = ZSDIR + ":" + p
373 os.Setenv("PATH", p)
374}
375
376func main() {
377 if len(os.Args) == 1 {
378 fmt.Println(os.Args[0], "<command> [args]")
379 return
380 }
381 cmd := os.Args[1]
382 args := os.Args[2:]
383 switch cmd {
384 case "build":
385 if len(args) == 0 {
386 buildAll(false)
387 } else if len(args) == 1 {
388 if err := build(args[0], os.Stdout, globals()); err != nil {
389 fmt.Println("ERROR: " + err.Error())
390 }
391 } else {
392 fmt.Println("ERROR: too many arguments")
393 }
394 case "watch":
395 buildAll(true)
396 case "var":
397 if len(args) == 0 {
398 fmt.Println("var: filename expected")
399 } else {
400 s := ""
401 if vars, _, err := getVars(args[0], globals()); err != nil {
402 fmt.Println("var: " + err.Error())
403 } else {
404 if len(args) > 1 {
405 for _, a := range args[1:] {
406 s = s + vars[a] + "\n"
407 }
408 } else {
409 for k, v := range vars {
410 s = s + k + ":" + v + "\n"
411 }
412 }
413 }
414 fmt.Println(strings.TrimSpace(s))
415 }
416 default:
417 if s, err := run(globals(), cmd, args...); err != nil {
418 fmt.Println(err)
419 } else {
420 fmt.Println(s)
421 }
422 }
423}
Note: See TracBrowser for help on using the repository browser.