gox-0.3.0/000077500000000000000000000000001224427237400123165ustar00rootroot00000000000000gox-0.3.0/.gitignore000066400000000000000000000000041224427237400143000ustar00rootroot00000000000000gox gox-0.3.0/CHANGELOG.md000066400000000000000000000014631224427237400141330ustar00rootroot00000000000000## 0.3.0 (November 23, 2013) FEATURES: - Use `-osarch` to specify complete os/arch pairs to build for. ## 0.2.0 (November 19, 2013) FEATURES: - Can specify `-ldflags` for the go build in order to get things like variables injected into the compile. IMPROVEMENTS: - Building toolchain no longer requires the GOROOT env var. It is now automatically detected using `go env` - On Windows builds, ".exe" is appended to the output path. BUG FIXES: - When building toolchains with verbose mode, wait until output is fully read before moving on to next compilation. - Work with `-os` or `-arch` is an empty string. - Building toolchain doesn't output "plan9" for all platforms. - Don't parallelize toolchain building, because it doesn't work. ## 0.1.0 (November 17, 2013) Initial release gox-0.3.0/LICENSE000066400000000000000000000405261224427237400133320ustar00rootroot00000000000000Mozilla Public License Version 2.0 ================================== 1. Definitions -------------- 1.1. "Contributor" means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. 1.2. "Contributor Version" means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor's Contribution. 1.3. "Contribution" means Covered Software of a particular Contributor. 1.4. "Covered Software" means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. 1.5. "Incompatible With Secondary Licenses" means (a) that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or (b) that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. 1.6. "Executable Form" means any form of the work other than Source Code Form. 1.7. "Larger Work" means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. 1.8. "License" means this document. 1.9. "Licensable" means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. 1.10. "Modifications" means any of the following: (a) any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or (b) any new file in Source Code Form that contains any Covered Software. 1.11. "Patent Claims" of a Contributor means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. 1.12. "Secondary License" means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. 1.13. "Source Code Form" means the form of the work preferred for making modifications. 1.14. "You" (or "Your") means an individual or a legal entity exercising rights under this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, "control" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. 2. License Grants and Conditions -------------------------------- 2.1. Grants Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: (a) under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and (b) under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. 2.2. Effective Date The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. 2.3. Limitations on Grant Scope The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: (a) for any code that a Contributor has removed from Covered Software; or (b) for infringements caused by: (i) Your and any other third party's modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or (c) under Patent Claims infringed by Covered Software in the absence of its Contributions. This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). 2.4. Subsequent Licenses No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). 2.5. Representation Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. 2.6. Fair Use This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. 2.7. Conditions Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. 3. Responsibilities ------------------- 3.1. Distribution of Source Form All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients' rights in the Source Code Form. 3.2. Distribution of Executable Form If You distribute Covered Software in Executable Form then: (a) such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and (b) You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients' rights in the Source Code Form under this License. 3.3. Distribution of a Larger Work You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). 3.4. Notices You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. 3.5. Application of Additional Terms You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. 4. Inability to Comply Due to Statute or Regulation --------------------------------------------------- If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. 5. Termination -------------- 5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. 5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. ************************************************************************ * * * 6. Disclaimer of Warranty * * ------------------------- * * * * Covered Software is provided under this License on an "as is" * * basis, without warranty of any kind, either expressed, implied, or * * statutory, including, without limitation, warranties that the * * Covered Software is free of defects, merchantable, fit for a * * particular purpose or non-infringing. The entire risk as to the * * quality and performance of the Covered Software is with You. * * Should any Covered Software prove defective in any respect, You * * (not any Contributor) assume the cost of any necessary servicing, * * repair, or correction. This disclaimer of warranty constitutes an * * essential part of this License. No use of any Covered Software is * * authorized under this License except under this disclaimer. * * * ************************************************************************ ************************************************************************ * * * 7. Limitation of Liability * * -------------------------- * * * * Under no circumstances and under no legal theory, whether tort * * (including negligence), contract, or otherwise, shall any * * Contributor, or anyone who distributes Covered Software as * * permitted above, be liable to You for any direct, indirect, * * special, incidental, or consequential damages of any character * * including, without limitation, damages for lost profits, loss of * * goodwill, work stoppage, computer failure or malfunction, or any * * and all other commercial damages or losses, even if such party * * shall have been informed of the possibility of such damages. This * * limitation of liability shall not apply to liability for death or * * personal injury resulting from such party's negligence to the * * extent applicable law prohibits such limitation. Some * * jurisdictions do not allow the exclusion or limitation of * * incidental or consequential damages, so this exclusion and * * limitation may not apply to You. * * * ************************************************************************ 8. Litigation ------------- Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party's ability to bring cross-claims or counter-claims. 9. Miscellaneous ---------------- This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. 10. Versions of the License --------------------------- 10.1. New Versions Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. 10.2. Effect of New Versions You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. 10.3. Modified Versions If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. Exhibit A - Source Code Form License Notice ------------------------------------------- This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. You may add additional accurate notices of copyright ownership. Exhibit B - "Incompatible With Secondary Licenses" Notice --------------------------------------------------------- This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. gox-0.3.0/README.md000066400000000000000000000060011224427237400135720ustar00rootroot00000000000000# Gox - Simple Go Cross Compilation Gox is a simple, no-frills tool for Go cross compilation that behaves a lot like standard `go build`. Gox will parallelize builds for multiple platforms. Gox will also build the cross-compilation toolchain for you. ## Installation To install Gox, please use `go get`. We tag versions so feel free to checkout that tag and compile. ``` $ go get github.com/mitchellh/gox ... $ gox -h ... ``` ## Usage Before you use Gox, you must build the cross-compilation toolchain. Gox can do this for you and will parallelize this process. Still, it can take some time. This only has to be done once (or whenever you update Go): ``` $ gox -build-toolchain ... ``` Once that is done, you're ready to cross compile! If you know how to use `go build`, then you know how to use Gox. For example, to build the current package, specify no parameters and just call `gox`. Gox will parallelize based on the number of CPUs you have by default and build for every platform by default: ``` $ gox Number of parallel builds: 4 --> darwin/386: github.com/mitchellh/gox --> darwin/amd64: github.com/mitchellh/gox --> linux/386: github.com/mitchellh/gox --> linux/amd64: github.com/mitchellh/gox --> linux/arm: github.com/mitchellh/gox --> freebsd/386: github.com/mitchellh/gox --> freebsd/amd64: github.com/mitchellh/gox --> openbsd/386: github.com/mitchellh/gox --> openbsd/amd64: github.com/mitchellh/gox --> windows/386: github.com/mitchellh/gox --> windows/amd64: github.com/mitchellh/gox --> freebsd/arm: github.com/mitchellh/gox --> netbsd/386: github.com/mitchellh/gox --> netbsd/amd64: github.com/mitchellh/gox --> netbsd/arm: github.com/mitchellh/gox --> plan9/386: github.com/mitchellh/gox ``` Or, if you want to build a package and sub-packages: ``` $ gox ./... ... ``` Or, if you want to build multiple distinct packages: ``` $ gox github.com/mitchellh/gox github.com/hashicorp/serf ... ``` Or if you want to just build for linux: ``` $ gox -os="linux" ... ``` Or maybe you just want to build for 64-bit linux: ``` $ gox -osarch="linux/amd64" ... ``` And more! Just run `gox -h` for help and additional information. ## Versus Other Cross-Compile Tools A big thanks to these other options for existing. They each paved the way in many aspects to make Go cross-compilation approachable. * [Dave Cheney's golang-crosscompile](https://github.com/davecheney/golang-crosscompile) - Gox compiles for multiple platforms and can therefore easily run on any platform Go supports. Dave's scripts require a shell. * [goxc](https://github.com/laher/goxc) - A very richly featured tool that can even do things such as build system packages, upload binaries, generate download webpages, etc. Gox is a super slim alternative that only cross-compiles binaries. goxc assumes that you're cross-compiling using the same version of Go that built goxc, whereas Gox can be used anywhere a `go` binary is available. So you can build Gox with Go 1.2 and build with Go 1.0. gox-0.3.0/go.go000066400000000000000000000062461224427237400132620ustar00rootroot00000000000000package main import ( "bytes" "fmt" "io/ioutil" "log" "os" "os/exec" "path/filepath" "strings" "text/template" ) type OutputTemplateData struct { Dir string OS string Arch string } // GoCrossCompile func GoCrossCompile(dir string, platform Platform, outputTpl string, ldflags string) error { env := append(os.Environ(), "GOOS="+platform.OS, "GOARCH="+platform.Arch) var outputPath bytes.Buffer tpl, err := template.New("output").Parse(outputTpl) if err != nil { return err } tplData := OutputTemplateData{ Dir: filepath.Base(dir), OS: platform.OS, Arch: platform.Arch, } if err := tpl.Execute(&outputPath, &tplData); err != nil { return nil } if platform.OS == "windows" { outputPath.WriteString(".exe") } _, err = execGo(env, "build", "-ldflags", ldflags, "-o", outputPath.String(), dir) return err } // GoMainDirs returns the file paths to the packages that are "main" // packages, from the list of packages given. The list of packages can // include relative paths, the special "..." Go keyword, etc. func GoMainDirs(packages []string) ([]string, error) { args := make([]string, 0, len(packages)+3) args = append(args, "list", "-f", "{{.Name}}|{{.ImportPath}}") args = append(args, packages...) output, err := execGo(nil, args...) if err != nil { return nil, err } results := make([]string, 0, len(output)) for _, line := range strings.Split(output, "\n") { if line == "" { continue } parts := strings.SplitN(line, "|", 2) if len(parts) != 2 { log.Printf("Bad line reading packages: %s", line) continue } if parts[0] == "main" { results = append(results, parts[1]) } } return results, nil } // GoRoot returns the GOROOT value for the compiled `go` binary. func GoRoot() (string, error) { output, err := execGo(nil, "env", "GOROOT") if err != nil { return "", err } return strings.TrimSpace(output), nil } // GoVersion reads the version of `go` that is on the PATH. This is done // instead of `runtime.Version()` because it is possible to run gox against // another Go version. func GoVersion() (string, error) { // NOTE: We use `go run` instead of `go version` because the output // of `go version` might change whereas the source is guaranteed to run // for some time thanks to Go's compatibility guarantee. td, err := ioutil.TempDir("", "gox") if err != nil { return "", err } defer os.RemoveAll(td) // Write the source code for the program that will generate the version sourcePath := filepath.Join(td, "version.go") if err := ioutil.WriteFile(sourcePath, []byte(versionSource), 0644); err != nil { return "", err } // Execute and read the version, which will be the only thing on stdout. return execGo(nil, "run", sourcePath) } func execGo(env []string, args ...string) (string, error) { var stderr, stdout bytes.Buffer cmd := exec.Command("go", args...) cmd.Stdout = &stdout cmd.Stderr = &stderr if env != nil { cmd.Env = env } if err := cmd.Run(); err != nil { err = fmt.Errorf("%s\nStderr: %s", err, stderr.String()) return "", err } return stdout.String(), nil } const versionSource = `package main import ( "fmt" "runtime" ) func main() { fmt.Print(runtime.Version()) }` gox-0.3.0/main.go000066400000000000000000000117751224427237400136040ustar00rootroot00000000000000package main import ( "flag" "fmt" "os" "os/exec" "runtime" "sync" ) func main() { // Call realMain so that defers work properly, since os.Exit won't // call defers. os.Exit(realMain()) } func realMain() int { var buildToolchain bool var ldflags string var outputTpl string var parallel int var platformFlag PlatformFlag var verbose bool flags := flag.NewFlagSet("gox", flag.ExitOnError) flags.Usage = func() { printUsage() } flags.Var(platformFlag.ArchFlagValue(), "arch", "arch to build for or skip") flags.Var(platformFlag.OSArchFlagValue(), "osarch", "os/arch pairs to build for or skip") flags.Var(platformFlag.OSFlagValue(), "os", "os to build for or skip") flags.StringVar(&ldflags, "ldflags", "", "linker flags") flags.StringVar(&outputTpl, "output", "{{.Dir}}_{{.OS}}_{{.Arch}}", "output path") flags.IntVar(¶llel, "parallel", -1, "parallelization factor") flags.BoolVar(&buildToolchain, "build-toolchain", false, "build toolchain") flags.BoolVar(&verbose, "verbose", false, "verbose") if err := flags.Parse(os.Args[1:]); err != nil { flags.Usage() return 1 } // Determine what amount of parallelism we want Default to the current // number of CPUs is <= 0 is specified. if parallel <= 0 { parallel = runtime.NumCPU() } if buildToolchain { return mainBuildToolchain(parallel, platformFlag, verbose) } if _, err := exec.LookPath("go"); err != nil { fmt.Fprintf(os.Stderr, "go executable must be on the PATH\n") return 1 } version, err := GoVersion() if err != nil { fmt.Fprintf(os.Stderr, "error reading Go version: %s", err) return 1 } // Determine the packages that we want to compile. Default to the // current directory if none are specified. packages := flags.Args() if len(packages) == 0 { packages = []string{"."} } // Get the packages that are in the given paths mainDirs, err := GoMainDirs(packages) if err != nil { fmt.Fprintf(os.Stderr, "Error reading packages: %s", err) return 1 } // Determine the platforms we're building for platforms := platformFlag.Platforms(SupportedPlatforms(version)) // Build in parallel! fmt.Printf("Number of parallel builds: %d\n\n", parallel) var errorLock sync.Mutex var wg sync.WaitGroup errors := make([]string, 0) semaphore := make(chan int, parallel) for _, platform := range platforms { for _, path := range mainDirs { // Start the goroutine that will do the actual build wg.Add(1) go func(path string, platform Platform) { defer wg.Done() semaphore <- 1 fmt.Printf("--> %15s: %s\n", platform.String(), path) if err := GoCrossCompile(path, platform, outputTpl, ldflags); err != nil { errorLock.Lock() defer errorLock.Unlock() errors = append(errors, fmt.Sprintf("%s error: %s", platform.String(), err)) } <-semaphore }(path, platform) } } wg.Wait() if len(errors) > 0 { fmt.Fprintf(os.Stderr, "\n%d errors occurred:\n", len(errors)) for _, err := range errors { fmt.Fprintf(os.Stderr, "--> %s\n", err) } return 1 } return 0 } func printUsage() { fmt.Fprintf(os.Stderr, helpText) } const helpText = `Usage: gox [options] [packages] Gox cross-compiles Go applications in parallel. If no specific operating systes or architectures are specified, Gox will build for all pairs supported by your version of Go. Options: -arch="" Space-separated list of architectures to build for -build-toolchain Build cross-compilation toolchain -ldflags="" Additional '-ldflags' value to pass to go build -os="" Space-separated list of operating systems to build for -osarch="" Space-separated list of os/arch pairs to build for -output="foo" Output path template. See below for more info -parallel=-1 Amount of parallelism, defaults to number of CPUs -verbose Verbose mode Output path template: The output path for the compiled binaries is specified with the "-output" flag. The value is a string that is a Go text template. The default value is "{{.Dir}}_{{.OS}}_{{.Arch}}". The variables and their values should be self-explanatory. Platforms (OS/Arch): The operating systems and architectures to cross-compile for may be specified with the "-arch" and "-os" flags. These are space separated lists of valid GOOS/GOARCH values to build for, respectively. You may prefix an OS or Arch with "!" to negate and not build for that platform. If the list is made up of only negations, then the negations will come from the default list. Additionally, the "-osarch" flag may be used to specify complete os/arch pairs that should be built or ignored. The syntax for this is what you would expect: "darwin/amd64" would be a valid osarch value. Multiple can be space separated. An os/arch pair can begin with "!" to not build for that platform. The "-osarch" flag has the highest precedent when determing whether to build for a platform. If it is included in the "-osarch" list, it will be built even if the specific os and arch is negated in "-os" and "-arch", respectively. ` gox-0.3.0/platform.go000066400000000000000000000021071224427237400144710ustar00rootroot00000000000000package main import ( "fmt" "strings" ) // Platform is a combination of OS/arch that can be built against. type Platform struct { OS string Arch string } func (p *Platform) String() string { return fmt.Sprintf("%s/%s", p.OS, p.Arch) } var ( OsList = []string{ "darwin", "linux", "freebsd", "netbsd", "openbsd", "plan9", "windows", } ArchList = []string{ "386", "amd64", "arm", } Platforms_1_0 = []Platform{ {"darwin", "386"}, {"darwin", "amd64"}, {"linux", "386"}, {"linux", "amd64"}, {"linux", "arm"}, {"freebsd", "386"}, {"freebsd", "amd64"}, {"openbsd", "386"}, {"openbsd", "amd64"}, {"windows", "386"}, {"windows", "amd64"}, } Platforms_1_1 = append(Platforms_1_0, []Platform{ {"freebsd", "arm"}, {"netbsd", "386"}, {"netbsd", "amd64"}, {"netbsd", "arm"}, {"plan9", "386"}, }...) ) // SupportedPlatforms returns the full list of supported platforms for // the version of Go that is func SupportedPlatforms(v string) []Platform { if strings.HasPrefix(v, "go1.0") { return Platforms_1_0 } return Platforms_1_1 } gox-0.3.0/platform_flag.go000066400000000000000000000133251224427237400154660ustar00rootroot00000000000000package main import ( "flag" "fmt" "strings" ) // PlatformFlag is a flag.Value (and flag.Getter) implementation that // is used to track the os/arch flags on the command-line. type PlatformFlag struct { OS []string Arch []string OSArch []Platform } // Platforms returns the list of platforms that were set by this flag. // The default set of platforms must be passed in. func (p *PlatformFlag) Platforms(supported []Platform) []Platform { // NOTE: Reading this method alone is a bit hard to understand. It // is much easier to understand this method if you pair this with the // table of test cases it has. // Build a list of OS and archs NOT to build ignoreArch := make(map[string]struct{}) includeArch := make(map[string]struct{}) ignoreOS := make(map[string]struct{}) includeOS := make(map[string]struct{}) ignoreOSArch := make(map[Platform]struct{}) includeOSArch := make(map[Platform]struct{}) for _, v := range p.Arch { if v[0] == '!' { ignoreArch[v[1:]] = struct{}{} } else { includeArch[v] = struct{}{} } } for _, v := range p.OS { if v[0] == '!' { ignoreOS[v[1:]] = struct{}{} } else { includeOS[v] = struct{}{} } } for _, v := range p.OSArch { if v.OS[0] == '!' { v = Platform{ OS: v.OS[1:], Arch: v.Arch, } ignoreOSArch[v] = struct{}{} } else { includeOSArch[v] = struct{}{} } } // We're building a list of new platforms, so build the list // based only on the configured OS/arch pairs. var prefilter []Platform = nil if len(includeOSArch) > 0 { prefilter = make([]Platform, 0, len(p.Arch)*len(p.OS)+len(includeOSArch)) for k, _ := range includeOSArch { prefilter = append(prefilter, k) } } if len(includeOS) > 0 && len(includeArch) > 0 { // Build up the list of prefiltered by what is specified if prefilter == nil { prefilter = make([]Platform, 0, len(p.Arch)*len(p.OS)) } for _, os := range p.OS { if _, ok := includeOS[os]; !ok { continue } for _, arch := range p.Arch { if _, ok := includeArch[arch]; !ok { continue } prefilter = append(prefilter, Platform{os, arch}) } } } if prefilter != nil { // Remove any that aren't supported result := make([]Platform, 0, len(prefilter)) for _, pending := range prefilter { found := false for _, platform := range supported { if pending == platform { found = true break } } if found { result = append(result, pending) } } prefilter = result } if prefilter == nil { prefilter = supported } // Go through each default platform and filter out the bad ones result := make([]Platform, 0, len(prefilter)) for _, platform := range prefilter { if len(ignoreOSArch) > 0 { if _, ok := ignoreOSArch[platform]; ok { continue } } // We only want to check the components (OS and Arch) if we didn't // specifically ask to include it via the osarch. checkComponents := true if len(includeOSArch) > 0 { if _, ok := includeOSArch[platform]; ok { checkComponents = false } } if checkComponents { if len(ignoreArch) > 0 { if _, ok := ignoreArch[platform.Arch]; ok { continue } } if len(ignoreOS) > 0 { if _, ok := ignoreOS[platform.OS]; ok { continue } } if len(includeArch) > 0 { if _, ok := includeArch[platform.Arch]; !ok { continue } } if len(includeOS) > 0 { if _, ok := includeOS[platform.OS]; !ok { continue } } } result = append(result, platform) } return result } // ArchFlagValue returns a flag.Value that can be used with the flag // package to collect the arches for the flag. func (p *PlatformFlag) ArchFlagValue() flag.Value { return (*appendStringValue)(&p.Arch) } // OSFlagValue returns a flag.Value that can be used with the flag // package to collect the operating systems for the flag. func (p *PlatformFlag) OSFlagValue() flag.Value { return (*appendStringValue)(&p.OS) } // OSArchFlagValue returns a flag.Value that can be used with the flag // package to collect complete os and arch pairs for the flag. func (p *PlatformFlag) OSArchFlagValue() flag.Value { return (*appendPlatformValue)(&p.OSArch) } // appendPlatformValue is a flag.Value that appends a full platform (os/arch) // to a list where the values from space-separated lines. This is used to // satisfy the -osarch flag. type appendPlatformValue []Platform func (s *appendPlatformValue) String() string { return "" } func (s *appendPlatformValue) Set(value string) error { if *s == nil { *s = make([]Platform, 0, 1) } if value == "" { return nil } for _, v := range strings.Split(value, " ") { parts := strings.Split(v, "/") if len(parts) != 2 { return fmt.Errorf( "Invalid platform syntax: %s should be os/arch", v) } platform := Platform{ OS: strings.ToLower(parts[0]), Arch: strings.ToLower(parts[1]), } s.appendIfMissing(&platform) } return nil } func (s *appendPlatformValue) appendIfMissing(value *Platform) { for _, existing := range *s { if existing == *value { return } } *s = append(*s, *value) } // appendStringValue is a flag.Value that appends values to the list, // where the values come from space-separated lines. This is used to // satisfy the -os="windows linux" flag to become []string{"windows", "linux"} type appendStringValue []string func (s *appendStringValue) String() string { return strings.Join(*s, " ") } func (s *appendStringValue) Set(value string) error { if *s == nil { *s = make([]string, 0, 1) } for _, v := range strings.Split(value, " ") { if v != "" { s.appendIfMissing(strings.ToLower(v)) } } return nil } func (s *appendStringValue) appendIfMissing(value string) { for _, existing := range *s { if existing == value { return } } *s = append(*s, value) } gox-0.3.0/platform_flag_test.go000066400000000000000000000114161224427237400165240ustar00rootroot00000000000000package main import ( "flag" "reflect" "testing" ) func TestPlatformFlagPlatforms(t *testing.T) { cases := []struct { OS []string Arch []string OSArch []Platform Supported []Platform Result []Platform }{ // Building a new list of platforms { []string{"foo", "bar"}, []string{"baz"}, []Platform{}, []Platform{ {"foo", "baz"}, {"bar", "baz"}, {"boo", "bop"}, }, []Platform{ {"foo", "baz"}, {"bar", "baz"}, }, }, // Skipping platforms { []string{"!foo"}, []string{}, []Platform{}, []Platform{ {"foo", "bar"}, {"foo", "baz"}, {"bar", "bar"}, }, []Platform{ {"bar", "bar"}, }, }, // Specifying only an OS { []string{"foo"}, []string{}, []Platform{}, []Platform{ {"foo", "bar"}, {"foo", "baz"}, {"bar", "bar"}, }, []Platform{ {"foo", "bar"}, {"foo", "baz"}, }, }, // Building a new list, but with some skips { []string{"foo", "bar", "!foo"}, []string{"baz"}, []Platform{}, []Platform{ {"foo", "bar"}, {"foo", "baz"}, {"bar", "baz"}, {"baz", "bar"}, }, []Platform{ {"bar", "baz"}, }, }, // Unsupported pairs { []string{"foo", "bar"}, []string{"baz"}, []Platform{}, []Platform{ {"foo", "baz"}, {"bar", "what"}, }, []Platform{ {"foo", "baz"}, }, }, // OSArch basic { []string{}, []string{}, []Platform{ {"foo", "baz"}, {"foo", "bar"}, }, []Platform{ {"foo", "baz"}, {"bar", "what"}, }, []Platform{ {"foo", "baz"}, }, }, // Negative OSArch { []string{}, []string{}, []Platform{ {"!foo", "baz"}, }, []Platform{ {"foo", "baz"}, {"bar", "what"}, }, []Platform{ {"bar", "what"}, }, }, // Mix it all { []string{"foo", "bar"}, []string{"bar"}, []Platform{ {"foo", "baz"}, {"!bar", "bar"}, }, []Platform{ {"foo", "bar"}, {"foo", "baz"}, {"bar", "bar"}, }, []Platform{ {"foo", "baz"}, {"foo", "bar"}, }, }, } for _, tc := range cases { f := PlatformFlag{ OS: tc.OS, Arch: tc.Arch, OSArch: tc.OSArch, } result := f.Platforms(tc.Supported) if !reflect.DeepEqual(result, tc.Result) { t.Errorf("input: %#v\nresult: %#v", f, result) } } } func TestPlatformFlagArchFlagValue(t *testing.T) { var f PlatformFlag val := f.ArchFlagValue() if err := val.Set("foo bar"); err != nil { t.Fatalf("err: %s", err) } expected := []string{"foo", "bar"} if !reflect.DeepEqual(f.Arch, expected) { t.Fatalf("bad: %#v", f.Arch) } } func TestPlatformFlagOSArchFlagValue(t *testing.T) { var f PlatformFlag val := f.OSArchFlagValue() if err := val.Set("foo/bar"); err != nil { t.Fatalf("err: %s", err) } expected := []Platform{{"foo", "bar"}} if !reflect.DeepEqual(f.OSArch, expected) { t.Fatalf("bad: %#v", f.OSArch) } } func TestPlatformFlagOSFlagValue(t *testing.T) { var f PlatformFlag val := f.OSFlagValue() if err := val.Set("foo bar"); err != nil { t.Fatalf("err: %s", err) } expected := []string{"foo", "bar"} if !reflect.DeepEqual(f.OS, expected) { t.Fatalf("bad: %#v", f.OS) } } func TestAppendPlatformValue_impl(t *testing.T) { var _ flag.Value = new(appendPlatformValue) } func TestAppendPlatformValue(t *testing.T) { var value appendPlatformValue if err := value.Set(""); err != nil { t.Fatalf("err: %s", err) } if len(value) > 0 { t.Fatalf("bad: %#v", value) } if err := value.Set("windows/arm/bad"); err == nil { t.Fatal("should err") } if err := value.Set("windows"); err == nil { t.Fatal("should err") } if err := value.Set("windows/arm windows/386"); err != nil { t.Fatalf("err: %s", err) } expected := []Platform{ {"windows", "arm"}, {"windows", "386"}, } if !reflect.DeepEqual([]Platform(value), expected) { t.Fatalf("bad: %#v", value) } } func TestAppendStringValue_impl(t *testing.T) { var _ flag.Value = new(appendStringValue) } func TestAppendStringValue(t *testing.T) { var value appendStringValue if err := value.Set(""); err != nil { t.Fatalf("err: %s", err) } if len(value) > 0 { t.Fatalf("bad: %#v", value) } if err := value.Set("windows LINUX"); err != nil { t.Fatalf("err: %s", err) } expected := []string{"windows", "linux"} if !reflect.DeepEqual([]string(value), expected) { t.Fatalf("bad: %#v", value) } if err := value.Set("darwin"); err != nil { t.Fatalf("err: %s", err) } expected = []string{"windows", "linux", "darwin"} if !reflect.DeepEqual([]string(value), expected) { t.Fatalf("bad: %#v", value) } if err := value.Set("darwin"); err != nil { t.Fatalf("err: %s", err) } expected = []string{"windows", "linux", "darwin"} if !reflect.DeepEqual([]string(value), expected) { t.Fatalf("bad: %#v", value) } } gox-0.3.0/platform_test.go000066400000000000000000000005131224427237400155270ustar00rootroot00000000000000package main import ( "reflect" "testing" ) func TestSupportedPlatforms(t *testing.T) { var ps []Platform ps = SupportedPlatforms("go1.0") if !reflect.DeepEqual(ps, Platforms_1_0) { t.Fatalf("bad: %#v", ps) } ps = SupportedPlatforms("go1.1") if !reflect.DeepEqual(ps, Platforms_1_1) { t.Fatalf("bad: %#v", ps) } } gox-0.3.0/toolchain.go000066400000000000000000000064741224427237400146400ustar00rootroot00000000000000package main import ( "bytes" "fmt" "github.com/mitchellh/iochan" "io" "os" "os/exec" "path/filepath" "runtime" "sync" ) // The "main" method for when the toolchain build is requested. func mainBuildToolchain(parallel int, platformFlag PlatformFlag, verbose bool) int { if _, err := exec.LookPath("go"); err != nil { fmt.Fprintf(os.Stderr, "You must have Go already built for your native platform\n") fmt.Fprintf(os.Stderr, "and the `go` binary on the PATH to build toolchains.\n") return 1 } version, err := GoVersion() if err != nil { fmt.Fprintf(os.Stderr, "error reading Go version: %s", err) return 1 } root, err := GoRoot() if err != nil { fmt.Fprintf(os.Stderr, "error finding GOROOT: %s\n", err) return 1 } if verbose { fmt.Println("Verbose mode enabled. Output from building each toolchain will be") fmt.Println("outputted to stdout as they are built.\n") } // Determine the platforms we're building the toolchain for. platforms := platformFlag.Platforms(SupportedPlatforms(version)) // The toolchain build can't be parallelized. if parallel > 1 { fmt.Println("The toolchain build can't be parallelized because compiling a single") fmt.Println("Go source directory can only be done for one platform at a time. Therefore,") fmt.Println("the toolchain for each platform will be built one at a time.\n") } parallel = 1 var errorLock sync.Mutex var wg sync.WaitGroup errs := make([]error, 0) semaphore := make(chan int, parallel) for _, platform := range platforms { wg.Add(1) go func(platform Platform) { err := buildToolchain(&wg, semaphore, root, platform, verbose) if err != nil { errorLock.Lock() defer errorLock.Unlock() errs = append(errs, fmt.Errorf("%s: %s", platform.String(), err)) } }(platform) } wg.Wait() if len(errs) > 0 { fmt.Fprintf(os.Stderr, "\n%d errors occurred:\n", len(errs)) for _, err := range errs { fmt.Fprintf(os.Stderr, "%s\n", err) } return 1 } return 0 } func buildToolchain(wg *sync.WaitGroup, semaphore chan int, root string, platform Platform, verbose bool) error { defer wg.Done() semaphore <- 1 defer func() { <-semaphore }() fmt.Printf("--> Toolchain: %s\n", platform.String()) scriptName := "make.bash" if runtime.GOOS == "windows" { scriptName = "make.bat" } var stderr bytes.Buffer scriptDir := filepath.Join(root, "src") scriptPath := filepath.Join(scriptDir, scriptName) cmd := exec.Command(scriptPath, "--no-clean") cmd.Dir = scriptDir cmd.Env = append(os.Environ(), "GOARCH="+platform.Arch, "GOOS="+platform.OS) cmd.Stderr = &stderr if verbose { // In verbose mode, we output all stdout to the console. r, w := io.Pipe() cmd.Stdout = w cmd.Stderr = io.MultiWriter(cmd.Stderr, w) // Send all the output to stdout, and also make a done channel // so that this compilation isn't done until we receive all output doneCh := make(chan struct{}) go func() { defer close(doneCh) for line := range iochan.DelimReader(r, '\n') { fmt.Printf("%s: %s", platform.String(), line) } }() defer func() { w.Close() <-doneCh }() } if err := cmd.Start(); err != nil { return fmt.Errorf("Error building '%s': %s", platform.String(), err) } if err := cmd.Wait(); err != nil { return fmt.Errorf("Error building '%s': %s", platform.String(), stderr.String()) } return nil }