-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
build.go
418 lines (354 loc) · 12.7 KB
/
build.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
package build
import (
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/pterm/pterm"
"github.com/samber/lo"
"github.com/wailsapp/wails/v2/internal/staticanalysis"
"github.com/wailsapp/wails/v2/pkg/commands/bindings"
"github.com/wailsapp/wails/v2/internal/fs"
"github.com/wailsapp/wails/v2/internal/shell"
"github.com/wailsapp/wails/v2/internal/project"
"github.com/wailsapp/wails/v2/pkg/clilogger"
)
// Mode is the type used to indicate the build modes
type Mode int
const (
// Dev mode
Dev Mode = iota
// Production mode
Production
// Debug build
Debug
)
// Options contains all the build options as well as the project data
type Options struct {
LDFlags string // Optional flags to pass to linker
UserTags []string // Tags to pass to the Go compiler
Logger *clilogger.CLILogger // All output to the logger
OutputType string // EG: desktop, server....
Mode Mode // release or dev
ProjectData *project.Project // The project data
Pack bool // Create a package for the app after building
Platform string // The platform to build for
Arch string // The architecture to build for
Compiler string // The compiler command to use
SkipModTidy bool // Skip mod tidy before compile
IgnoreFrontend bool // Indicates if the frontend does not need building
IgnoreApplication bool // Indicates if the application does not need building
OutputFile string // Override the output filename
BinDirectory string // Directory to use to write the built applications
CleanBinDirectory bool // Indicates if the bin output directory should be cleaned before building
CompiledBinary string // Fully qualified path to the compiled binary
KeepAssets bool // Keep the generated assets/files
Verbosity int // Verbosity level (0 - silent, 1 - default, 2 - verbose)
Compress bool // Compress the final binary
CompressFlags string // Flags to pass to UPX
WebView2Strategy string // WebView2 installer strategy
RunDelve bool // Indicates if we should run delve after the build
WailsJSDir string // Directory to generate the wailsjs module
ForceBuild bool // Force
BundleName string // Bundlename for Mac
TrimPath bool // Use Go's trimpath compiler flag
RaceDetector bool // Build with Go's race detector
WindowsConsole bool // Indicates that the windows console should be kept
Obfuscated bool // Indicates that bound methods should be obfuscated
GarbleArgs string // The arguments for Garble
SkipBindings bool // Skip binding generation
}
// Build the project!
func Build(options *Options) (string, error) {
// Extract logger
outputLogger := options.Logger
// Get working directory
cwd, err := os.Getwd()
if err != nil {
return "", err
}
// wails js dir
options.WailsJSDir = options.ProjectData.GetWailsJSDir()
// Set build directory
options.BinDirectory = filepath.Join(options.ProjectData.GetBuildDir(), "bin")
// Save the project type
options.ProjectData.OutputType = options.OutputType
// Create builder
var builder Builder
switch options.OutputType {
case "desktop":
builder = newDesktopBuilder(options)
case "dev":
builder = newDesktopBuilder(options)
default:
return "", fmt.Errorf("cannot build assets for output type %s", options.ProjectData.OutputType)
}
// Set up our clean up method
defer builder.CleanUp()
// Initialise Builder
builder.SetProjectData(options.ProjectData)
hookArgs := map[string]string{
"${platform}": options.Platform + "/" + options.Arch,
}
for _, hook := range []string{options.Platform + "/" + options.Arch, options.Platform + "/*", "*/*"} {
if err := execPreBuildHook(outputLogger, options, hook, hookArgs); err != nil {
return "", err
}
}
// Create embed directories if they don't exist
if err := CreateEmbedDirectories(cwd, options); err != nil {
return "", err
}
// Generate bindings
if !options.SkipBindings {
err = GenerateBindings(options)
if err != nil {
return "", err
}
}
if !options.IgnoreFrontend {
err = builder.BuildFrontend(outputLogger)
if err != nil {
return "", err
}
}
compileBinary := ""
if !options.IgnoreApplication {
compileBinary, err = execBuildApplication(builder, options)
if err != nil {
return "", err
}
}
hookArgs["${bin}"] = compileBinary
for _, hook := range []string{options.Platform + "/" + options.Arch, options.Platform + "/*", "*/*"} {
if err := execPostBuildHook(outputLogger, options, hook, hookArgs); err != nil {
return "", err
}
}
return compileBinary, nil
}
func CreateEmbedDirectories(cwd string, buildOptions *Options) error {
path := cwd
if buildOptions.ProjectData != nil {
path = buildOptions.ProjectData.Path
}
embedDetails, err := staticanalysis.GetEmbedDetails(path)
if err != nil {
return err
}
for _, embedDetail := range embedDetails {
fullPath := embedDetail.GetFullPath()
if _, err := os.Stat(fullPath); os.IsNotExist(err) {
err := os.MkdirAll(fullPath, 0755)
if err != nil {
return err
}
f, err := os.Create(filepath.Join(fullPath, "gitkeep"))
if err != nil {
return err
}
_ = f.Close()
}
}
return nil
}
func fatal(message string) {
printer := pterm.PrefixPrinter{
MessageStyle: &pterm.ThemeDefault.FatalMessageStyle,
Prefix: pterm.Prefix{
Style: &pterm.ThemeDefault.FatalPrefixStyle,
Text: " FATAL ",
},
}
printer.Println(message)
os.Exit(1)
}
func printBulletPoint(text string, args ...any) {
item := pterm.BulletListItem{
Level: 2,
Text: text,
}
t, err := pterm.DefaultBulletList.WithItems([]pterm.BulletListItem{item}).Srender()
if err != nil {
fatal(err.Error())
}
t = strings.Trim(t, "\n\r")
pterm.Printf(t, args...)
}
func GenerateBindings(buildOptions *Options) error {
obfuscated := buildOptions.Obfuscated
if obfuscated {
printBulletPoint("Generating obfuscated bindings: ")
buildOptions.UserTags = append(buildOptions.UserTags, "obfuscated")
} else {
printBulletPoint("Generating bindings: ")
}
// Generate Bindings
output, err := bindings.GenerateBindings(bindings.Options{
Tags: buildOptions.UserTags,
GoModTidy: !buildOptions.SkipModTidy,
TsPrefix: buildOptions.ProjectData.Bindings.TsGeneration.Prefix,
TsSuffix: buildOptions.ProjectData.Bindings.TsGeneration.Suffix,
})
if err != nil {
return err
}
if buildOptions.Verbosity == VERBOSE {
pterm.Info.Println(output)
}
pterm.Println("Done.")
return nil
}
func execBuildApplication(builder Builder, options *Options) (string, error) {
// If we are building for windows, we will need to generate the asset bundle before
// compilation. This will be a .syso file in the project root
if options.Pack && options.Platform == "windows" {
printBulletPoint("Generating application assets: ")
err := packageApplicationForWindows(options)
if err != nil {
return "", err
}
pterm.Println("Done.")
// When we finish, we will want to remove the syso file
defer func() {
err := os.Remove(filepath.Join(options.ProjectData.Path, options.ProjectData.Name+"-res.syso"))
if err != nil {
fatal(err.Error())
}
}()
}
// Compile the application
printBulletPoint("Compiling application: ")
if options.Platform == "darwin" && options.Arch == "universal" {
outputFile := builder.OutputFilename(options)
amd64Filename := outputFile + "-amd64"
arm64Filename := outputFile + "-arm64"
// Build amd64 first
options.Arch = "amd64"
options.OutputFile = amd64Filename
options.CleanBinDirectory = false
if options.Verbosity == VERBOSE {
pterm.Println("Building AMD64 Target: " + filepath.Join(options.BinDirectory, options.OutputFile))
}
err := builder.CompileProject(options)
if err != nil {
return "", err
}
// Build arm64
options.Arch = "arm64"
options.OutputFile = arm64Filename
options.CleanBinDirectory = false
if options.Verbosity == VERBOSE {
pterm.Println("Building ARM64 Target: " + filepath.Join(options.BinDirectory, options.OutputFile))
}
err = builder.CompileProject(options)
if err != nil {
return "", err
}
// Run lipo
if options.Verbosity == VERBOSE {
pterm.Println(fmt.Sprintf("Running lipo: lipo -create -output %s %s %s", outputFile, amd64Filename, arm64Filename))
}
_, stderr, err := shell.RunCommand(options.BinDirectory, "lipo", "-create", "-output", outputFile, amd64Filename, arm64Filename)
if err != nil {
return "", fmt.Errorf("%s - %s", err.Error(), stderr)
}
// Remove temp binaries
err = fs.DeleteFile(filepath.Join(options.BinDirectory, amd64Filename))
if err != nil {
return "", err
}
err = fs.DeleteFile(filepath.Join(options.BinDirectory, arm64Filename))
if err != nil {
return "", err
}
options.ProjectData.OutputFilename = outputFile
options.CompiledBinary = filepath.Join(options.BinDirectory, outputFile)
} else {
err := builder.CompileProject(options)
if err != nil {
return "", err
}
}
pterm.Println("Done.")
// Do we need to pack the app for non-windows?
if options.Pack && options.Platform != "windows" {
printBulletPoint("Packaging application: ")
// TODO: Allow cross platform build
err := packageProject(options, runtime.GOOS)
if err != nil {
return "", err
}
pterm.Println("Done.")
}
if options.Platform == "windows" {
const nativeWebView2Loader = "native_webview2loader"
tags := options.UserTags
if lo.Contains(tags, nativeWebView2Loader) {
message := "You are using the legacy native WebView2Loader. This loader will be deprecated in the near future. Please report any bugs related to the new loader: https://github.com/wailsapp/wails/issues/2004"
pterm.Warning.Println(message)
} else {
tags = append(tags, nativeWebView2Loader)
message := fmt.Sprintf("Wails is now using the new Go WebView2Loader. If you encounter any issues with it, please report them to https://github.com/wailsapp/wails/issues/2004. You could also use the old legacy loader with `-tags %s`, but keep in mind this will be deprecated in the near future.", strings.Join(tags, ","))
pterm.Info.Println(message)
}
}
if options.Platform == "darwin" && options.Mode == Debug {
pterm.Warning.Println("A darwin debug build contains private APIs, please don't distribute this build. Please use it only as a test build for testing and debug purposes.")
}
return options.CompiledBinary, nil
}
func execPreBuildHook(outputLogger *clilogger.CLILogger, options *Options, hookIdentifier string, argReplacements map[string]string) error {
preBuildHook := options.ProjectData.PreBuildHooks[hookIdentifier]
if preBuildHook == "" {
return nil
}
return executeBuildHook(outputLogger, options, hookIdentifier, argReplacements, preBuildHook, "pre")
}
func execPostBuildHook(outputLogger *clilogger.CLILogger, options *Options, hookIdentifier string, argReplacements map[string]string) error {
postBuildHook := options.ProjectData.PostBuildHooks[hookIdentifier]
if postBuildHook == "" {
return nil
}
return executeBuildHook(outputLogger, options, hookIdentifier, argReplacements, postBuildHook, "post")
}
func executeBuildHook(outputLogger *clilogger.CLILogger, options *Options, hookIdentifier string, argReplacements map[string]string, buildHook string, hookName string) error {
if !options.ProjectData.RunNonNativeBuildHooks {
if hookIdentifier == "" {
// That's the global hook
} else {
platformOfHook := strings.Split(hookIdentifier, "/")[0]
if platformOfHook == "*" {
// That's OK, we don't have a specific platform of the hook
} else if platformOfHook == runtime.GOOS {
// The hook is for host platform
} else {
// Skip a hook which is not native
printBulletPoint(fmt.Sprintf("Non native build hook '%s': Skipping.", hookIdentifier))
return nil
}
}
}
printBulletPoint("Executing %s build hook '%s': ", hookName, hookIdentifier)
args := strings.Split(buildHook, " ")
for i, arg := range args {
newArg := argReplacements[arg]
if newArg == "" {
continue
}
args[i] = newArg
}
if options.Verbosity == VERBOSE {
pterm.Info.Println(strings.Join(args, " "))
}
stdout, stderr, err := shell.RunCommand(options.BinDirectory, args[0], args[1:]...)
if options.Verbosity == VERBOSE {
pterm.Info.Println(stdout)
}
if err != nil {
return fmt.Errorf("%s - %s", err.Error(), stderr)
}
pterm.Println("Done.")
return nil
}