This repository was archived by the owner on Apr 30, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathgenerator.go
108 lines (87 loc) · 2.35 KB
/
generator.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
package parcello
import (
"bufio"
"bytes"
"fmt"
"go/format"
"io"
"os"
"strings"
)
var _ Composer = &Generator{}
// GeneratorConfig controls how the code generation happens
type GeneratorConfig struct {
// Package determines the name of the package
Package string
// InlcudeDocs determines whether to include documentation
InlcudeDocs bool
}
// Generator generates an embedable resource
type Generator struct {
// FileSystem represents the underlying file system
FileSystem FileSystem
// Config controls how the code generation happens
Config *GeneratorConfig
}
// Compose generates an embedable resource for given directory
func (g *Generator) Compose(bundle *Bundle) error {
template := &bytes.Buffer{}
if g.Config.InlcudeDocs {
fmt.Fprintln(template, "// Code generated by parcello; DO NOT EDIT.")
fmt.Fprintln(template, "")
fmt.Fprintln(template, "// Package", g.Config.Package, "contains embedded resources")
}
fmt.Fprintln(template, "package", g.Config.Package)
fmt.Fprintln(template)
fmt.Fprintf(template, "import \"github.com/phogolabs/parcello\"")
fmt.Fprintln(template)
fmt.Fprintln(template)
fmt.Fprintln(template, "func init() {")
fmt.Fprintln(template, "\tparcello.AddResource([]byte{")
template.Write(g.prepare(bundle.Body))
fmt.Fprintln(template, "\t})")
fmt.Fprintln(template, "}")
return g.write(bundle.Name, template.Bytes())
}
func (g *Generator) prepare(data []byte) []byte {
prepared := &bytes.Buffer{}
body := bytes.NewBuffer(data)
reader := bufio.NewReader(body)
buffer := &bytes.Buffer{}
for {
bit, rErr := reader.ReadByte()
if rErr == io.EOF {
line := strings.TrimSpace(buffer.String())
fmt.Fprintln(prepared, line)
return prepared.Bytes()
}
if buffer.Len() == 0 {
fmt.Fprint(buffer, "\t\t")
}
fmt.Fprintf(buffer, "%d, ", int(bit))
if buffer.Len() >= 60 {
line := strings.TrimSpace(buffer.String())
fmt.Fprintln(prepared, line)
buffer.Reset()
continue
}
}
}
func (g *Generator) write(name string, data []byte) error {
var err error
if data, err = format.Source(data); err != nil {
return err
}
filename := fmt.Sprintf("%s.go", name)
file, err := g.FileSystem.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
defer func() {
if ioErr := file.Close(); err == nil {
err = ioErr
}
}()
_, err = file.Write(data)
return err
}