| 1 | // Copyright 2015 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | //go:generate go run gendex.go -o dex.go |
| 6 | |
| 7 | package main |
| 8 | |
| 9 | import ( |
| 10 | "bufio" |
| 11 | "errors" |
| 12 | "fmt" |
| 13 | "io" |
| 14 | "os" |
| 15 | "os/exec" |
| 16 | "regexp" |
| 17 | "strconv" |
| 18 | "strings" |
| 19 | |
| 20 | "golang.org/x/mobile/internal/sdkpath" |
| 21 | "golang.org/x/tools/go/packages" |
| 22 | ) |
| 23 | |
| 24 | var tmpdir string |
| 25 | |
| 26 | var cmdBuild = &command{ |
| 27 | run: runBuild, |
| 28 | Name: "build", |
| 29 | Usage: "[-target android|" + strings.Join(applePlatforms, "|") + "] [-o output] [-bundleid bundleID] [build flags] [package]", |
| 30 | Short: "compile android APK and iOS app", |
| 31 | Long: ` |
| 32 | Build compiles and encodes the app named by the import path. |
| 33 | |
| 34 | The named package must define a main function. |
| 35 | |
| 36 | The -target flag takes either android (the default), or one or more |
| 37 | comma-delimited Apple platforms (` + strings.Join(applePlatforms, ", ") + `). |
| 38 | |
| 39 | For -target android, if an AndroidManifest.xml is defined in the |
| 40 | package directory, it is added to the APK output. Otherwise, a default |
| 41 | manifest is generated. By default, this builds a fat APK for all supported |
| 42 | instruction sets (arm, 386, amd64, arm64). A subset of instruction sets can |
| 43 | be selected by specifying target type with the architecture name. E.g. |
| 44 | -target=android/arm,android/386. |
| 45 | |
| 46 | For Apple -target platforms, gomobile must be run on an OS X machine with |
| 47 | Xcode installed. |
| 48 | |
| 49 | By default, -target ios will generate an XCFramework for both ios |
| 50 | and iossimulator. Multiple Apple targets can be specified, creating a "fat" |
| 51 | XCFramework with each slice. To generate a fat XCFramework that supports |
| 52 | iOS, macOS, and macCatalyst for all supportec architectures (amd64 and arm64), |
| 53 | specify -target ios,macos,maccatalyst. A subset of instruction sets can be |
| 54 | selectged by specifying the platform with an architecture name. E.g. |
| 55 | -target=ios/arm64,maccatalyst/arm64. |
| 56 | |
| 57 | If the package directory contains an assets subdirectory, its contents |
| 58 | are copied into the output. |
| 59 | |
| 60 | Flag -iosversion sets the minimal version of the iOS SDK to compile against. |
| 61 | The default version is 13.0. |
| 62 | |
| 63 | Flag -androidapi sets the Android API version to compile against. |
| 64 | The default and minimum is 16. |
| 65 | |
| 66 | The -bundleid flag is required for -target ios and sets the bundle ID to use |
| 67 | with the app. |
| 68 | |
| 69 | The -o flag specifies the output file name. If not specified, the |
| 70 | output file name depends on the package built. |
| 71 | |
| 72 | The -v flag provides verbose output, including the list of packages built. |
| 73 | |
| 74 | The build flags -a, -i, -n, -x, -gcflags, -ldflags, -overlay, -tags, -trimpath, |
| 75 | and -work are shared with the build command. For documentation, see |
| 76 | 'go help build'. |
| 77 | `, |
| 78 | } |
| 79 | |
| 80 | func runBuild(cmd *command) (err error) { |
| 81 | _, err = runBuildImpl(cmd) |
| 82 | return |
| 83 | } |
| 84 | |
| 85 | // runBuildImpl builds a package for mobiles based on the given commands. |
| 86 | // runBuildImpl returns a built package information and an error if exists. |
| 87 | func runBuildImpl(cmd *command) (*packages.Package, error) { |
| 88 | cleanup, err := buildEnvInit() |
| 89 | if err != nil { |
| 90 | return nil, err |
| 91 | } |
| 92 | defer cleanup() |
| 93 | |
| 94 | args := cmd.flag.Args() |
| 95 | |
| 96 | targets, err := parseBuildTarget(buildTarget) |
| 97 | if err != nil { |
| 98 | return nil, fmt.Errorf(`invalid -target=%q: %v`, buildTarget, err) |
| 99 | } |
| 100 | |
| 101 | var buildPath string |
| 102 | switch len(args) { |
| 103 | case 0: |
| 104 | buildPath = "." |
| 105 | case 1: |
| 106 | buildPath = args[0] |
| 107 | default: |
| 108 | cmd.usage() |
| 109 | os.Exit(1) |
| 110 | } |
| 111 | |
| 112 | // TODO(ydnar): this should work, unless build tags affect loading a single package. |
| 113 | // Should we try to import packages with different build tags per platform? |
| 114 | pkgs, err := packages.Load(packagesConfig(targets[0]), buildPath) |
| 115 | if err != nil { |
| 116 | return nil, err |
| 117 | } |
| 118 | |
| 119 | // len(pkgs) can be more than 1 e.g., when the specified path includes `...`. |
| 120 | if len(pkgs) != 1 { |
| 121 | cmd.usage() |
| 122 | os.Exit(1) |
| 123 | } |
| 124 | |
| 125 | pkg := pkgs[0] |
| 126 | |
| 127 | if pkg.Name != "main" && buildO != "" { |
| 128 | return nil, fmt.Errorf("cannot set -o when building non-main package") |
| 129 | } |
| 130 | |
| 131 | var nmpkgs map[string]bool |
| 132 | switch { |
| 133 | case isAndroidPlatform(targets[0].platform): |
| 134 | if pkg.Name != "main" { |
| 135 | for _, t := range targets { |
| 136 | if err := goBuild(pkg.PkgPath, androidEnv[t.arch]); err != nil { |
| 137 | return nil, err |
| 138 | } |
| 139 | } |
| 140 | return pkg, nil |
| 141 | } |
| 142 | nmpkgs, err = goAndroidBuild(pkg, targets) |
| 143 | if err != nil { |
| 144 | return nil, err |
| 145 | } |
| 146 | case isApplePlatform(targets[0].platform): |
| 147 | if !xcodeAvailable() { |
| 148 | return nil, fmt.Errorf("-target=%s requires XCode", buildTarget) |
| 149 | } |
| 150 | if pkg.Name != "main" { |
| 151 | for _, t := range targets { |
| 152 | // Catalyst support requires iOS 13+ |
| 153 | v, _ := strconv.ParseFloat(buildIOSVersion, 64) |
| 154 | if t.platform == "maccatalyst" && v < 13.0 { |
| 155 | return nil, errors.New("catalyst requires -iosversion=13 or higher") |
| 156 | } |
| 157 | if err := goBuild(pkg.PkgPath, appleEnv[t.String()]); err != nil { |
| 158 | return nil, err |
| 159 | } |
| 160 | } |
| 161 | return pkg, nil |
| 162 | } |
| 163 | if buildBundleID == "" { |
| 164 | return nil, fmt.Errorf("-target=%s requires -bundleid set", buildTarget) |
| 165 | } |
| 166 | nmpkgs, err = goAppleBuild(pkg, buildBundleID, targets) |
| 167 | if err != nil { |
| 168 | return nil, err |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | if !nmpkgs["golang.org/x/mobile/app"] { |
| 173 | return nil, fmt.Errorf(`%s does not import "golang.org/x/mobile/app"`, pkg.PkgPath) |
| 174 | } |
| 175 | |
| 176 | return pkg, nil |
| 177 | } |
| 178 | |
| 179 | var nmRE = regexp.MustCompile(`[0-9a-f]{8} t _?(?:.*/vendor/)?(golang.org/x.*/[^.]*)`) |
| 180 | |
| 181 | func extractPkgs(nm string, path string) (map[string]bool, error) { |
| 182 | if buildN { |
| 183 | return map[string]bool{"golang.org/x/mobile/app": true}, nil |
| 184 | } |
| 185 | r, w := io.Pipe() |
| 186 | cmd := exec.Command(nm, path) |
| 187 | cmd.Stdout = w |
| 188 | cmd.Stderr = os.Stderr |
| 189 | |
| 190 | nmpkgs := make(map[string]bool) |
| 191 | errc := make(chan error, 1) |
| 192 | go func() { |
| 193 | s := bufio.NewScanner(r) |
| 194 | for s.Scan() { |
| 195 | if res := nmRE.FindStringSubmatch(s.Text()); res != nil { |
| 196 | nmpkgs[res[1]] = true |
| 197 | } |
| 198 | } |
| 199 | errc <- s.Err() |
| 200 | }() |
| 201 | |
| 202 | err := cmd.Run() |
| 203 | w.Close() |
| 204 | if err != nil { |
| 205 | return nil, fmt.Errorf("%s %s: %v", nm, path, err) |
| 206 | } |
| 207 | if err := <-errc; err != nil { |
| 208 | return nil, fmt.Errorf("%s %s: %v", nm, path, err) |
| 209 | } |
| 210 | return nmpkgs, nil |
| 211 | } |
| 212 | |
| 213 | var xout io.Writer = os.Stderr |
| 214 | |
| 215 | func printcmd(format string, args ...interface{}) { |
| 216 | cmd := fmt.Sprintf(format+"\n", args...) |
| 217 | if tmpdir != "" { |
| 218 | cmd = strings.Replace(cmd, tmpdir, "$WORK", -1) |
| 219 | } |
| 220 | if androidHome, err := sdkpath.AndroidHome(); err == nil { |
| 221 | cmd = strings.Replace(cmd, androidHome, "$ANDROID_HOME", -1) |
| 222 | } |
| 223 | if gomobilepath != "" { |
| 224 | cmd = strings.Replace(cmd, gomobilepath, "$GOMOBILE", -1) |
| 225 | } |
| 226 | if gopath := goEnv("GOPATH"); gopath != "" { |
| 227 | cmd = strings.Replace(cmd, gopath, "$GOPATH", -1) |
| 228 | } |
| 229 | if env := os.Getenv("HOMEPATH"); env != "" { |
| 230 | cmd = strings.Replace(cmd, env, "$HOMEPATH", -1) |
| 231 | } |
| 232 | fmt.Fprint(xout, cmd) |
| 233 | } |
| 234 | |
| 235 | // "Build flags", used by multiple commands. |
| 236 | var ( |
| 237 | buildA bool // -a |
| 238 | buildI bool // -i |
| 239 | buildN bool // -n |
| 240 | buildV bool // -v |
| 241 | buildX bool // -x |
| 242 | buildO string // -o |
| 243 | buildGcflags string // -gcflags |
| 244 | buildLdflags string // -ldflags |
| 245 | buildOverlay string // -overlay |
| 246 | buildTarget string // -target |
| 247 | buildTrimpath bool // -trimpath |
| 248 | buildWork bool // -work |
| 249 | buildBundleID string // -bundleid |
| 250 | buildIOSVersion string // -iosversion |
| 251 | buildAndroidAPI int // -androidapi |
| 252 | buildTags stringsFlag // -tags |
| 253 | ) |
| 254 | |
| 255 | func addBuildFlags(cmd *command) { |
| 256 | cmd.flag.StringVar(&buildO, "o", "", "") |
| 257 | cmd.flag.StringVar(&buildGcflags, "gcflags", "", "") |
| 258 | cmd.flag.StringVar(&buildLdflags, "ldflags", "", "") |
| 259 | cmd.flag.StringVar(&buildOverlay, "overlay", "", "") |
| 260 | cmd.flag.StringVar(&buildTarget, "target", "android", "") |
| 261 | cmd.flag.StringVar(&buildBundleID, "bundleid", "", "") |
| 262 | cmd.flag.StringVar(&buildIOSVersion, "iosversion", "13.0", "") |
| 263 | cmd.flag.IntVar(&buildAndroidAPI, "androidapi", minAndroidAPI, "") |
| 264 | |
| 265 | cmd.flag.BoolVar(&buildA, "a", false, "") |
| 266 | cmd.flag.BoolVar(&buildI, "i", false, "") |
| 267 | cmd.flag.BoolVar(&buildTrimpath, "trimpath", false, "") |
| 268 | cmd.flag.Var(&buildTags, "tags", "") |
| 269 | } |
| 270 | |
| 271 | func addBuildFlagsNVXWork(cmd *command) { |
| 272 | cmd.flag.BoolVar(&buildN, "n", false, "") |
| 273 | cmd.flag.BoolVar(&buildV, "v", false, "") |
| 274 | cmd.flag.BoolVar(&buildX, "x", false, "") |
| 275 | cmd.flag.BoolVar(&buildWork, "work", false, "") |
| 276 | } |
| 277 | |
| 278 | func init() { |
| 279 | addBuildFlags(cmdBuild) |
| 280 | addBuildFlagsNVXWork(cmdBuild) |
| 281 | |
| 282 | addBuildFlags(cmdInstall) |
| 283 | addBuildFlagsNVXWork(cmdInstall) |
| 284 | |
| 285 | addBuildFlagsNVXWork(cmdInit) |
| 286 | |
| 287 | addBuildFlags(cmdBind) |
| 288 | addBuildFlagsNVXWork(cmdBind) |
| 289 | |
| 290 | addBuildFlagsNVXWork(cmdClean) |
| 291 | } |
| 292 | |
| 293 | func goBuild(src string, env []string, args ...string) error { |
| 294 | return goCmd("build", []string{src}, env, args...) |
| 295 | } |
| 296 | |
| 297 | func goBuildAt(at string, src string, env []string, args ...string) error { |
| 298 | return goCmdAt(at, "build", []string{src}, env, args...) |
| 299 | } |
| 300 | |
| 301 | func goInstall(srcs []string, env []string, args ...string) error { |
| 302 | return goCmd("install", srcs, env, args...) |
| 303 | } |
| 304 | |
| 305 | func goCmd(subcmd string, srcs []string, env []string, args ...string) error { |
| 306 | return goCmdAt("", subcmd, srcs, env, args...) |
| 307 | } |
| 308 | |
| 309 | func goCmdAt(at string, subcmd string, srcs []string, env []string, args ...string) error { |
| 310 | cmd := exec.Command("go", subcmd) |
| 311 | tags := buildTags |
| 312 | if len(tags) > 0 { |
| 313 | cmd.Args = append(cmd.Args, "-tags", strings.Join(tags, ",")) |
| 314 | } |
| 315 | if buildV { |
| 316 | cmd.Args = append(cmd.Args, "-v") |
| 317 | } |
| 318 | if subcmd != "install" && buildI { |
| 319 | cmd.Args = append(cmd.Args, "-i") |
| 320 | } |
| 321 | if buildX { |
| 322 | cmd.Args = append(cmd.Args, "-x") |
| 323 | } |
| 324 | if buildA { |
| 325 | cmd.Args = append(cmd.Args, "-a") |
| 326 | } |
| 327 | if buildGcflags != "" { |
| 328 | cmd.Args = append(cmd.Args, "-gcflags", buildGcflags) |
| 329 | } |
| 330 | if buildLdflags != "" { |
| 331 | cmd.Args = append(cmd.Args, "-ldflags", buildLdflags) |
| 332 | } |
| 333 | if buildOverlay != "" { |
| 334 | cmd.Args = append(cmd.Args, "-overlay", buildOverlay) |
| 335 | } |
| 336 | if buildTrimpath { |
| 337 | cmd.Args = append(cmd.Args, "-trimpath") |
| 338 | } |
| 339 | if buildWork { |
| 340 | cmd.Args = append(cmd.Args, "-work") |
| 341 | } |
| 342 | cmd.Args = append(cmd.Args, args...) |
| 343 | cmd.Args = append(cmd.Args, srcs...) |
| 344 | |
| 345 | // Specify GOMODCACHE explicitly. The default cache path is GOPATH[0]/pkg/mod, |
| 346 | // but the path varies when GOPATH is specified at env, which results in cold cache. |
| 347 | if gmc, err := goModCachePath(); err == nil { |
| 348 | env = append([]string{"GOMODCACHE=" + gmc}, env...) |
| 349 | } else { |
| 350 | env = append([]string{}, env...) |
| 351 | } |
| 352 | cmd.Env = env |
| 353 | cmd.Dir = at |
| 354 | return runCmd(cmd) |
| 355 | } |
| 356 | |
| 357 | func goModTidyAt(at string, env []string) error { |
| 358 | cmd := exec.Command("go", "mod", "tidy") |
| 359 | if buildV { |
| 360 | cmd.Args = append(cmd.Args, "-v") |
| 361 | } |
| 362 | |
| 363 | // Specify GOMODCACHE explicitly. The default cache path is GOPATH[0]/pkg/mod, |
| 364 | // but the path varies when GOPATH is specified at env, which results in cold cache. |
| 365 | if gmc, err := goModCachePath(); err == nil { |
| 366 | env = append([]string{"GOMODCACHE=" + gmc}, env...) |
| 367 | } else { |
| 368 | env = append([]string{}, env...) |
| 369 | } |
| 370 | cmd.Env = env |
| 371 | cmd.Dir = at |
| 372 | return runCmd(cmd) |
| 373 | } |
| 374 | |
| 375 | // parseBuildTarget parses buildTarget into 1 or more platforms and architectures. |
| 376 | // Returns an error if buildTarget contains invalid input. |
| 377 | // Example valid target strings: |
| 378 | // |
| 379 | // android |
| 380 | // android/arm64,android/386,android/amd64 |
| 381 | // ios,iossimulator,maccatalyst |
| 382 | // macos/amd64 |
| 383 | func parseBuildTarget(buildTarget string) ([]targetInfo, error) { |
| 384 | if buildTarget == "" { |
| 385 | return nil, fmt.Errorf(`invalid target ""`) |
| 386 | } |
| 387 | |
| 388 | targets := []targetInfo{} |
| 389 | targetsAdded := make(map[targetInfo]bool) |
| 390 | |
| 391 | addTarget := func(platform, arch string) { |
| 392 | t := targetInfo{platform, arch} |
| 393 | if targetsAdded[t] { |
| 394 | return |
| 395 | } |
| 396 | targets = append(targets, t) |
| 397 | targetsAdded[t] = true |
| 398 | } |
| 399 | |
| 400 | addPlatform := func(platform string) { |
| 401 | for _, arch := range platformArchs(platform) { |
| 402 | addTarget(platform, arch) |
| 403 | } |
| 404 | } |
| 405 | |
| 406 | var isAndroid, isApple bool |
| 407 | for _, target := range strings.Split(buildTarget, ",") { |
| 408 | tuple := strings.SplitN(target, "/", 2) |
| 409 | platform := tuple[0] |
| 410 | hasArch := len(tuple) == 2 |
| 411 | |
| 412 | if isAndroidPlatform(platform) { |
| 413 | isAndroid = true |
| 414 | } else if isApplePlatform(platform) { |
| 415 | isApple = true |
| 416 | } else { |
| 417 | return nil, fmt.Errorf("unsupported platform: %q", platform) |
| 418 | } |
| 419 | if isAndroid && isApple { |
| 420 | return nil, fmt.Errorf(`cannot mix android and Apple platforms`) |
| 421 | } |
| 422 | |
| 423 | if hasArch { |
| 424 | arch := tuple[1] |
| 425 | if !isSupportedArch(platform, arch) { |
| 426 | return nil, fmt.Errorf(`unsupported platform/arch: %q`, target) |
| 427 | } |
| 428 | addTarget(platform, arch) |
| 429 | } else { |
| 430 | addPlatform(platform) |
| 431 | } |
| 432 | } |
| 433 | |
| 434 | // Special case to build iossimulator if -target=ios |
| 435 | if buildTarget == "ios" { |
| 436 | addPlatform("iossimulator") |
| 437 | } |
| 438 | |
| 439 | return targets, nil |
| 440 | } |
| 441 | |
| 442 | type targetInfo struct { |
| 443 | platform string |
| 444 | arch string |
| 445 | } |
| 446 | |
| 447 | func (t targetInfo) String() string { |
| 448 | return t.platform + "/" + t.arch |
| 449 | } |
| 450 | |
| 451 | func goModCachePath() (string, error) { |
| 452 | out, err := exec.Command("go", "env", "GOMODCACHE").Output() |
| 453 | if err != nil { |
| 454 | return "", err |
| 455 | } |
| 456 | return strings.TrimSpace(string(out)), nil |
| 457 | } |