source: code/trunk/zs_util.go@ 24

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

fixed output file names in html pages, fixed amber function bindings, replaced print command with build, fixed plugin functions, implemented zs and exec functions

File size: 2.1 KB
RevLine 
[24]1package main
2
3import (
4 "bytes"
5 "io"
6 "log"
7 "os"
8 "os/exec"
9 "path/filepath"
10 "strings"
11)
12
13func varFunc(s string) func() string {
14 return func() string {
15 return s
16 }
17}
18
19func pluginFunc(cmd string, vars Vars) func(args ...string) string {
20 return func(args ...string) string {
21 out := bytes.NewBuffer(nil)
22 if err := run(cmd, args, vars, out); err != nil {
23 return cmd + ":" + err.Error()
24 } else {
25 return string(out.Bytes())
26 }
27 }
28}
29
30func builtins() Funcs {
31 exec := func(s ...string) string {
32 return ""
33 }
34 return Funcs{
35 "exec": exec,
36 "zs": func(args ...string) string {
37 cmd := []string{"zs"}
38 cmd = append(cmd, args...)
39 return exec(cmd...)
40 },
41 }
42}
43
44func renameExt(path, from, to string) string {
45 if from == "" {
46 from = filepath.Ext(path)
47 }
48 if strings.HasSuffix(path, from) {
49 return strings.TrimSuffix(path, from) + to
50 } else {
51 return path
52 }
53}
54
55func globals() Vars {
56 vars := Vars{}
57 for _, e := range os.Environ() {
58 pair := strings.Split(e, "=")
59 if strings.HasPrefix(pair[0], "ZS_") {
60 vars[strings.ToLower(pair[0][3:])] = pair[1]
61 }
62 }
63 return vars
64}
65
66// Converts zs markdown variables into environment variables
67func env(vars Vars) []string {
68 env := []string{"ZS=" + os.Args[0], "ZS_OUTDIR=" + PUBDIR}
69 env = append(env, os.Environ()...)
70 if vars != nil {
71 for k, v := range vars {
72 env = append(env, "ZS_"+strings.ToUpper(k)+"="+v)
73 }
74 }
75 return env
76}
77
78// Runs command with given arguments and variables, intercepts stderr and
79// redirects stdout into the given writer
80func run(cmd string, args []string, vars Vars, output io.Writer) error {
81 var errbuf bytes.Buffer
82 c := exec.Command(cmd, args...)
83 c.Env = env(vars)
84 c.Stdout = output
85 c.Stderr = &errbuf
86
87 err := c.Run()
88
89 if errbuf.Len() > 0 {
90 log.Println("ERROR:", errbuf.String())
91 }
92
93 if err != nil {
94 return err
95 }
96 return nil
97}
98
99// Splits a string in exactly two parts by delimiter
100// If no delimiter is found - the second string is be empty
101func split2(s, delim string) (string, string) {
102 parts := strings.SplitN(s, delim, 2)
103 if len(parts) == 2 {
104 return parts[0], parts[1]
105 } else {
106 return parts[0], ""
107 }
108}
Note: See TracBrowser for help on using the repository browser.