forked from fyne-io/fyne
/
bundle.go
278 lines (244 loc) · 7.21 KB
/
bundle.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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
package commands
import (
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"regexp"
"strings"
"fyne.io/fyne/v2"
"github.com/urfave/cli/v2"
)
const fileHeader = "// auto-generated\n" + // to exclude this file in goreportcard (it has to be first)
"// Code generated by '$ fyne bundle'. DO NOT EDIT." // idiomatic mark, see https://golang.org/s/generatedcode
// Bundle returns the vendor cli command
func Bundle() *cli.Command {
b := &Bundler{}
return &cli.Command{
Name: "bundle",
Usage: "Embeds static content into your go application.",
Description: "Each resource will have a generated filename unless specified.",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "name",
Usage: "The variable name to assign the resource (file mode only).",
Destination: &b.name,
},
&cli.StringFlag{
Name: "output",
Aliases: []string{"o"},
Usage: "Specify an output file instead of printing to standard output.",
Destination: &b.out,
},
&cli.StringFlag{
Name: "package",
Aliases: []string{"pkg"},
Usage: "The package to output in headers (if not appending).",
Value: "main",
Destination: &b.pkg,
},
&cli.StringFlag{
Name: "prefix",
Usage: "A prefix for variables (ignored if name is set).",
Value: "resource",
Destination: &b.prefix,
},
&cli.BoolFlag{
Name: "append",
Aliases: []string{"a"},
Usage: "Append an existing go file (don't output headers).",
Destination: &b.noheader,
},
},
Action: b.bundleAction,
}
}
// Bundler bundles resources into Go code.
type Bundler struct {
name, pkg, out string
prefix string
noheader bool
}
// AddFlags adds all the command line flags for passing to the Bundler.
//
// Deprecated: Access to the individual cli commands are being removed.
func (b *Bundler) AddFlags() {
flag.StringVar(&b.name, "name", "", "The variable name to assign the resource (file mode only)")
flag.StringVar(&b.out, "o", "", "Specify an output file instead of printing to standard output")
flag.StringVar(&b.pkg, "package", "main", "The package to output in headers (if not appending)")
flag.StringVar(&b.prefix, "prefix", "resource", "A prefix for variables (ignored if name is set)")
flag.BoolVar(&b.noheader, "append", false, "Append an existing go file (don't output headers)")
}
// PrintHelp prints the help message for the bundle command.
//
// Deprecated: Access to the individual cli commands are being removed.
func (b *Bundler) PrintHelp(indent string) {
fmt.Println(indent, "The bundle command embeds static content into your go application.")
fmt.Println(indent, "Each resource will have a generated filename unless specified")
fmt.Println(indent, "Command usage: fyne bundle [parameters] file|directory")
}
// Run runs the bundle command.
//
// Deprecated: A better version will be exposed in the future.
func (b *Bundler) Run(args []string) {
if len(args) != 1 {
fyne.LogError("Missing required file or directory parameter after flags", nil)
return
}
outFile := os.Stdout
if b.out != "" {
fileModes := os.O_RDWR | os.O_CREATE | os.O_TRUNC
if b.noheader {
fileModes = os.O_RDWR | os.O_APPEND
}
f, err := os.OpenFile(b.out, fileModes, 0666)
if err == nil {
outFile = f
} else {
if os.IsNotExist(err) {
f, err = os.Create(b.out)
if err == nil {
outFile = f
} else {
fyne.LogError("Unable to read, or create, output file : "+b.out, err)
return
}
} else {
fyne.LogError("Unable to open output file", err)
return
}
}
}
switch stat, err := os.Stat(args[0]); {
case os.IsNotExist(err):
fyne.LogError("Specified file could not be found", err)
case stat.IsDir():
b.noheader = false
b.dirBundle(args[0], outFile)
case b.name != "":
b.prefix = ""
fallthrough
default:
b.doBundle(args[0], outFile)
}
}
func (b *Bundler) bundleAction(ctx *cli.Context) (err error) {
if ctx.Args().Len() != 1 {
return errors.New("missing required file or directory parameter after flags")
}
outFile := os.Stdout
if b.out != "" {
file, closeFile, err := openOutputFile(b.out, b.noheader)
if err != nil {
return err
}
defer func() {
if r := closeFile(); r != nil {
err = r
}
}()
outFile = file
}
arg := ctx.Args().First()
switch stat, err := os.Stat(arg); {
case os.IsNotExist(err):
fyne.LogError("Specified file could not be found", err)
return err
case stat.IsDir():
b.noheader = false
return b.dirBundle(arg, outFile)
case b.name != "":
b.prefix = ""
fallthrough
default:
b.doBundle(arg, outFile)
}
return nil
}
func (b *Bundler) dirBundle(dirpath string, out *os.File) error {
files, err := ioutil.ReadDir(dirpath)
if err != nil {
fyne.LogError("Error reading specified directory", err)
return err
}
for i, file := range files {
filename := file.Name()
if path.Ext(filename) == ".go" {
continue
}
b.name = ""
b.doBundle(path.Join(dirpath, filename), out)
if i == 0 { // only show header on first iteration
b.noheader = true
}
}
return nil
}
// Bundle takes a file (at filepath) and serialises it into Go to be output into
// a generated bundle file. The go file will be part of the specified package
// (pkg) and the data will be assigned to variable named "name". If you are
// appending an existing resource file then pass true to noheader as the headers
// should only be output once per file.
func (b *Bundler) doBundle(filepath string, out *os.File) {
if !b.noheader {
writeHeader(b.pkg, out)
}
if b.name == "" {
b.name = sanitiseName(path.Base(filepath), b.prefix)
}
writeResource(filepath, b.name, out)
}
func openOutputFile(filePath string, noheader bool) (file *os.File, close func() error, err error) {
fileModes := os.O_RDWR | os.O_CREATE | os.O_TRUNC
if noheader {
fileModes = os.O_RDWR | os.O_APPEND
}
f, err := os.OpenFile(filePath, fileModes, 0666)
if err != nil {
if !os.IsNotExist(err) {
fyne.LogError("Unable to open output file", err)
return nil, nil, err
}
// try creating the file
f, err = os.Create(filePath)
if err != nil {
fyne.LogError("Unable to read, or create, output file : "+filePath, err)
return nil, nil, err
}
}
return f, f.Close, nil
}
func sanitiseName(file, prefix string) string {
titled := strings.Title(file)
reg, _ := regexp.Compile("[^a-zA-Z0-9]+")
name := reg.ReplaceAllString(titled, "")
return prefix + name
}
func writeHeader(pkg string, out *os.File) {
fmt.Fprintln(out, fileHeader)
fmt.Fprintln(out)
fmt.Fprintln(out, "package", pkg)
fmt.Fprintln(out)
fmt.Fprintln(out, "import \"fyne.io/fyne/v2\"")
fmt.Fprintln(out)
}
func writeResource(file, name string, f io.Writer) {
res, err := fyne.LoadResourceFromPath(file)
if err != nil {
fyne.LogError("Unable to load file "+file, err)
return
}
staticRes, ok := res.(*fyne.StaticResource)
if !ok {
fyne.LogError("Unable to format resource", fmt.Errorf("unexpected resource type %T", res))
return
}
v := fmt.Sprintf("var %s = &fyne.StaticResource{\n\tStaticName: %q,\n\tStaticContent: []byte(\n\t\t%q),\n}\n", name, staticRes.StaticName, staticRes.StaticContent)
_, err = f.Write([]byte(v))
if err != nil {
fyne.LogError("Unable to write to bundled file", err)
}
}