This repository has been archived by the owner on Jul 14, 2021. It is now read-only.
/
embed.go
198 lines (177 loc) · 4.11 KB
/
embed.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
198
package main
import (
"bytes"
"context"
"encoding/base64"
"fmt"
"go/format"
"io/ioutil"
"log"
"os"
"path/filepath"
"text/template"
"github.com/urfave/cli/v2"
)
func pathToVar(path string) string {
return fmt.Sprintf("file%x", []byte(path))
}
func encodeFile(data []byte) string {
return base64.RawStdEncoding.EncodeToString(data)
}
var (
fileTemplate = template.Must(template.New("").Funcs(template.FuncMap{"pathToVar": pathToVar, "encode": encodeFile}).Parse(`package {{ .Package }}
import (
"encoding/base64"
"sort"
)
const (
{{- range $path, $data := .Files }}
{{ pathToVar $path }} = "{{ encode $data }}"
{{- end }}
)
// Embedded implements github.com/klingtnet/embed/Embed .
type Embedded struct {
embedMap map[string]string
}
// Embeds stores the embedded data.
var Embeds = Embedded {
embedMap: map[string]string{
{{- range $path, $_ := .Files }}
"{{ $path }}": {{ pathToVar $path }},
{{- end }}
},
}
// Files implements github.com/klingtnet/embed/Embed .
func (e Embedded) Files() []string {
var fs []string
for f := range e.embedMap {
fs = append(fs,f)
}
sort.Strings(fs)
return fs
}
// File implements github.com/klingtnet/embed/Embed .
func (e Embedded) File(path string) []byte {
file, ok := e.embedMap[path]
if !ok {
return nil
}
d, err := base64.RawStdEncoding.DecodeString(file)
if err != nil {
panic(err)
}
return d
}
// FileString implements github.com/klingtnet/embed/Embed .
func (e Embedded) FileString(path string) string {
return string(e.File(path))
}
`))
)
func readFile(path string) (data []byte, err error) {
f, err := os.Open(path)
if err != nil {
return
}
defer f.Close()
data, err = ioutil.ReadAll(f)
return
}
func embedAction(c *cli.Context) error {
return embed(c.Context, c.StringSlice("include"), c.String("package"), c.String("destination"))
}
func embed(ctx context.Context, includes []string, packageName, destinationPath string) error {
files := make(map[string][]byte)
for _, includePath := range includes {
info, err := os.Stat(includePath)
if err != nil {
return fmt.Errorf("stat: %w", err)
}
if info.IsDir() {
walkFn := func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
data, err := readFile(path)
if err != nil {
return fmt.Errorf("readFile: %w", err)
}
files[path] = data
return nil
}
err = filepath.Walk(includePath, walkFn)
if err != nil {
return fmt.Errorf("filepath.Walk: %w", err)
}
} else {
data, err := readFile(includePath)
if err != nil {
return fmt.Errorf("readFile: %w", err)
}
files[includePath] = data
}
}
templateData := struct {
Package string
Files map[string][]byte
}{
Package: packageName,
Files: files,
}
buf := bytes.NewBuffer(nil)
err := fileTemplate.Execute(buf, templateData)
if err != nil {
return fmt.Errorf("fileTemplate.Execute: %w", err)
}
source, err := format.Source(buf.Bytes())
if err != nil {
return fmt.Errorf("format.Source: %w", err)
}
dest, err := os.OpenFile(destinationPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
if err != nil {
return fmt.Errorf("os.OpenFile %q: %w", destinationPath, err)
}
defer dest.Close()
_, err = dest.Write(source)
if err != nil {
return fmt.Errorf("dest.Write: %w", err)
}
return nil
}
// Version is the build version.
// The actual version is set on build time.
var Version = "unset"
func main() {
app := cli.App{
Name: "embed",
Version: Version,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "package",
Aliases: []string{"p"},
Usage: "name of the package the generated Go file is associated to",
Value: "main",
},
&cli.StringFlag{
Name: "destination",
Aliases: []string{"dest", "d"},
Usage: "where to store the generated Go file",
Value: "embeds.go",
},
&cli.StringSliceFlag{
Name: "include",
Aliases: []string{"i"},
Usage: "paths to embed, directories are stored recursively (can be used multiple times)",
Required: true,
},
},
Action: embedAction,
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}