forked from fyne-io/fyne
/
package.go
526 lines (467 loc) · 14.3 KB
/
package.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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
package commands
import (
"errors"
"flag"
"fmt"
"image"
_ "image/jpeg" // import image encodings
"image/png" // import image encodings
"log"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
_ "github.com/fyne-io/image/ico" // import image encodings
"github.com/urfave/cli/v2"
"golang.org/x/mod/modfile"
"golang.org/x/mod/module"
"fyne.io/fyne/v2"
"fyne.io/fyne/v2/cmd/fyne/internal/metadata"
)
const (
defaultAppBuild = 1
defaultAppVersion = "0.0.1"
)
// Package returns the cli command for packaging fyne applications
func Package() *cli.Command {
p := NewPackager()
return &cli.Command{
Name: "package",
Usage: "Packages an application for distribution.",
Description: "You may specify the -executable to package, otherwise -sourceDir will be built.",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "target",
Aliases: []string{"os"},
Usage: "The mobile platform to target (android, android/arm, android/arm64, android/amd64, android/386, ios, iossimulator, wasm, js, web).",
Destination: &p.os,
},
&cli.StringFlag{
Name: "executable",
Aliases: []string{"exe"},
Usage: "The path to the executable, default is the current dir main binary",
Destination: &p.exe,
},
&cli.StringFlag{
Name: "name",
Usage: "The name of the application, default is the executable file name",
Destination: &p.Name,
},
&cli.StringFlag{
Name: "tags",
Usage: "A comma-separated list of build tags.",
Destination: &p.tags,
},
&cli.StringFlag{
Name: "appVersion",
Usage: "Version number in the form x, x.y or x.y.z semantic version",
Destination: &p.AppVersion,
},
&cli.IntFlag{
Name: "appBuild",
Usage: "Build number, should be greater than 0 and incremented for each build",
Destination: &p.AppBuild,
},
&cli.StringFlag{
Name: "sourceDir",
Aliases: []string{"src"},
Usage: "The directory to package, if executable is not set.",
Destination: &p.srcDir,
},
&cli.StringFlag{
Name: "icon",
Usage: "The name of the application icon file.",
Value: "",
Destination: &p.icon,
},
&cli.BoolFlag{
Name: "use-raw-icon",
Usage: "Skip any OS-specific icon pre-processing",
Value: false,
Destination: &p.rawIcon,
},
&cli.StringFlag{
Name: "appID",
Aliases: []string{"id"},
Usage: "For Android, darwin, iOS and Windows targets an appID in the form of a reversed domain name is required, for ios this must match a valid provisioning profile",
Destination: &p.AppID,
},
&cli.StringFlag{
Name: "certificate",
Aliases: []string{"cert"},
Usage: "iOS/macOS/Windows: name of the certificate to sign the build",
Destination: &p.certificate,
},
&cli.StringFlag{
Name: "profile",
Usage: "iOS/macOS: name of the provisioning profile for this build",
Destination: &p.profile,
Value: "XCWildcard",
},
&cli.BoolFlag{
Name: "release",
Usage: "Enable installation in release mode (disable debug etc).",
Destination: &p.release,
},
&cli.GenericFlag{
Name: "metadata",
Usage: "Specify custom metadata key value pair that you do not want to store in your FyneApp.toml (key=value)",
Value: &p.customMetadata,
},
},
Action: func(_ *cli.Context) error {
if p.customMetadata.m == nil {
p.customMetadata.m = map[string]string{}
}
return p.Package()
},
}
}
// Packager wraps executables into full GUI app packages.
type Packager struct {
*appData
srcDir, dir, exe, os string
install, release, distribution bool
certificate, profile string // optional flags for releasing
tags, category string
tempDir string
customMetadata keyValueFlag
linuxAndBSDMetadata *metadata.LinuxAndBSD
}
// NewPackager returns a command that can handle the packaging a GUI apps built using Fyne from local source code.
func NewPackager() *Packager {
return &Packager{appData: &appData{}}
}
// AddFlags adds the flags for interacting with the package command.
//
// Deprecated: Access to the individual cli commands are being removed.
func (p *Packager) AddFlags() {
flag.StringVar(&p.os, "os", "", "The operating system to target (android, android/arm, android/arm64, android/amd64, android/386, darwin, freebsd, ios, linux, netbsd, openbsd, windows, wasm)")
flag.StringVar(&p.exe, "executable", "", "Specify an existing binary instead of building before package")
flag.StringVar(&p.srcDir, "sourceDir", "", "The directory to package, if executable is not set")
flag.StringVar(&p.Name, "name", "", "The name of the application, default is the executable file name")
flag.StringVar(&p.icon, "icon", "", "The name of the application icon file")
flag.StringVar(&p.AppID, "appID", "", "For ios or darwin targets an appID is required, for ios this must \nmatch a valid provisioning profile")
flag.StringVar(&p.AppVersion, "appVersion", "", "Version number in the form x, x.y or x.y.z semantic version")
flag.IntVar(&p.AppBuild, "appBuild", 0, "Build number, should be greater than 0 and incremented for each build")
flag.BoolVar(&p.release, "release", false, "Should this package be prepared for release? (disable debug etc)")
flag.StringVar(&p.tags, "tags", "", "A comma-separated list of build tags")
}
// PrintHelp prints the help for the package command.
//
// Deprecated: Access to the individual cli commands are being removed.
func (*Packager) PrintHelp(indent string) {
fmt.Println(indent, "The package command prepares an application for installation and testing.")
fmt.Println(indent, "You may specify the -executable to package, otherwise -sourceDir will be built.")
fmt.Println(indent, "Command usage: fyne package [parameters]")
}
// Run runs the package command.
//
// Deprecated: A better version will be exposed in the future.
func (p *Packager) Run(_ []string) {
err := p.validate()
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(1)
}
err = p.doPackage(nil)
if err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err.Error())
os.Exit(1)
}
}
// Package starts the packaging process
func (p *Packager) Package() error {
err := p.validate()
if err != nil {
return err
}
return p.packageWithoutValidate()
}
func (p *Packager) packageWithoutValidate() error {
err := p.doPackage(nil)
if err != nil {
return err
}
data, err := metadata.LoadStandard(p.srcDir)
if err != nil {
return nil // no metadata to update
}
data.Details.Build++
return metadata.SaveStandard(data, p.srcDir)
}
func (p *Packager) buildPackage(runner runner, tags []string) ([]string, error) {
if p.os != "web" {
b := &Builder{
os: p.os,
srcdir: p.srcDir,
target: p.exe,
release: p.release,
tags: tags,
runner: runner,
appData: p.appData,
}
return []string{p.exe}, b.build()
}
bWasm := &Builder{
os: "wasm",
srcdir: p.srcDir,
target: p.exe + ".wasm",
release: p.release,
tags: tags,
runner: runner,
appData: p.appData,
}
err := bWasm.build()
if err != nil {
return nil, err
}
if runtime.GOOS == "windows" {
return []string{bWasm.target}, nil
}
bGopherJS := &Builder{
os: "js",
srcdir: p.srcDir,
target: p.exe + ".js",
release: p.release,
tags: tags,
runner: runner,
appData: p.appData,
}
err = bGopherJS.build()
if err != nil {
return nil, err
}
return []string{bWasm.target, bGopherJS.target}, nil
}
func (p *Packager) combinedVersion() string {
versions := strings.Split(p.AppVersion, ".")
for len(versions) < 3 {
versions = append(versions, "0")
}
appVersion := strings.Join(versions, ".")
return fmt.Sprintf("%s.%d", appVersion, p.AppBuild)
}
func (p *Packager) doPackage(runner runner) error {
// sensible defaults - validation deemed them optional
if p.AppVersion == "" {
p.AppVersion = defaultAppVersion
}
if p.AppBuild <= 0 {
p.AppBuild = defaultAppBuild
}
defer os.RemoveAll(p.tempDir)
var tags []string
if p.tags != "" {
tags = strings.Split(p.tags, ",")
}
if !util.Exists(p.exe) && !util.IsMobile(p.os) {
files, err := p.buildPackage(runner, tags)
if err != nil {
return fmt.Errorf("error building application: %w", err)
}
for _, file := range files {
if p.os != "web" && !util.Exists(file) {
return fmt.Errorf("unable to build directory to expected executable, %s", file)
}
}
if p.os != "windows" {
defer p.removeBuild(files)
}
}
if util.IsMobile(p.os) { // we don't use the normal build command for mobile so inject before gomobile...
close, err := injectMetadataIfPossible(newCommand("go"), p.dir, p.appData, createMetadataInitFile)
if err != nil {
fyne.LogError("Failed to inject metadata init file, omitting metadata", err)
} else if close != nil {
defer close()
}
}
switch p.os {
case "darwin":
return p.packageDarwin()
case "linux", "openbsd", "freebsd", "netbsd":
return p.packageUNIX()
case "windows":
return p.packageWindows(tags)
case "android/arm", "android/arm64", "android/amd64", "android/386", "android":
return p.packageAndroid(p.os, tags)
case "ios", "iossimulator":
return p.packageIOS(p.os, tags)
case "wasm":
return p.packageWasm()
case "js":
return p.packageGopherJS()
case "web":
return p.packageWeb()
default:
return fmt.Errorf("unsupported target operating system \"%s\"", p.os)
}
}
func (p *Packager) removeBuild(files []string) {
for _, file := range files {
err := os.Remove(file)
if err != nil {
log.Println("Unable to remove temporary build file", p.exe)
}
}
}
func (p *Packager) validate() (err error) {
p.tempDir, err = os.MkdirTemp("", "fyne-package-*")
defer func() {
if err != nil {
_ = os.RemoveAll(p.tempDir)
}
}()
if p.os == "" {
p.os = targetOS()
}
baseDir, err := os.Getwd()
if err != nil {
return fmt.Errorf("unable to get the current directory, needed to find main executable: %w", err)
}
if p.dir == "" {
p.dir = baseDir
}
if p.srcDir == "" {
p.srcDir = baseDir
} else {
if p.os == "ios" || p.os == "android" {
return errors.New("parameter -sourceDir is currently not supported for mobile builds. " +
"Change directory to the main package and try again")
}
p.srcDir = util.EnsureAbsPath(p.srcDir)
}
os.Chdir(p.srcDir)
p.appData.CustomMetadata = p.customMetadata.m
data, err := metadata.LoadStandard(p.srcDir)
if err == nil {
// When icon path specified in metadata file, we should make it relative to metadata file
if data.Details.Icon != "" {
data.Details.Icon = util.MakePathRelativeTo(p.srcDir, data.Details.Icon)
}
p.appData.Release = p.release
p.appData.mergeMetadata(data)
p.linuxAndBSDMetadata = data.LinuxAndBSD
}
exeName := calculateExeName(p.srcDir, p.os)
if p.exe == "" {
p.exe = filepath.Join(p.srcDir, exeName)
if util.Exists(p.exe) { // the exe was not specified, assume stale
p.removeBuild([]string{p.exe})
}
} else if p.os == "ios" || p.os == "android" {
_, _ = fmt.Fprint(os.Stderr, "Parameter -executable is ignored for mobile builds.\n")
}
if p.Name == "" {
p.Name = exeName
}
if p.icon == "" || p.icon == "Icon.png" {
p.icon = filepath.Join(p.srcDir, "Icon.png")
}
if !util.Exists(p.icon) {
return errors.New("Missing application icon at \"" + p.icon + "\"")
}
if strings.ToLower(filepath.Ext(p.icon)) != ".png" {
tmp, err := p.normaliseIcon(p.icon)
if err != nil {
return err
}
p.icon = tmp
}
p.AppID, err = validateAppID(p.AppID, p.os, p.Name, p.release)
if err != nil {
return err
}
if p.AppVersion != "" && !isValidVersion(p.AppVersion) {
return errors.New("invalid -appVersion parameter, integer and '.' characters only up to x.y.z")
}
return nil
}
func calculateExeName(sourceDir, osys string) string {
exeName := filepath.Base(sourceDir)
/* #nosec */
if data, err := os.ReadFile(filepath.Join(sourceDir, "go.mod")); err == nil {
modulePath := modfile.ModulePath(data)
moduleName, _, ok := module.SplitPathVersion(modulePath)
if ok {
paths := strings.Split(moduleName, "/")
name := paths[len(paths)-1]
if name != "" {
exeName = name
}
}
}
if osys == "windows" {
exeName = exeName + ".exe"
}
return exeName
}
func isValidVersion(ver string) bool {
nums := strings.Split(ver, ".")
if len(nums) == 0 || len(nums) > 3 {
return false
}
for _, num := range nums {
if _, err := strconv.Atoi(num); err != nil {
return false
}
}
return true
}
// normaliseIcon takes a non-png image file and converts it to PNG for use in packaging.
// Successful conversion will return a path to the new file.
// Any errors that occur will be returned with an empty string for new path.
func (p *Packager) normaliseIcon(path string) (string, error) {
// convert icon
img, err := os.Open(path)
if err != nil {
return "", fmt.Errorf("failed to open source image: %w", err)
}
defer img.Close()
srcImg, _, err := image.Decode(img)
if err != nil {
return "", fmt.Errorf("failed to decode source image: %w", err)
}
out, err := os.CreateTemp(p.tempDir, "fyne-ico-*.png")
if err != nil {
return "", fmt.Errorf("failed to open image output file: %w", err)
}
tmpPath := out.Name()
defer out.Close()
err = png.Encode(out, srcImg)
return tmpPath, err
}
func validateAppID(appID, os, name string, release bool) (string, error) {
// old darwin compatibility
if os == "darwin" {
if appID == "" {
return "com.example." + name, nil
}
} else if os == "ios" || util.IsAndroid(os) || (os == "windows" && release) {
// all mobile, and for windows when releasing, needs a unique id - usually reverse DNS style
if appID == "" {
return "", errors.New("missing appID parameter for package")
} else if !strings.Contains(appID, ".") {
return "", errors.New("appID must be globally unique and contain at least 1 '.'")
} else if util.IsAndroid(os) {
if strings.Contains(appID, "-") {
return "", errors.New("appID can not contain '-'")
}
// appID package names can not start with '_' or a number
packageNames := strings.Split(appID, ".")
for _, name := range packageNames {
if len(name) == 0 {
continue
}
if name[0] == '_' {
return "", fmt.Errorf("appID package names can not start with '_' (%s)", name)
} else if name[0] >= '0' && name[0] <= '9' {
return "", fmt.Errorf("appID package names can not start with a number (%s)", name)
}
}
}
}
return appID, nil
}