~evanj/embed

ref: 9f4e4dc945aca6b5462c38db63977663763d0fd4 embed/embed.go -rw-r--r-- 4.1 KiB
9f4e4dc9Evan M Jones Feat(embed.go): Changing impl. from string based to rune based. Can 1 year, 8 months ago
                                                                                
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
package main

import (
	"bytes"
	"flag"
	"fmt"
	"go/ast"
	"go/format"
	"go/types"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"text/template"

	"golang.org/x/tools/go/packages"
)

var (
	pattern = flag.String("pattern", "", "a string recognizing a set of files; must be set")
	id      = flag.String("id", "", "an identifier for the resulting variable")
)

func Usage() {
	fmt.Fprintf(os.Stderr, "Usage of embed:\n")
	fmt.Fprintf(os.Stderr, "\tembed [flags] -pattern string\n")
	fmt.Fprintf(os.Stderr, "\tembed [flags] -id string\n")
	fmt.Fprintf(os.Stderr, "For more information, see:\n")
	fmt.Fprintf(os.Stderr, "\thttp://godoc.org/git.sr.ht/~evanj/embed\n")
	flag.PrintDefaults()
}

func main() {
	log.SetFlags(0)
	log.SetPrefix("embed: ")
	flag.Usage = Usage
	flag.Parse()

	if len(*pattern) == 0 || len(*id) == 0 {
		flag.Usage()
		os.Exit(2)
	}

	args := flag.Args()
	if len(args) == 0 {
		args = []string{"."}
	}

	var dir string
	g := Generator{}
	dir = filepath.Dir(args[0])

	g.parsePackage(args)

	g.Printf("// Code generated by \"embed %s\"; DO NOT EDIT.\n", strings.Join(os.Args[1:], " "))
	g.Printf("\n")
	g.Printf("package %s", g.pkg.name)
	g.Printf("\n")

	if err := g.generate(*pattern, *id); err != nil {
		log.Fatalf("writing output: %s", err)
	}

	src := g.format()

	baseName := fmt.Sprintf("%s_embed.go", *id)
	outputName := filepath.Join(dir, strings.ToLower(baseName))
	err := ioutil.WriteFile(outputName, src, 0644)
	if err != nil {
		log.Fatalf("writing output: %s", err)
	}
}

type Generator struct {
	buf bytes.Buffer
	pkg *Package

	trimPrefix  string
	lineComment bool
}

func (g *Generator) Printf(format string, args ...interface{}) {
	fmt.Fprintf(&g.buf, format, args...)
}

type File struct {
	pkg  *Package
	file *ast.File

	trimPrefix  string
	lineComment bool
}

type Package struct {
	name  string
	defs  map[*ast.Ident]types.Object
	files []*File
}

func (g *Generator) parsePackage(patterns []string) {
	cfg := &packages.Config{
		Mode:  packages.LoadSyntax,
		Tests: false,
	}
	pkgs, err := packages.Load(cfg, patterns...)
	if err != nil {
		log.Fatal(err)
	}
	if len(pkgs) != 1 {
		log.Fatalf("error: %d packages found", len(pkgs))
	}
	g.addPackage(pkgs[0])
}

func (g *Generator) addPackage(pkg *packages.Package) {
	g.pkg = &Package{
		name:  pkg.Name,
		defs:  pkg.TypesInfo.Defs,
		files: make([]*File, len(pkg.Syntax)),
	}

	for i, file := range pkg.Syntax {
		g.pkg.files[i] = &File{
			file:        file,
			pkg:         g.pkg,
			trimPrefix:  g.trimPrefix,
			lineComment: g.lineComment,
		}
	}
}

type FileContents struct {
	Name, Content string
}

func (fc *FileContents) RuneRepr() string {
	var intRepr []string
	for _, r := range fc.Content {
		i := int(r)
		s := strconv.Itoa(i)
		intRepr = append(intRepr, s)
	}
	return strings.Join(intRepr, ", ")
}

func (g *Generator) generate(pattern string, id string) error {
	fns, err := filepath.Glob(pattern)
	if err != nil {
		return err
	}

	var fileData struct {
		ID    string
		Files []FileContents
	}

	fileData.ID = id
	for _, fn := range fns {
		bytes, err := ioutil.ReadFile(fn)
		if err != nil {
			return err
		}
		fileData.Files = append(fileData.Files, FileContents{fn, string(bytes)})
	}

	tmpl, err := template.New("embed").Parse(`
var {{ .ID }} map[string]string

func tostring(ints ...int) string {
	runes := make([]rune, len(ints))
	for index, i := range ints { 
		runes[index] = rune(i)
	}
	return string(runes)
}

func init() {
	{{ .ID }} = make(map[string]string)
	{{ range .Files }}
	{{ $.ID }}["{{ .Name }}"] = tostring({{ .RuneRepr }})
	{{ end }}
}

func Get(name string) (string, bool) {
	val, ok := {{ .ID }}[name]
	return val, ok
}

func Must(name string) string {
	val, _ := {{ .ID }}[name]
	return val
}
`)

	if err != nil {
		return err
	}

	var buf bytes.Buffer
	if err := tmpl.Execute(&buf, fileData); err != nil {
		return err
	}

	g.Printf(buf.String())
	return nil
}

func (g *Generator) format() []byte {
	src, err := format.Source(g.buf.Bytes())
	if err != nil {
		log.Printf("warning: internal error: invalid Go generated: %s", err)
		log.Printf("warning: compile the package to analyze the error")
		return g.buf.Bytes()
	}
	return src
}