/
main.go
197 lines (180 loc) · 4.69 KB
/
main.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
package main
import (
"archive/tar"
"bytes"
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
htmltemplate "html/template"
"text/template"
"github.com/Masterminds/sprig"
)
var (
flagInput = flag.String("f", "-", "Input source")
flagOutput = flag.String("w", "-", "Output destination")
flagHTML = flag.Bool("html", false, "If true, use html/template instead of text/template")
flagRecursive = flag.String("r", "", "If provided, traverse the argument as a directory")
flagStripN = flag.Int("stripn", 0, "If provided, strips this many directories from the output (only valid if -r and -w are provided)")
)
func main() {
flag.Parse()
if err := run(*flagInput, *flagOutput, *flagRecursive, *flagHTML); err != nil {
fmt.Fprintln(os.Stderr, "tmpl error:", err)
os.Exit(1)
}
}
func run(input, output string, recurseDir string, htmlMode bool) error {
in, err := getInput(*flagInput)
if err != nil {
return err
}
if recurseDir != "" {
return runDir(recurseDir, htmlMode, *flagOutput, *flagStripN, envMap())
}
out, err := getOutput(*flagOutput)
if err != nil {
return err
}
return tmpl(in, *flagHTML, out, envMap())
}
func getInput(path string) (io.Reader, error) {
if path == "-" {
return os.Stdin, nil
}
return os.Open(path)
}
func getOutput(path string) (io.Writer, error) {
if path == "-" {
return os.Stdout, nil
}
return os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
}
func envMap() map[string]string {
result := map[string]string{}
for _, envvar := range os.Environ() {
parts := strings.SplitN(envvar, "=", 2)
result[parts[0]] = parts[1]
}
return result
}
func tmpl(in io.Reader, htmlMode bool, out io.Writer, ctx interface{}) error {
i, err := ioutil.ReadAll(in)
if err != nil {
return err
}
if htmlMode {
tmpl, err := htmltemplate.New("format string").Funcs(sprig.HtmlFuncMap()).Parse(string(i))
if err != nil {
return err
}
return tmpl.Execute(out, ctx)
}
tmpl, err := template.New("format string").Funcs(sprig.TxtFuncMap()).Parse(string(i))
if err != nil {
return err
}
return tmpl.Execute(out, ctx)
}
func tmplToString(in io.Reader, htmlMode bool, ctx interface{}) (string, error) {
o := bytes.NewBuffer([]byte{})
err := tmpl(in, htmlMode, o, ctx)
return o.String(), err
}
func tmplStr(in string, ctx interface{}) string {
o := bytes.NewBuffer([]byte{})
err := tmpl(strings.NewReader(in), false, o, ctx)
if err != nil {
fmt.Fprintln(os.Stderr, "issue rendering string:", err)
}
return o.String()
}
func runDir(dir string, htmlMode bool, outPath string, stripN int, ctx interface{}) error {
buf := new(bytes.Buffer)
tw := tar.NewWriter(buf)
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.Mode().IsRegular() {
return nil
}
f, err := os.Open(path)
if err != nil {
return err
}
contents, err := tmplToString(f, htmlMode, ctx)
if err != nil {
return fmt.Errorf("%v: %w", path, err)
}
hdr := &tar.Header{
Name: tmplStr(path, ctx),
Mode: int64(info.Mode()),
Size: int64(len(contents)),
}
if err := tw.WriteHeader(hdr); err != nil {
return err
}
if _, err := tw.Write([]byte(contents)); err != nil {
return err
}
return tw.Flush()
})
if err != nil {
return fmt.Errorf("issue recursing: %w", err)
}
if outPath == "-" {
_, err = io.Copy(os.Stdout, buf)
return err
}
return extractTar(buf, outPath, stripN)
}
func extractTar(buf io.Reader, outPath string, stripN int) error {
tarReader := tar.NewReader(buf)
for true {
header, err := tarReader.Next()
if err == io.EOF {
break
}
if err != nil {
return fmt.Errorf("Next() failed: %w", err)
}
path := header.Name
parts := strings.Split(path, string(filepath.Separator))
toStrip := stripN
if toStrip >= len(parts) {
toStrip = len(parts) - 1
}
if len(parts) > toStrip {
path = strings.Join(parts[toStrip:], string(filepath.Separator))
}
fullPath := filepath.Join(outPath, path)
if err := ensureEnclosingDir(fullPath); err != nil {
return fmt.Errorf("issue ensuring directory exists: %w", err)
}
switch header.Typeflag {
case tar.TypeDir:
if err := os.Mkdir(fullPath, 0755); err != nil {
return fmt.Errorf("Mkdir() failed: %w", err)
}
case tar.TypeReg:
outFile, err := os.Create(fullPath)
if err != nil {
return fmt.Errorf("Create() failed: %w", err)
}
if _, err := io.Copy(outFile, tarReader); err != nil {
return fmt.Errorf("io.Copy() failed: %w", err)
}
outFile.Close()
default:
return fmt.Errorf("extractTar: uknown type: %v in %v", header.Typeflag, header.Name)
}
}
return nil
}
func ensureEnclosingDir(path string) error {
return os.MkdirAll(filepath.Dir(path), 0755)
}