-
Notifications
You must be signed in to change notification settings - Fork 10
/
command_template.go
38 lines (35 loc) · 792 Bytes
/
command_template.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package main
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"text/template"
"github.com/urfave/cli"
)
func cmdTemplate(c *cli.Context) error {
source := c.Args().First()
isRewrite := c.Bool("w")
data, err := ioutil.ReadFile(source)
if err != nil {
printError(err.Error())
return errAbort
}
funcs := template.FuncMap{"env": os.Getenv}
tmpl, err := template.New("tmpl").Funcs(funcs).Parse(string(data))
if err != nil {
printError(err.Error())
return errAbort
}
output := new(bytes.Buffer)
err = tmpl.Execute(output, "")
if err != nil {
printError(err.Error())
return errAbort
}
if isRewrite {
return ioutil.WriteFile(source, output.Bytes(), os.FileMode(0644)) // -rw-r--r--, see http://permissions-calculator.org/
}
fmt.Fprintln(os.Stdout, output)
return nil
}