forked from liamjbennett/sous
-
Notifications
You must be signed in to change notification settings - Fork 0
/
includeTmpls.go
110 lines (92 loc) · 2.27 KB
/
includeTmpls.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package main
import (
"bytes"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
"strings"
"golang.org/x/tools/imports"
)
// started from http://stackoverflow.com/questions/17796043/golang-embedding-text-file-into-compiled-executable
// Reads all .txt files in the current folder
// and encodes them as strings literals in textfiles.go
const header = `// This file was automatically generated based on the contents of *.tmpl
// If you need to update this file, change the contents of those files
// (or add new ones) and run 'go generate'
`
func main() {
out := &bytes.Buffer{}
file, err := os.Create("templates.go")
if err != nil {
log.Fatal(err)
}
fs, err := ioutil.ReadDir(".")
if err != nil {
log.Fatal(err)
}
out.Write([]byte(header))
out.Write([]byte("package docker \n\nconst (\n"))
for _, f := range fs {
if strings.HasSuffix(f.Name(), ".tmpl") {
out.Write([]byte(strings.TrimSuffix(f.Name(), ".tmpl") + "Tmpl = \""))
f, err := os.Open(f.Name())
if err != nil {
log.Fatal(err)
}
r := newEscaper(f)
io.Copy(out, r)
out.Write([]byte("\"\n\n"))
}
}
out.Write([]byte(")\n"))
cwd, err := os.Getwd()
if err != nil {
log.Fatal("Couldn't get current working directory")
}
fullpath := filepath.Join(cwd, "templates.go")
formattedBytes, err := imports.Process(fullpath, out.Bytes(), nil)
if err != nil {
log.Print("Problem formatting to ", fullpath, ": ", err)
formattedBytes = out.Bytes()
}
file.Write(formattedBytes)
}
type escaper struct {
r io.Reader
old []byte
}
var doublesRE = regexp.MustCompile(`"`)
var newlsRE = regexp.MustCompile("(?m)\n")
func (e *escaper) Read(p []byte) (n int, err error) {
new := make([]byte, len(p)-len(e.old))
c, err := e.r.Read(new)
new = append(e.old, new[0:c]...)
i, n := 0, 0
for ; i < len(new) && n < len(p); i, n = i+1, n+1 {
switch new[i] {
default:
p[n] = new[i]
case '"', '\\':
p[n] = '\\'
n++
p[n] = new[i]
case '\n':
p[n] = '\\'
n++
p[n] = 'n'
}
}
if len(p) < i {
e.old = new[len(new)-(len(p)-i):]
} else {
e.old = new[0:0]
}
log.Print(i, "/", n, "\n", len(e.old), ":", string(e.old), "\n", len(p), ":", string(p), "\n\n**************************\n\n")
return
}
func newEscaper(r io.Reader) *escaper {
return &escaper{r, make([]byte, 0)}
}