├── .gitattributes ├── .github └── workflows │ └── test.yml ├── .gitignore ├── LICENSE ├── README.md ├── appveyor.yml ├── env_override.go ├── go.go ├── go.mod ├── go.sum ├── go_test.go ├── main.go ├── main_osarch.go ├── platform.go ├── platform_flag.go ├── platform_flag_test.go ├── platform_test.go └── toolchain.go /.gitattributes: -------------------------------------------------------------------------------- 1 | * text 2 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | 3 | on: 4 | push: {} 5 | 6 | env: 7 | GOPATH: /home/runner/work/go 8 | 9 | jobs: 10 | test-after-go-11: 11 | runs-on: ubuntu-latest 12 | strategy: 13 | matrix: 14 | go: [ 15 | "1.11.13", 16 | "1.12.17", 17 | "1.13.15", 18 | "1.14.15", 19 | "1.15.15", 20 | "1.16.15", 21 | "1.17.7", 22 | "1.18.3", 23 | ] 24 | fail-fast: true 25 | 26 | name: Go ${{ matrix.go }} test 27 | steps: 28 | - uses: actions/checkout@v3 29 | - name: Setup go 30 | uses: actions/setup-go@v3 31 | with: 32 | go-version: ${{ matrix.go }} 33 | - name: Build 34 | run: go build . 35 | - name: Test 36 | run: go test -v ./... 37 | test-before-go-11: 38 | runs-on: ubuntu-latest 39 | strategy: 40 | matrix: 41 | go: [ 42 | "1.6.4", 43 | "1.7.6", 44 | "1.8.7", 45 | "1.9.7", 46 | "1.10.8", 47 | ] 48 | fail-fast: true 49 | 50 | name: Go ${{ matrix.go }} test 51 | steps: 52 | - uses: actions/checkout@v3 53 | - name: Setup go 54 | uses: actions/setup-go@v3 55 | with: 56 | go-version: ${{ matrix.go }} 57 | - name: Setup GOPATH 58 | run: mkdir -p $GOPATH/src/github.com/$GITHUB_REPOSITORY 59 | - name: Copy 60 | run: cp -r ./ $GOPATH/src/github.com/$GITHUB_REPOSITORY 61 | - name: Get 62 | run: cd $GOPATH/src/github.com/$GITHUB_REPOSITORY && go get . 63 | - name: Build 64 | run: cd $GOPATH/src/github.com/$GITHUB_REPOSITORY && go build . 65 | - name: Test 66 | run: cd $GOPATH/src/github.com/$GITHUB_REPOSITORY && go test -v ./... 67 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | gox 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | 375 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Gox - Simple Go Cross Compilation 2 | 3 | Gox is a simple, no-frills tool for Go cross compilation that behaves a 4 | lot like standard `go build`. Gox will parallelize builds for multiple 5 | platforms. Gox will also build the cross-compilation toolchain for you. 6 | 7 | ## Installation 8 | 9 | To install Gox, please use `go get`. We tag versions so feel free to 10 | checkout that tag and compile. 11 | 12 | ``` 13 | $ go install github.com/mitchellh/gox@latest 14 | ... 15 | $ gox -h 16 | ... 17 | ``` 18 | 19 | ## Usage 20 | 21 | If you know how to use `go build`, then you know how to use Gox. For 22 | example, to build the current package, specify no parameters and just 23 | call `gox`. Gox will parallelize based on the number of CPUs you have 24 | by default and build for every platform by default: 25 | 26 | ``` 27 | $ gox 28 | Number of parallel builds: 4 29 | 30 | --> darwin/386: github.com/mitchellh/gox 31 | --> darwin/amd64: github.com/mitchellh/gox 32 | --> linux/386: github.com/mitchellh/gox 33 | --> linux/amd64: github.com/mitchellh/gox 34 | --> linux/arm: github.com/mitchellh/gox 35 | --> freebsd/386: github.com/mitchellh/gox 36 | --> freebsd/amd64: github.com/mitchellh/gox 37 | --> openbsd/386: github.com/mitchellh/gox 38 | --> openbsd/amd64: github.com/mitchellh/gox 39 | --> windows/386: github.com/mitchellh/gox 40 | --> windows/amd64: github.com/mitchellh/gox 41 | --> freebsd/arm: github.com/mitchellh/gox 42 | --> netbsd/386: github.com/mitchellh/gox 43 | --> netbsd/amd64: github.com/mitchellh/gox 44 | --> netbsd/arm: github.com/mitchellh/gox 45 | --> plan9/386: github.com/mitchellh/gox 46 | ``` 47 | 48 | Or, if you want to build a package and sub-packages: 49 | 50 | ``` 51 | $ gox ./... 52 | ... 53 | ``` 54 | 55 | Or, if you want to build multiple distinct packages: 56 | 57 | ``` 58 | $ gox github.com/mitchellh/gox github.com/hashicorp/serf 59 | ... 60 | ``` 61 | 62 | Or if you want to just build for linux: 63 | 64 | ``` 65 | $ gox -os="linux" 66 | ... 67 | ``` 68 | 69 | Or maybe you just want to build for 64-bit linux: 70 | 71 | ``` 72 | $ gox -osarch="linux/amd64" 73 | ... 74 | ``` 75 | 76 | And more! Just run `gox -h` for help and additional information. 77 | 78 | ## Versus Other Cross-Compile Tools 79 | 80 | A big thanks to these other options for existing. They each paved the 81 | way in many aspects to make Go cross-compilation approachable. 82 | 83 | * [Dave Cheney's golang-crosscompile](https://github.com/davecheney/golang-crosscompile) - 84 | Gox compiles for multiple platforms and can therefore easily run on 85 | any platform Go supports, whereas Dave's scripts require a shell. Gox 86 | will also parallelize builds. Dave's scripts build sequentially. Gox has 87 | much easier to use OS/Arch filtering built in. 88 | 89 | * [goxc](https://github.com/laher/goxc) - 90 | A very richly featured tool that can even do things such as build system 91 | packages, upload binaries, generate download webpages, etc. Gox is a 92 | super slim alternative that only cross-compiles binaries. Gox builds packages in parallel, whereas 93 | goxc doesn't. Gox doesn't enforce a specific output structure for built 94 | binaries. 95 | 96 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | 2 | version: build-{build}.{branch} 3 | 4 | clone_folder: C:\gopath\src\github.com\mitchellh\gox 5 | shallow_clone: true 6 | 7 | environment: 8 | GOPATH: C:\gopath 9 | 10 | platform: 11 | - x64 12 | 13 | test_script: 14 | - go get ./... 15 | - go test -v ./... 16 | 17 | build: off 18 | 19 | deploy: off 20 | -------------------------------------------------------------------------------- /env_override.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "strings" 7 | ) 8 | 9 | // envOverride overrides the given target based on if there is a 10 | // env var in the format of GOX_{OS}_{ARCH}_{KEY}. 11 | func envOverride(target *string, platform Platform, key string) { 12 | key = strings.ToUpper(fmt.Sprintf( 13 | "GOX_%s_%s_%s", platform.OS, platform.Arch, key)) 14 | if v := os.Getenv(key); v != "" { 15 | *target = v 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /go.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "io/ioutil" 7 | "log" 8 | "os" 9 | "os/exec" 10 | "path/filepath" 11 | "regexp" 12 | "runtime" 13 | "strings" 14 | "text/template" 15 | ) 16 | 17 | type OutputTemplateData struct { 18 | Dir string 19 | OS string 20 | Arch string 21 | } 22 | 23 | type CompileOpts struct { 24 | PackagePath string 25 | Platform Platform 26 | OutputTpl string 27 | Ldflags string 28 | Gcflags string 29 | Asmflags string 30 | Tags string 31 | ModMode string 32 | Cgo bool 33 | Rebuild bool 34 | GoCmd string 35 | Race bool 36 | } 37 | 38 | // GoCrossCompile 39 | func GoCrossCompile(opts *CompileOpts) error { 40 | env := append(os.Environ(), 41 | "GOOS="+opts.Platform.OS, 42 | "GOARCH="+opts.Platform.Arch) 43 | 44 | // If we're building for our own platform, then enable cgo always. We 45 | // respect the CGO_ENABLED flag if that is explicitly set on the platform. 46 | if !opts.Cgo && os.Getenv("CGO_ENABLED") != "0" { 47 | opts.Cgo = runtime.GOOS == opts.Platform.OS && 48 | runtime.GOARCH == opts.Platform.Arch 49 | } 50 | 51 | // If cgo is enabled then set that env var 52 | if opts.Cgo { 53 | env = append(env, "CGO_ENABLED=1") 54 | } else { 55 | env = append(env, "CGO_ENABLED=0") 56 | } 57 | 58 | var outputPath bytes.Buffer 59 | tpl, err := template.New("output").Parse(opts.OutputTpl) 60 | if err != nil { 61 | return err 62 | } 63 | tplData := OutputTemplateData{ 64 | Dir: filepath.Base(opts.PackagePath), 65 | OS: opts.Platform.OS, 66 | Arch: opts.Platform.Arch, 67 | } 68 | if err := tpl.Execute(&outputPath, &tplData); err != nil { 69 | return err 70 | } 71 | 72 | if opts.Platform.OS == "windows" { 73 | outputPath.WriteString(".exe") 74 | } 75 | 76 | // Determine the full path to the output so that we can change our 77 | // working directory when executing go build. 78 | outputPathReal := outputPath.String() 79 | outputPathReal, err = filepath.Abs(outputPathReal) 80 | if err != nil { 81 | return err 82 | } 83 | 84 | // Go prefixes the import directory with '_' when it is outside 85 | // the GOPATH.For this, we just drop it since we move to that 86 | // directory to build. 87 | chdir := "" 88 | if opts.PackagePath[0] == '_' { 89 | if runtime.GOOS == "windows" { 90 | // We have to replace weird paths like this: 91 | // 92 | // _/c_/Users 93 | // 94 | // With: 95 | // 96 | // c:\Users 97 | // 98 | re := regexp.MustCompile("^/([a-zA-Z])_/") 99 | chdir = re.ReplaceAllString(opts.PackagePath[1:], "$1:\\") 100 | chdir = strings.Replace(chdir, "/", "\\", -1) 101 | } else { 102 | chdir = opts.PackagePath[1:] 103 | } 104 | 105 | opts.PackagePath = "" 106 | } 107 | 108 | args := []string{"build"} 109 | if opts.Rebuild { 110 | args = append(args, "-a") 111 | } 112 | if opts.ModMode != "" { 113 | args = append(args, "-mod", opts.ModMode) 114 | } 115 | if opts.Race { 116 | args = append(args, "-race") 117 | } 118 | args = append(args, 119 | "-gcflags", opts.Gcflags, 120 | "-ldflags", opts.Ldflags, 121 | "-asmflags", opts.Asmflags, 122 | "-tags", opts.Tags, 123 | "-o", outputPathReal, 124 | opts.PackagePath) 125 | 126 | _, err = execGo(opts.GoCmd, env, chdir, args...) 127 | return err 128 | } 129 | 130 | // GoMainDirs returns the file paths to the packages that are "main" 131 | // packages, from the list of packages given. The list of packages can 132 | // include relative paths, the special "..." Go keyword, etc. 133 | func GoMainDirs(packages []string, GoCmd string) ([]string, error) { 134 | args := make([]string, 0, len(packages)+3) 135 | args = append(args, "list", "-f", "{{.Name}}|{{.ImportPath}}") 136 | args = append(args, packages...) 137 | 138 | output, err := execGo(GoCmd, nil, "", args...) 139 | if err != nil { 140 | return nil, err 141 | } 142 | 143 | results := make([]string, 0, len(output)) 144 | for _, line := range strings.Split(output, "\n") { 145 | if line == "" { 146 | continue 147 | } 148 | 149 | parts := strings.SplitN(line, "|", 2) 150 | if len(parts) != 2 { 151 | log.Printf("Bad line reading packages: %s", line) 152 | continue 153 | } 154 | 155 | if parts[0] == "main" { 156 | results = append(results, parts[1]) 157 | } 158 | } 159 | 160 | return results, nil 161 | } 162 | 163 | // GoRoot returns the GOROOT value for the compiled `go` binary. 164 | func GoRoot() (string, error) { 165 | output, err := execGo("go", nil, "", "env", "GOROOT") 166 | if err != nil { 167 | return "", err 168 | } 169 | 170 | return strings.TrimSpace(output), nil 171 | } 172 | 173 | // GoVersion reads the version of `go` that is on the PATH. This is done 174 | // instead of `runtime.Version()` because it is possible to run gox against 175 | // another Go version. 176 | func GoVersion() (string, error) { 177 | // NOTE: We use `go run` instead of `go version` because the output 178 | // of `go version` might change whereas the source is guaranteed to run 179 | // for some time thanks to Go's compatibility guarantee. 180 | 181 | td, err := ioutil.TempDir("", "gox") 182 | if err != nil { 183 | return "", err 184 | } 185 | defer os.RemoveAll(td) 186 | 187 | // Write the source code for the program that will generate the version 188 | sourcePath := filepath.Join(td, "version.go") 189 | if err := ioutil.WriteFile(sourcePath, []byte(versionSource), 0644); err != nil { 190 | return "", err 191 | } 192 | 193 | // Execute and read the version, which will be the only thing on stdout. 194 | return execGo("go", nil, "", "run", sourcePath) 195 | } 196 | 197 | // GoVersionParts parses the version numbers from the version itself 198 | // into major and minor: 1.5, 1.4, etc. 199 | func GoVersionParts() (result [2]int, err error) { 200 | version, err := GoVersion() 201 | if err != nil { 202 | return 203 | } 204 | 205 | _, err = fmt.Sscanf(version, "go%d.%d", &result[0], &result[1]) 206 | return 207 | } 208 | 209 | func execGo(GoCmd string, env []string, dir string, args ...string) (string, error) { 210 | var stderr, stdout bytes.Buffer 211 | cmd := exec.Command(GoCmd, args...) 212 | cmd.Stdout = &stdout 213 | cmd.Stderr = &stderr 214 | if env != nil { 215 | cmd.Env = env 216 | } 217 | if dir != "" { 218 | cmd.Dir = dir 219 | } 220 | if err := cmd.Run(); err != nil { 221 | err = fmt.Errorf("%s\nStderr: %s", err, stderr.String()) 222 | return "", err 223 | } 224 | 225 | return stdout.String(), nil 226 | } 227 | 228 | const versionSource = `package main 229 | 230 | import ( 231 | "fmt" 232 | "runtime" 233 | ) 234 | 235 | func main() { 236 | fmt.Print(runtime.Version()) 237 | }` 238 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/mitchellh/gox 2 | 3 | go 1.17 4 | 5 | require ( 6 | github.com/hashicorp/go-version v1.0.0 7 | github.com/mitchellh/iochan v1.0.0 8 | ) 9 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/hashicorp/go-version v1.0.0 h1:21MVWPKDphxa7ineQQTrCU5brh7OuVVAzGOCnnCPtE8= 2 | github.com/hashicorp/go-version v1.0.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= 3 | github.com/mitchellh/iochan v1.0.0 h1:C+X3KsSTLFVBr/tK1eYN/vs4rJcvsiLU338UhYPJWeY= 4 | github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY= 5 | -------------------------------------------------------------------------------- /go_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "strings" 5 | "testing" 6 | ) 7 | 8 | func TestGoVersion(t *testing.T) { 9 | v, err := GoVersion() 10 | if err != nil { 11 | t.Fatalf("err: %s", err) 12 | } 13 | 14 | acceptable := []string{ 15 | "devel", 16 | "go1.0", 17 | "go1.1", 18 | "go1.2", 19 | "go1.3", 20 | "go1.4", 21 | "go1.5", 22 | "go1.6", 23 | "go1.7", 24 | "go1.8", 25 | "go1.9", 26 | "go1.10", 27 | "go1.11", 28 | "go1.12", 29 | "go1.13", 30 | "go1.14", 31 | "go1.15", 32 | "go1.16", 33 | "go1.17", 34 | "go1.18", 35 | } 36 | found := false 37 | for _, expected := range acceptable { 38 | if strings.HasPrefix(v, expected) { 39 | found = true 40 | break 41 | } 42 | } 43 | 44 | if !found { 45 | t.Fatalf("bad: %#v", v) 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "os" 7 | "os/exec" 8 | "runtime" 9 | "strings" 10 | "sync" 11 | 12 | version "github.com/hashicorp/go-version" 13 | ) 14 | 15 | func main() { 16 | // Call realMain so that defers work properly, since os.Exit won't 17 | // call defers. 18 | os.Exit(realMain()) 19 | } 20 | 21 | func realMain() int { 22 | var buildToolchain bool 23 | var ldflags string 24 | var outputTpl string 25 | var parallel int 26 | var platformFlag PlatformFlag 27 | var tags string 28 | var verbose bool 29 | var flagGcflags, flagAsmflags string 30 | var flagCgo, flagRebuild, flagListOSArch, flagRaceFlag bool 31 | var flagGoCmd string 32 | var modMode string 33 | flags := flag.NewFlagSet("gox", flag.ExitOnError) 34 | flags.Usage = func() { printUsage() } 35 | flags.Var(platformFlag.ArchFlagValue(), "arch", "arch to build for or skip") 36 | flags.Var(platformFlag.OSArchFlagValue(), "osarch", "os/arch pairs to build for or skip") 37 | flags.Var(platformFlag.OSFlagValue(), "os", "os to build for or skip") 38 | flags.StringVar(&ldflags, "ldflags", "", "linker flags") 39 | flags.StringVar(&tags, "tags", "", "go build tags") 40 | flags.StringVar(&outputTpl, "output", "{{.Dir}}_{{.OS}}_{{.Arch}}", "output path") 41 | flags.IntVar(¶llel, "parallel", -1, "parallelization factor") 42 | flags.BoolVar(&buildToolchain, "build-toolchain", false, "build toolchain") 43 | flags.BoolVar(&verbose, "verbose", false, "verbose") 44 | flags.BoolVar(&flagCgo, "cgo", false, "") 45 | flags.BoolVar(&flagRebuild, "rebuild", false, "") 46 | flags.BoolVar(&flagListOSArch, "osarch-list", false, "") 47 | flags.BoolVar(&flagRaceFlag, "race", false, "") 48 | flags.StringVar(&flagGcflags, "gcflags", "", "") 49 | flags.StringVar(&flagAsmflags, "asmflags", "", "") 50 | flags.StringVar(&flagGoCmd, "gocmd", "go", "") 51 | flags.StringVar(&modMode, "mod", "", "") 52 | if err := flags.Parse(os.Args[1:]); err != nil { 53 | flags.Usage() 54 | return 1 55 | } 56 | 57 | // Determine what amount of parallelism we want Default to the current 58 | // number of CPUs-1 is <= 0 is specified. 59 | if parallel <= 0 { 60 | cpus := runtime.NumCPU() 61 | if cpus < 2 { 62 | parallel = 1 63 | } else { 64 | parallel = cpus - 1 65 | } 66 | 67 | // Joyent containers report 48 cores via runtime.NumCPU(), and a 68 | // default of 47 parallel builds causes a panic. Default to 3 on 69 | // Solaris-derived operating systems unless overridden with the 70 | // -parallel flag. 71 | if runtime.GOOS == "solaris" { 72 | parallel = 3 73 | } 74 | } 75 | 76 | if buildToolchain { 77 | return mainBuildToolchain(parallel, platformFlag, verbose) 78 | } 79 | 80 | if _, err := exec.LookPath(flagGoCmd); err != nil { 81 | fmt.Fprintf(os.Stderr, "%s executable must be on the PATH\n", 82 | flagGoCmd) 83 | return 1 84 | } 85 | 86 | versionStr, err := GoVersion() 87 | if err != nil { 88 | fmt.Fprintf(os.Stderr, "error reading Go version: %s", err) 89 | return 1 90 | } 91 | 92 | if flagListOSArch { 93 | return mainListOSArch(versionStr) 94 | } 95 | 96 | // Determine the packages that we want to compile. Default to the 97 | // current directory if none are specified. 98 | packages := flags.Args() 99 | if len(packages) == 0 { 100 | packages = []string{"."} 101 | } 102 | 103 | // Get the packages that are in the given paths 104 | mainDirs, err := GoMainDirs(packages, flagGoCmd) 105 | if err != nil { 106 | fmt.Fprintf(os.Stderr, "Error reading packages: %s", err) 107 | return 1 108 | } 109 | 110 | // Determine the platforms we're building for 111 | platforms := platformFlag.Platforms(SupportedPlatforms(versionStr)) 112 | if len(platforms) == 0 { 113 | fmt.Println("No valid platforms to build for. If you specified a value") 114 | fmt.Println("for the 'os', 'arch', or 'osarch' flags, make sure you're") 115 | fmt.Println("using a valid value.") 116 | return 1 117 | } 118 | 119 | // Assume -mod is supported when no version prefix is found 120 | if modMode != "" && strings.HasPrefix(versionStr, "go") { 121 | // go-version only cares about version numbers 122 | current, err := version.NewVersion(versionStr[2:]) 123 | if err != nil { 124 | fmt.Fprintf(os.Stderr, "Unable to parse current go version: %s\n%s", versionStr, err.Error()) 125 | return 1 126 | } 127 | 128 | constraint, err := version.NewConstraint(">= 1.11") 129 | if err != nil { 130 | panic(err) 131 | } 132 | 133 | if !constraint.Check(current) { 134 | fmt.Printf("Go compiler version %s does not support the -mod flag\n", versionStr) 135 | modMode = "" 136 | } 137 | } 138 | 139 | // Build in parallel! 140 | fmt.Printf("Number of parallel builds: %d\n\n", parallel) 141 | var errorLock sync.Mutex 142 | var wg sync.WaitGroup 143 | errors := make([]string, 0) 144 | semaphore := make(chan int, parallel) 145 | for _, platform := range platforms { 146 | for _, path := range mainDirs { 147 | // Start the goroutine that will do the actual build 148 | wg.Add(1) 149 | go func(path string, platform Platform) { 150 | defer wg.Done() 151 | semaphore <- 1 152 | fmt.Printf("--> %15s: %s\n", platform.String(), path) 153 | 154 | opts := &CompileOpts{ 155 | PackagePath: path, 156 | Platform: platform, 157 | OutputTpl: outputTpl, 158 | Ldflags: ldflags, 159 | Gcflags: flagGcflags, 160 | Asmflags: flagAsmflags, 161 | Tags: tags, 162 | ModMode: modMode, 163 | Cgo: flagCgo, 164 | Rebuild: flagRebuild, 165 | GoCmd: flagGoCmd, 166 | Race: flagRaceFlag, 167 | } 168 | 169 | // Determine if we have specific CFLAGS or LDFLAGS for this 170 | // GOOS/GOARCH combo and override the defaults if so. 171 | envOverride(&opts.Ldflags, platform, "LDFLAGS") 172 | envOverride(&opts.Gcflags, platform, "GCFLAGS") 173 | envOverride(&opts.Asmflags, platform, "ASMFLAGS") 174 | 175 | if err := GoCrossCompile(opts); err != nil { 176 | errorLock.Lock() 177 | defer errorLock.Unlock() 178 | errors = append(errors, 179 | fmt.Sprintf("%s error: %s", platform.String(), err)) 180 | } 181 | <-semaphore 182 | }(path, platform) 183 | } 184 | } 185 | wg.Wait() 186 | 187 | if len(errors) > 0 { 188 | fmt.Fprintf(os.Stderr, "\n%d errors occurred:\n", len(errors)) 189 | for _, err := range errors { 190 | fmt.Fprintf(os.Stderr, "--> %s\n", err) 191 | } 192 | return 1 193 | } 194 | 195 | return 0 196 | } 197 | 198 | func printUsage() { 199 | fmt.Fprintf(os.Stderr, helpText) 200 | } 201 | 202 | const helpText = `Usage: gox [options] [packages] 203 | 204 | Gox cross-compiles Go applications in parallel. 205 | 206 | If no specific operating systems or architectures are specified, Gox 207 | will build for all pairs supported by your version of Go. 208 | 209 | Options: 210 | 211 | -arch="" Space-separated list of architectures to build for 212 | -build-toolchain Build cross-compilation toolchain 213 | -cgo Sets CGO_ENABLED=1, requires proper C toolchain (advanced) 214 | -gcflags="" Additional '-gcflags' value to pass to go build 215 | -ldflags="" Additional '-ldflags' value to pass to go build 216 | -asmflags="" Additional '-asmflags' value to pass to go build 217 | -tags="" Additional '-tags' value to pass to go build 218 | -mod="" Additional '-mod' value to pass to go build 219 | -os="" Space-separated list of operating systems to build for 220 | -osarch="" Space-separated list of os/arch pairs to build for 221 | -osarch-list List supported os/arch pairs for your Go version 222 | -output="foo" Output path template. See below for more info 223 | -parallel=-1 Amount of parallelism, defaults to number of CPUs 224 | -race Build with the go race detector enabled, requires CGO 225 | -gocmd="go" Build command, defaults to Go 226 | -rebuild Force rebuilding of package that were up to date 227 | -verbose Verbose mode 228 | 229 | Output path template: 230 | 231 | The output path for the compiled binaries is specified with the 232 | "-output" flag. The value is a string that is a Go text template. 233 | The default value is "{{.Dir}}_{{.OS}}_{{.Arch}}". The variables and 234 | their values should be self-explanatory. 235 | 236 | Platforms (OS/Arch): 237 | 238 | The operating systems and architectures to cross-compile for may be 239 | specified with the "-arch" and "-os" flags. These are space separated lists 240 | of valid GOOS/GOARCH values to build for, respectively. You may prefix an 241 | OS or Arch with "!" to negate and not build for that platform. If the list 242 | is made up of only negations, then the negations will come from the default 243 | list. 244 | 245 | Additionally, the "-osarch" flag may be used to specify complete os/arch 246 | pairs that should be built or ignored. The syntax for this is what you would 247 | expect: "darwin/amd64" would be a valid osarch value. Multiple can be space 248 | separated. An os/arch pair can begin with "!" to not build for that platform. 249 | 250 | The "-osarch" flag has the highest precedent when determing whether to 251 | build for a platform. If it is included in the "-osarch" list, it will be 252 | built even if the specific os and arch is negated in "-os" and "-arch", 253 | respectively. 254 | 255 | Platform Overrides: 256 | 257 | The "-gcflags", "-ldflags" and "-asmflags" options can be overridden per-platform 258 | by using environment variables. Gox will look for environment variables 259 | in the following format and use those to override values if they exist: 260 | 261 | GOX_[OS]_[ARCH]_GCFLAGS 262 | GOX_[OS]_[ARCH]_LDFLAGS 263 | GOX_[OS]_[ARCH]_ASMFLAGS 264 | 265 | ` 266 | -------------------------------------------------------------------------------- /main_osarch.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | func mainListOSArch(version string) int { 8 | fmt.Printf( 9 | "Supported OS/Arch combinations for %s are shown below. The \"default\"\n"+ 10 | "boolean means that if you don't specify an OS/Arch, it will be\n"+ 11 | "included by default. If it isn't a default OS/Arch, you must explicitly\n"+ 12 | "specify that OS/Arch combo for Gox to use it.\n\n", 13 | version) 14 | for _, p := range SupportedPlatforms(version) { 15 | fmt.Printf("%s\t(default: %v)\n", p.String(), p.Default) 16 | } 17 | 18 | return 0 19 | } 20 | -------------------------------------------------------------------------------- /platform.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "strings" 7 | 8 | version "github.com/hashicorp/go-version" 9 | ) 10 | 11 | // Platform is a combination of OS/arch that can be built against. 12 | type Platform struct { 13 | OS string 14 | Arch string 15 | 16 | // Default, if true, will be included as a default build target 17 | // if no OS/arch is specified. We try to only set as a default popular 18 | // targets or targets that are generally useful. For example, Android 19 | // is not a default because it is quite rare that you're cross-compiling 20 | // something to Android AND something like Linux. 21 | Default bool 22 | } 23 | 24 | func (p *Platform) String() string { 25 | return fmt.Sprintf("%s/%s", p.OS, p.Arch) 26 | } 27 | 28 | // addDrop appends all of the "add" entries and drops the "drop" entries, ignoring 29 | // the "Default" parameter. 30 | func addDrop(base []Platform, add []Platform, drop []Platform) []Platform { 31 | newPlatforms := make([]Platform, len(base)+len(add)) 32 | copy(newPlatforms, base) 33 | copy(newPlatforms[len(base):], add) 34 | 35 | // slow, but we only do this during initialization at most once per version 36 | for _, platform := range drop { 37 | found := -1 38 | for i := range newPlatforms { 39 | if newPlatforms[i].Arch == platform.Arch && newPlatforms[i].OS == platform.OS { 40 | found = i 41 | break 42 | } 43 | } 44 | if found < 0 { 45 | panic(fmt.Sprintf("Expected to remove %+v but not found in list %+v", platform, newPlatforms)) 46 | } 47 | if found == len(newPlatforms)-1 { 48 | newPlatforms = newPlatforms[:found] 49 | } else if found == 0 { 50 | newPlatforms = newPlatforms[found:] 51 | } else { 52 | newPlatforms = append(newPlatforms[:found], newPlatforms[found+1:]...) 53 | } 54 | } 55 | return newPlatforms 56 | } 57 | 58 | var ( 59 | Platforms_1_0 = []Platform{ 60 | {"darwin", "386", true}, 61 | {"darwin", "amd64", true}, 62 | {"linux", "386", true}, 63 | {"linux", "amd64", true}, 64 | {"linux", "arm", true}, 65 | {"freebsd", "386", true}, 66 | {"freebsd", "amd64", true}, 67 | {"openbsd", "386", true}, 68 | {"openbsd", "amd64", true}, 69 | {"windows", "386", true}, 70 | {"windows", "amd64", true}, 71 | } 72 | 73 | Platforms_1_1 = addDrop(Platforms_1_0, []Platform{ 74 | {"freebsd", "arm", true}, 75 | {"netbsd", "386", true}, 76 | {"netbsd", "amd64", true}, 77 | {"netbsd", "arm", true}, 78 | {"plan9", "386", false}, 79 | }, nil) 80 | 81 | Platforms_1_3 = addDrop(Platforms_1_1, []Platform{ 82 | {"dragonfly", "386", false}, 83 | {"dragonfly", "amd64", false}, 84 | {"nacl", "amd64", false}, 85 | {"nacl", "amd64p32", false}, 86 | {"nacl", "arm", false}, 87 | {"solaris", "amd64", false}, 88 | }, nil) 89 | 90 | Platforms_1_4 = addDrop(Platforms_1_3, []Platform{ 91 | {"android", "arm", false}, 92 | {"plan9", "amd64", false}, 93 | }, nil) 94 | 95 | Platforms_1_5 = addDrop(Platforms_1_4, []Platform{ 96 | {"darwin", "arm", false}, 97 | {"darwin", "arm64", false}, 98 | {"linux", "arm64", false}, 99 | {"linux", "ppc64", false}, 100 | {"linux", "ppc64le", false}, 101 | }, nil) 102 | 103 | Platforms_1_6 = addDrop(Platforms_1_5, []Platform{ 104 | {"android", "386", false}, 105 | {"android", "amd64", false}, 106 | {"linux", "mips64", false}, 107 | {"linux", "mips64le", false}, 108 | {"nacl", "386", false}, 109 | {"openbsd", "arm", true}, 110 | }, nil) 111 | 112 | Platforms_1_7 = addDrop(Platforms_1_5, []Platform{ 113 | // While not fully supported s390x is generally useful 114 | {"linux", "s390x", true}, 115 | {"plan9", "arm", false}, 116 | // Add the 1.6 Platforms, but reflect full support for mips64 and mips64le 117 | {"android", "386", false}, 118 | {"android", "amd64", false}, 119 | {"linux", "mips64", true}, 120 | {"linux", "mips64le", true}, 121 | {"nacl", "386", false}, 122 | {"openbsd", "arm", true}, 123 | }, nil) 124 | 125 | Platforms_1_8 = addDrop(Platforms_1_7, []Platform{ 126 | {"linux", "mips", true}, 127 | {"linux", "mipsle", true}, 128 | }, nil) 129 | 130 | // no new platforms in 1.9 131 | Platforms_1_9 = Platforms_1_8 132 | 133 | // unannounced, but dropped support for android/amd64 134 | Platforms_1_10 = addDrop(Platforms_1_9, nil, []Platform{{"android", "amd64", false}}) 135 | 136 | Platforms_1_11 = addDrop(Platforms_1_10, []Platform{ 137 | {"js", "wasm", true}, 138 | }, nil) 139 | 140 | Platforms_1_12 = addDrop(Platforms_1_11, []Platform{ 141 | {"aix", "ppc64", false}, 142 | {"windows", "arm", true}, 143 | }, nil) 144 | 145 | Platforms_1_13 = addDrop(Platforms_1_12, []Platform{ 146 | {"illumos", "amd64", false}, 147 | {"netbsd", "arm64", true}, 148 | {"openbsd", "arm64", true}, 149 | }, nil) 150 | 151 | Platforms_1_14 = addDrop(Platforms_1_13, []Platform{ 152 | {"freebsd", "arm64", true}, 153 | {"linux", "riscv64", true}, 154 | }, []Platform{ 155 | // drop nacl 156 | {"nacl", "386", false}, 157 | {"nacl", "amd64", false}, 158 | {"nacl", "arm", false}, 159 | }) 160 | 161 | Platforms_1_15 = addDrop(Platforms_1_14, []Platform{ 162 | {"android", "arm64", false}, 163 | }, []Platform{ 164 | // drop i386 macos 165 | {"darwin", "386", false}, 166 | }) 167 | 168 | Platforms_1_16 = addDrop(Platforms_1_15, []Platform{ 169 | {"android", "amd64", false}, 170 | {"darwin", "arm64", true}, 171 | {"openbsd", "mips64", false}, 172 | }, nil) 173 | 174 | Platforms_1_17 = addDrop(Platforms_1_16, []Platform{ 175 | {"windows", "arm64", true}, 176 | }, nil) 177 | 178 | // no new platforms in 1.18 179 | Platforms_1_18 = Platforms_1_17 180 | 181 | PlatformsLatest = Platforms_1_18 182 | ) 183 | 184 | // SupportedPlatforms returns the full list of supported platforms for 185 | // the version of Go that is 186 | func SupportedPlatforms(v string) []Platform { 187 | // Use latest if we get an unexpected version string 188 | if !strings.HasPrefix(v, "go") { 189 | return PlatformsLatest 190 | } 191 | // go-version only cares about version numbers 192 | v = v[2:] 193 | 194 | current, err := version.NewVersion(v) 195 | if err != nil { 196 | log.Printf("Unable to parse current go version: %s\n%s", v, err.Error()) 197 | 198 | // Default to latest 199 | return PlatformsLatest 200 | } 201 | 202 | var platforms = []struct { 203 | constraint string 204 | plat []Platform 205 | }{ 206 | {"<= 1.0", Platforms_1_0}, 207 | {">= 1.1, < 1.3", Platforms_1_1}, 208 | {">= 1.3, < 1.4", Platforms_1_3}, 209 | {">= 1.4, < 1.5", Platforms_1_4}, 210 | {">= 1.5, < 1.6", Platforms_1_5}, 211 | {">= 1.6, < 1.7", Platforms_1_6}, 212 | {">= 1.7, < 1.8", Platforms_1_7}, 213 | {">= 1.8, < 1.9", Platforms_1_8}, 214 | {">= 1.9, < 1.10", Platforms_1_9}, 215 | {">= 1.10, < 1.11", Platforms_1_10}, 216 | {">= 1.11, < 1.12", Platforms_1_11}, 217 | {">= 1.12, < 1.13", Platforms_1_12}, 218 | {">= 1.13, < 1.14", Platforms_1_13}, 219 | {">= 1.14, < 1.15", Platforms_1_14}, 220 | {">= 1.15, < 1.16", Platforms_1_15}, 221 | {">= 1.16, < 1.17", Platforms_1_16}, 222 | {">= 1.17, < 1.18", Platforms_1_17}, 223 | {">= 1.18, < 1.19", Platforms_1_18}, 224 | } 225 | 226 | for _, p := range platforms { 227 | constraints, err := version.NewConstraint(p.constraint) 228 | if err != nil { 229 | panic(err) 230 | } 231 | if constraints.Check(current) { 232 | return p.plat 233 | } 234 | } 235 | 236 | // Assume latest 237 | return PlatformsLatest 238 | } 239 | -------------------------------------------------------------------------------- /platform_flag.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "strings" 7 | ) 8 | 9 | // PlatformFlag is a flag.Value (and flag.Getter) implementation that 10 | // is used to track the os/arch flags on the command-line. 11 | type PlatformFlag struct { 12 | OS []string 13 | Arch []string 14 | OSArch []Platform 15 | } 16 | 17 | // Platforms returns the list of platforms that were set by this flag. 18 | // The default set of platforms must be passed in. 19 | func (p *PlatformFlag) Platforms(supported []Platform) []Platform { 20 | // NOTE: Reading this method alone is a bit hard to understand. It 21 | // is much easier to understand this method if you pair this with the 22 | // table of test cases it has. 23 | 24 | // Build a list of OS and archs NOT to build 25 | ignoreArch := make(map[string]struct{}) 26 | includeArch := make(map[string]struct{}) 27 | ignoreOS := make(map[string]struct{}) 28 | includeOS := make(map[string]struct{}) 29 | ignoreOSArch := make(map[string]Platform) 30 | includeOSArch := make(map[string]Platform) 31 | for _, v := range p.Arch { 32 | if v[0] == '!' { 33 | ignoreArch[v[1:]] = struct{}{} 34 | } else { 35 | includeArch[v] = struct{}{} 36 | } 37 | } 38 | for _, v := range p.OS { 39 | if v[0] == '!' { 40 | ignoreOS[v[1:]] = struct{}{} 41 | } else { 42 | includeOS[v] = struct{}{} 43 | } 44 | } 45 | for _, v := range p.OSArch { 46 | if v.OS[0] == '!' { 47 | v = Platform{ 48 | OS: v.OS[1:], 49 | Arch: v.Arch, 50 | } 51 | 52 | ignoreOSArch[v.String()] = v 53 | } else { 54 | includeOSArch[v.String()] = v 55 | } 56 | } 57 | 58 | // We're building a list of new platforms, so build the list 59 | // based only on the configured OS/arch pairs. 60 | var prefilter []Platform = nil 61 | if len(includeOSArch) > 0 { 62 | prefilter = make([]Platform, 0, len(p.Arch)*len(p.OS)+len(includeOSArch)) 63 | for _, v := range includeOSArch { 64 | prefilter = append(prefilter, v) 65 | } 66 | } 67 | 68 | if len(includeOS) > 0 && len(includeArch) > 0 { 69 | // Build up the list of prefiltered by what is specified 70 | if prefilter == nil { 71 | prefilter = make([]Platform, 0, len(p.Arch)*len(p.OS)) 72 | } 73 | 74 | for _, os := range p.OS { 75 | if _, ok := includeOS[os]; !ok { 76 | continue 77 | } 78 | 79 | for _, arch := range p.Arch { 80 | if _, ok := includeArch[arch]; !ok { 81 | continue 82 | } 83 | 84 | prefilter = append(prefilter, Platform{ 85 | OS: os, 86 | Arch: arch, 87 | }) 88 | } 89 | } 90 | } else if len(includeOS) > 0 { 91 | // Build up the list of prefiltered by what is specified 92 | if prefilter == nil { 93 | prefilter = make([]Platform, 0, len(p.Arch)*len(p.OS)) 94 | } 95 | 96 | for _, os := range p.OS { 97 | for _, platform := range supported { 98 | if platform.OS == os { 99 | prefilter = append(prefilter, platform) 100 | } 101 | } 102 | } 103 | } 104 | 105 | if prefilter != nil { 106 | // Remove any that aren't supported 107 | result := make([]Platform, 0, len(prefilter)) 108 | for _, pending := range prefilter { 109 | found := false 110 | for _, platform := range supported { 111 | if pending.String() == platform.String() { 112 | found = true 113 | break 114 | } 115 | } 116 | 117 | if found { 118 | add := pending 119 | add.Default = false 120 | result = append(result, add) 121 | } 122 | } 123 | 124 | prefilter = result 125 | } 126 | 127 | if prefilter == nil { 128 | prefilter = make([]Platform, 0, len(supported)) 129 | for _, v := range supported { 130 | if v.Default { 131 | add := v 132 | add.Default = false 133 | prefilter = append(prefilter, add) 134 | } 135 | } 136 | } 137 | 138 | // Go through each default platform and filter out the bad ones 139 | result := make([]Platform, 0, len(prefilter)) 140 | for _, platform := range prefilter { 141 | if len(ignoreOSArch) > 0 { 142 | if _, ok := ignoreOSArch[platform.String()]; ok { 143 | continue 144 | } 145 | } 146 | 147 | // We only want to check the components (OS and Arch) if we didn't 148 | // specifically ask to include it via the osarch. 149 | checkComponents := true 150 | if len(includeOSArch) > 0 { 151 | if _, ok := includeOSArch[platform.String()]; ok { 152 | checkComponents = false 153 | } 154 | } 155 | 156 | if checkComponents { 157 | if len(ignoreArch) > 0 { 158 | if _, ok := ignoreArch[platform.Arch]; ok { 159 | continue 160 | } 161 | } 162 | if len(ignoreOS) > 0 { 163 | if _, ok := ignoreOS[platform.OS]; ok { 164 | continue 165 | } 166 | } 167 | if len(includeArch) > 0 { 168 | if _, ok := includeArch[platform.Arch]; !ok { 169 | continue 170 | } 171 | } 172 | if len(includeOS) > 0 { 173 | if _, ok := includeOS[platform.OS]; !ok { 174 | continue 175 | } 176 | } 177 | } 178 | 179 | result = append(result, platform) 180 | } 181 | 182 | return result 183 | } 184 | 185 | // ArchFlagValue returns a flag.Value that can be used with the flag 186 | // package to collect the arches for the flag. 187 | func (p *PlatformFlag) ArchFlagValue() flag.Value { 188 | return (*appendStringValue)(&p.Arch) 189 | } 190 | 191 | // OSFlagValue returns a flag.Value that can be used with the flag 192 | // package to collect the operating systems for the flag. 193 | func (p *PlatformFlag) OSFlagValue() flag.Value { 194 | return (*appendStringValue)(&p.OS) 195 | } 196 | 197 | // OSArchFlagValue returns a flag.Value that can be used with the flag 198 | // package to collect complete os and arch pairs for the flag. 199 | func (p *PlatformFlag) OSArchFlagValue() flag.Value { 200 | return (*appendPlatformValue)(&p.OSArch) 201 | } 202 | 203 | // appendPlatformValue is a flag.Value that appends a full platform (os/arch) 204 | // to a list where the values from space-separated lines. This is used to 205 | // satisfy the -osarch flag. 206 | type appendPlatformValue []Platform 207 | 208 | func (s *appendPlatformValue) String() string { 209 | return "" 210 | } 211 | 212 | func (s *appendPlatformValue) Set(value string) error { 213 | if value == "" { 214 | return nil 215 | } 216 | 217 | for _, v := range strings.Split(value, " ") { 218 | parts := strings.Split(v, "/") 219 | if len(parts) != 2 { 220 | return fmt.Errorf( 221 | "Invalid platform syntax: %s should be os/arch", v) 222 | } 223 | 224 | platform := Platform{ 225 | OS: strings.ToLower(parts[0]), 226 | Arch: strings.ToLower(parts[1]), 227 | } 228 | 229 | s.appendIfMissing(&platform) 230 | } 231 | 232 | return nil 233 | } 234 | 235 | func (s *appendPlatformValue) appendIfMissing(value *Platform) { 236 | for _, existing := range *s { 237 | if existing == *value { 238 | return 239 | } 240 | } 241 | 242 | *s = append(*s, *value) 243 | } 244 | 245 | // appendStringValue is a flag.Value that appends values to the list, 246 | // where the values come from space-separated lines. This is used to 247 | // satisfy the -os="windows linux" flag to become []string{"windows", "linux"} 248 | type appendStringValue []string 249 | 250 | func (s *appendStringValue) String() string { 251 | return strings.Join(*s, " ") 252 | } 253 | 254 | func (s *appendStringValue) Set(value string) error { 255 | for _, v := range strings.Split(value, " ") { 256 | if v != "" { 257 | s.appendIfMissing(strings.ToLower(v)) 258 | } 259 | } 260 | 261 | return nil 262 | } 263 | 264 | func (s *appendStringValue) appendIfMissing(value string) { 265 | for _, existing := range *s { 266 | if existing == value { 267 | return 268 | } 269 | } 270 | 271 | *s = append(*s, value) 272 | } 273 | -------------------------------------------------------------------------------- /platform_flag_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "reflect" 6 | "testing" 7 | ) 8 | 9 | func TestPlatformFlagPlatforms(t *testing.T) { 10 | cases := []struct { 11 | OS []string 12 | Arch []string 13 | OSArch []Platform 14 | Supported []Platform 15 | Result []Platform 16 | }{ 17 | // Building a new list of platforms 18 | { 19 | []string{"foo", "bar"}, 20 | []string{"baz"}, 21 | []Platform{}, 22 | []Platform{ 23 | {"foo", "baz", true}, 24 | {"bar", "baz", true}, 25 | {"boo", "bop", true}, 26 | }, 27 | []Platform{ 28 | {"foo", "baz", false}, 29 | {"bar", "baz", false}, 30 | }, 31 | }, 32 | 33 | // Skipping platforms 34 | { 35 | []string{"!foo"}, 36 | []string{}, 37 | []Platform{}, 38 | []Platform{ 39 | {"foo", "bar", true}, 40 | {"foo", "baz", true}, 41 | {"bar", "bar", true}, 42 | }, 43 | []Platform{ 44 | {"bar", "bar", false}, 45 | }, 46 | }, 47 | 48 | // Specifying only an OS 49 | { 50 | []string{"foo"}, 51 | []string{}, 52 | []Platform{}, 53 | []Platform{ 54 | {"foo", "bar", true}, 55 | {"foo", "baz", true}, 56 | {"bar", "bar", true}, 57 | }, 58 | []Platform{ 59 | {"foo", "bar", false}, 60 | {"foo", "baz", false}, 61 | }, 62 | }, 63 | 64 | // Building a new list, but with some skips 65 | { 66 | []string{"foo", "bar", "!foo"}, 67 | []string{"baz"}, 68 | []Platform{}, 69 | []Platform{ 70 | {"foo", "bar", true}, 71 | {"foo", "baz", true}, 72 | {"bar", "baz", true}, 73 | {"baz", "bar", true}, 74 | }, 75 | []Platform{ 76 | {"bar", "baz", false}, 77 | }, 78 | }, 79 | 80 | // Unsupported pairs 81 | { 82 | []string{"foo", "bar"}, 83 | []string{"baz"}, 84 | []Platform{}, 85 | []Platform{ 86 | {"foo", "baz", true}, 87 | {"bar", "what", true}, 88 | }, 89 | []Platform{ 90 | {"foo", "baz", false}, 91 | }, 92 | }, 93 | 94 | // OSArch basic 95 | { 96 | []string{}, 97 | []string{}, 98 | []Platform{ 99 | {"foo", "baz", true}, 100 | {"foo", "bar", true}, 101 | }, 102 | []Platform{ 103 | {"foo", "baz", true}, 104 | {"bar", "what", true}, 105 | }, 106 | []Platform{ 107 | {"foo", "baz", false}, 108 | }, 109 | }, 110 | 111 | // Negative OSArch 112 | { 113 | []string{}, 114 | []string{}, 115 | []Platform{ 116 | {"!foo", "baz", true}, 117 | }, 118 | []Platform{ 119 | {"foo", "baz", true}, 120 | {"bar", "what", true}, 121 | }, 122 | []Platform{ 123 | {"bar", "what", false}, 124 | }, 125 | }, 126 | 127 | // Mix it all 128 | { 129 | []string{"foo", "bar"}, 130 | []string{"bar"}, 131 | []Platform{ 132 | {"foo", "baz", true}, 133 | {"!bar", "bar", true}, 134 | }, 135 | []Platform{ 136 | {"foo", "bar", true}, 137 | {"foo", "baz", true}, 138 | {"bar", "bar", true}, 139 | }, 140 | []Platform{ 141 | {"foo", "baz", false}, 142 | {"foo", "bar", false}, 143 | }, 144 | }, 145 | 146 | // Ignores non-default 147 | { 148 | []string{}, 149 | []string{}, 150 | []Platform{}, 151 | []Platform{ 152 | {"foo", "bar", true}, 153 | {"foo", "baz", true}, 154 | {"bar", "bar", false}, 155 | }, 156 | []Platform{ 157 | {"foo", "bar", false}, 158 | {"foo", "baz", false}, 159 | }, 160 | }, 161 | 162 | // Adds non-default by OS 163 | { 164 | []string{"bar"}, 165 | []string{}, 166 | []Platform{}, 167 | []Platform{ 168 | {"foo", "bar", true}, 169 | {"foo", "baz", true}, 170 | {"bar", "bar", false}, 171 | }, 172 | []Platform{ 173 | {"bar", "bar", false}, 174 | }, 175 | }, 176 | 177 | // Adds non-default by both 178 | { 179 | []string{"bar"}, 180 | []string{"bar"}, 181 | []Platform{}, 182 | []Platform{ 183 | {"foo", "bar", true}, 184 | {"foo", "baz", true}, 185 | {"bar", "bar", false}, 186 | }, 187 | []Platform{ 188 | {"bar", "bar", false}, 189 | }, 190 | }, 191 | } 192 | 193 | for _, tc := range cases { 194 | f := PlatformFlag{ 195 | OS: tc.OS, 196 | Arch: tc.Arch, 197 | OSArch: tc.OSArch, 198 | } 199 | 200 | result := f.Platforms(tc.Supported) 201 | if !reflect.DeepEqual(result, tc.Result) { 202 | t.Errorf("input: %#v\nresult: %#v", f, result) 203 | } 204 | } 205 | } 206 | 207 | func TestPlatformFlagArchFlagValue(t *testing.T) { 208 | var f PlatformFlag 209 | val := f.ArchFlagValue() 210 | if err := val.Set("foo bar"); err != nil { 211 | t.Fatalf("err: %s", err) 212 | } 213 | 214 | expected := []string{"foo", "bar"} 215 | if !reflect.DeepEqual(f.Arch, expected) { 216 | t.Fatalf("bad: %#v", f.Arch) 217 | } 218 | } 219 | 220 | func TestPlatformFlagOSArchFlagValue(t *testing.T) { 221 | var f PlatformFlag 222 | val := f.OSArchFlagValue() 223 | if err := val.Set("foo/bar"); err != nil { 224 | t.Fatalf("err: %s", err) 225 | } 226 | 227 | expected := []Platform{{"foo", "bar", false}} 228 | if !reflect.DeepEqual(f.OSArch, expected) { 229 | t.Fatalf("bad: %#v", f.OSArch) 230 | } 231 | } 232 | 233 | func TestPlatformFlagOSFlagValue(t *testing.T) { 234 | var f PlatformFlag 235 | val := f.OSFlagValue() 236 | if err := val.Set("foo bar"); err != nil { 237 | t.Fatalf("err: %s", err) 238 | } 239 | 240 | expected := []string{"foo", "bar"} 241 | if !reflect.DeepEqual(f.OS, expected) { 242 | t.Fatalf("bad: %#v", f.OS) 243 | } 244 | } 245 | 246 | func TestAppendPlatformValue_impl(t *testing.T) { 247 | var _ flag.Value = new(appendPlatformValue) 248 | } 249 | 250 | func TestAppendPlatformValue(t *testing.T) { 251 | var value appendPlatformValue 252 | 253 | if err := value.Set(""); err != nil { 254 | t.Fatalf("err: %s", err) 255 | } 256 | 257 | if len(value) > 0 { 258 | t.Fatalf("bad: %#v", value) 259 | } 260 | 261 | if err := value.Set("windows/arm/bad"); err == nil { 262 | t.Fatal("should err") 263 | } 264 | 265 | if err := value.Set("windows"); err == nil { 266 | t.Fatal("should err") 267 | } 268 | 269 | if err := value.Set("windows/arm windows/386"); err != nil { 270 | t.Fatalf("err: %s", err) 271 | } 272 | 273 | expected := []Platform{ 274 | {"windows", "arm", false}, 275 | {"windows", "386", false}, 276 | } 277 | if !reflect.DeepEqual([]Platform(value), expected) { 278 | t.Fatalf("bad: %#v", value) 279 | } 280 | } 281 | 282 | func TestAppendStringValue_impl(t *testing.T) { 283 | var _ flag.Value = new(appendStringValue) 284 | } 285 | 286 | func TestAppendStringValue(t *testing.T) { 287 | var value appendStringValue 288 | 289 | if err := value.Set(""); err != nil { 290 | t.Fatalf("err: %s", err) 291 | } 292 | 293 | if len(value) > 0 { 294 | t.Fatalf("bad: %#v", value) 295 | } 296 | 297 | if err := value.Set("windows LINUX"); err != nil { 298 | t.Fatalf("err: %s", err) 299 | } 300 | 301 | expected := []string{"windows", "linux"} 302 | if !reflect.DeepEqual([]string(value), expected) { 303 | t.Fatalf("bad: %#v", value) 304 | } 305 | 306 | if err := value.Set("darwin"); err != nil { 307 | t.Fatalf("err: %s", err) 308 | } 309 | 310 | expected = []string{"windows", "linux", "darwin"} 311 | if !reflect.DeepEqual([]string(value), expected) { 312 | t.Fatalf("bad: %#v", value) 313 | } 314 | 315 | if err := value.Set("darwin"); err != nil { 316 | t.Fatalf("err: %s", err) 317 | } 318 | 319 | expected = []string{"windows", "linux", "darwin"} 320 | if !reflect.DeepEqual([]string(value), expected) { 321 | t.Fatalf("bad: %#v", value) 322 | } 323 | } 324 | -------------------------------------------------------------------------------- /platform_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestSupportedPlatforms(t *testing.T) { 9 | var ps []Platform 10 | 11 | ps = SupportedPlatforms("go1.0") 12 | if !reflect.DeepEqual(ps, Platforms_1_0) { 13 | t.Fatalf("bad: %#v", ps) 14 | } 15 | 16 | ps = SupportedPlatforms("go1.1") 17 | if !reflect.DeepEqual(ps, Platforms_1_1) { 18 | t.Fatalf("bad: %#v", ps) 19 | } 20 | 21 | ps = SupportedPlatforms("go1.2") 22 | if !reflect.DeepEqual(ps, Platforms_1_1) { 23 | t.Fatalf("bad: %#v", ps) 24 | } 25 | 26 | ps = SupportedPlatforms("go1.3") 27 | if !reflect.DeepEqual(ps, Platforms_1_3) { 28 | t.Fatalf("bad: %#v", ps) 29 | } 30 | 31 | ps = SupportedPlatforms("go1.4") 32 | if !reflect.DeepEqual(ps, Platforms_1_4) { 33 | t.Fatalf("bad: %#v", ps) 34 | } 35 | 36 | ps = SupportedPlatforms("go1.5") 37 | if !reflect.DeepEqual(ps, Platforms_1_5) { 38 | t.Fatalf("bad: %#v", ps) 39 | } 40 | 41 | ps = SupportedPlatforms("go1.6") 42 | if !reflect.DeepEqual(ps, Platforms_1_6) { 43 | t.Fatalf("bad: %#v", ps) 44 | } 45 | 46 | ps = SupportedPlatforms("go1.7") 47 | if !reflect.DeepEqual(ps, Platforms_1_7) { 48 | t.Fatalf("bad: %#v", ps) 49 | } 50 | 51 | ps = SupportedPlatforms("go1.8") 52 | if !reflect.DeepEqual(ps, Platforms_1_8) { 53 | t.Fatalf("bad: %#v", ps) 54 | } 55 | 56 | ps = SupportedPlatforms("go1.9") 57 | if !reflect.DeepEqual(ps, Platforms_1_9) { 58 | t.Fatalf("bad: %#v", ps) 59 | } 60 | 61 | ps = SupportedPlatforms("go1.10") 62 | if !reflect.DeepEqual(ps, Platforms_1_10) { 63 | t.Fatalf("bad: %#v", ps) 64 | } 65 | 66 | ps = SupportedPlatforms("go1.10") 67 | if !reflect.DeepEqual(ps, Platforms_1_10) { 68 | t.Fatalf("bad: %#v", ps) 69 | } 70 | 71 | ps = SupportedPlatforms("go1.11") 72 | if !reflect.DeepEqual(ps, Platforms_1_11) { 73 | t.Fatalf("bad: %#v", ps) 74 | } 75 | 76 | ps = SupportedPlatforms("go1.12") 77 | if !reflect.DeepEqual(ps, Platforms_1_12) { 78 | t.Fatalf("bad: %#v", ps) 79 | } 80 | 81 | ps = SupportedPlatforms("go1.13") 82 | if !reflect.DeepEqual(ps, Platforms_1_13) { 83 | t.Fatalf("bad: %#v", ps) 84 | } 85 | 86 | ps = SupportedPlatforms("go1.14") 87 | if !reflect.DeepEqual(ps, Platforms_1_14) { 88 | t.Fatalf("bad: %#v", ps) 89 | } 90 | 91 | ps = SupportedPlatforms("go1.15") 92 | if !reflect.DeepEqual(ps, Platforms_1_15) { 93 | t.Fatalf("bad: %#v", ps) 94 | } 95 | 96 | ps = SupportedPlatforms("go1.16") 97 | if !reflect.DeepEqual(ps, Platforms_1_16) { 98 | t.Fatalf("bad: %#v", ps) 99 | } 100 | 101 | ps = SupportedPlatforms("go1.17") 102 | if !reflect.DeepEqual(ps, Platforms_1_17) { 103 | t.Fatalf("bad: %#v", ps) 104 | } 105 | 106 | ps = SupportedPlatforms("go1.18") 107 | if !reflect.DeepEqual(ps, Platforms_1_18) { 108 | t.Fatalf("bad: %#v", ps) 109 | } 110 | 111 | ps = SupportedPlatforms("go1.10") 112 | if !reflect.DeepEqual(ps, Platforms_1_10) { 113 | t.Fatalf("bad: %#v", ps) 114 | } 115 | // Unknown 116 | ps = SupportedPlatforms("foo") 117 | if !reflect.DeepEqual(ps, PlatformsLatest) { 118 | t.Fatalf("bad: %#v", ps) 119 | } 120 | } 121 | 122 | func TestMIPS(t *testing.T) { 123 | g16 := SupportedPlatforms("go1.6") 124 | found := false 125 | for _, p := range g16 { 126 | if p.OS == "linux" && p.Arch == "mips64" && !p.Default { 127 | found = true 128 | } 129 | if p.OS == "linux" && p.Arch == "mips64" && p.Default { 130 | t.Fatalf("mips64 should not be default for 1.6, but got %+v, %+v", p, g16) 131 | } 132 | } 133 | if !found { 134 | t.Fatal("Expected to find linux/mips64/false in go1.6 supported platforms") 135 | } 136 | found = false 137 | 138 | g17 := SupportedPlatforms("go1.7") 139 | for _, p := range g17 { 140 | if p.OS == "linux" && p.Arch == "mips64" && p.Default { 141 | found = true 142 | } 143 | if p.OS == "linux" && p.Arch == "mips64" && !p.Default { 144 | t.Fatal("mips64 should be default for 1.7") 145 | } 146 | } 147 | if !found { 148 | t.Fatal("Expected to find linux/mips64/true in go1.7 supported platforms") 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /toolchain.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "io" 7 | "os" 8 | "os/exec" 9 | "path/filepath" 10 | "runtime" 11 | "sync" 12 | 13 | "github.com/mitchellh/iochan" 14 | ) 15 | 16 | // The "main" method for when the toolchain build is requested. 17 | func mainBuildToolchain(parallel int, platformFlag PlatformFlag, verbose bool) int { 18 | if _, err := exec.LookPath("go"); err != nil { 19 | fmt.Fprintf(os.Stderr, "You must have Go already built for your native platform\n") 20 | fmt.Fprintf(os.Stderr, "and the `go` binary on the PATH to build toolchains.\n") 21 | return 1 22 | } 23 | 24 | // If we're version 1.5 or greater, then we don't need to do this anymore! 25 | versionParts, err := GoVersionParts() 26 | if err != nil { 27 | fmt.Fprintf(os.Stderr, "error reading Go version: %s", err) 28 | return 1 29 | } 30 | if versionParts[0] >= 1 && versionParts[1] >= 5 { 31 | fmt.Fprintf( 32 | os.Stderr, 33 | "-build-toolchain is no longer required for Go 1.5 or later.\n"+ 34 | "You can start using Gox immediately!\n") 35 | return 1 36 | } 37 | 38 | version, err := GoVersion() 39 | if err != nil { 40 | fmt.Fprintf(os.Stderr, "error reading Go version: %s", err) 41 | return 1 42 | } 43 | 44 | root, err := GoRoot() 45 | if err != nil { 46 | fmt.Fprintf(os.Stderr, "error finding GOROOT: %s\n", err) 47 | return 1 48 | } 49 | 50 | if verbose { 51 | fmt.Println("Verbose mode enabled. Output from building each toolchain will be") 52 | fmt.Println("outputted to stdout as they are built.\n ") 53 | } 54 | 55 | // Determine the platforms we're building the toolchain for. 56 | platforms := platformFlag.Platforms(SupportedPlatforms(version)) 57 | 58 | // The toolchain build can't be parallelized. 59 | if parallel > 1 { 60 | fmt.Println("The toolchain build can't be parallelized because compiling a single") 61 | fmt.Println("Go source directory can only be done for one platform at a time. Therefore,") 62 | fmt.Println("the toolchain for each platform will be built one at a time.\n ") 63 | } 64 | parallel = 1 65 | 66 | var errorLock sync.Mutex 67 | var wg sync.WaitGroup 68 | errs := make([]error, 0) 69 | semaphore := make(chan int, parallel) 70 | for _, platform := range platforms { 71 | wg.Add(1) 72 | go func(platform Platform) { 73 | err := buildToolchain(&wg, semaphore, root, platform, verbose) 74 | if err != nil { 75 | errorLock.Lock() 76 | defer errorLock.Unlock() 77 | errs = append(errs, fmt.Errorf("%s: %s", platform.String(), err)) 78 | } 79 | }(platform) 80 | } 81 | wg.Wait() 82 | 83 | if len(errs) > 0 { 84 | fmt.Fprintf(os.Stderr, "\n%d errors occurred:\n", len(errs)) 85 | for _, err := range errs { 86 | fmt.Fprintf(os.Stderr, "%s\n", err) 87 | } 88 | return 1 89 | } 90 | 91 | return 0 92 | } 93 | 94 | func buildToolchain(wg *sync.WaitGroup, semaphore chan int, root string, platform Platform, verbose bool) error { 95 | defer wg.Done() 96 | semaphore <- 1 97 | defer func() { <-semaphore }() 98 | fmt.Printf("--> Toolchain: %s\n", platform.String()) 99 | 100 | scriptName := "make.bash" 101 | if runtime.GOOS == "windows" { 102 | scriptName = "make.bat" 103 | } 104 | 105 | var stderr bytes.Buffer 106 | var stdout bytes.Buffer 107 | scriptDir := filepath.Join(root, "src") 108 | scriptPath := filepath.Join(scriptDir, scriptName) 109 | cmd := exec.Command(scriptPath, "--no-clean") 110 | cmd.Dir = scriptDir 111 | cmd.Env = append(os.Environ(), 112 | "GOARCH="+platform.Arch, 113 | "GOOS="+platform.OS) 114 | cmd.Stderr = &stderr 115 | cmd.Stdout = &stdout 116 | 117 | if verbose { 118 | // In verbose mode, we output all stdout to the console. 119 | r, w := io.Pipe() 120 | cmd.Stdout = w 121 | cmd.Stderr = io.MultiWriter(cmd.Stderr, w) 122 | 123 | // Send all the output to stdout, and also make a done channel 124 | // so that this compilation isn't done until we receive all output 125 | doneCh := make(chan struct{}) 126 | go func() { 127 | defer close(doneCh) 128 | for line := range iochan.DelimReader(r, '\n') { 129 | fmt.Printf("%s: %s", platform.String(), line) 130 | } 131 | }() 132 | defer func() { 133 | w.Close() 134 | <-doneCh 135 | }() 136 | } 137 | 138 | if err := cmd.Start(); err != nil { 139 | return fmt.Errorf("Error building '%s': %s", platform.String(), err) 140 | } 141 | 142 | if err := cmd.Wait(); err != nil { 143 | return fmt.Errorf("Error building '%s'.\n\nStdout: %s\n\nStderr: %s\n", 144 | platform.String(), stdout.String(), stderr.String()) 145 | } 146 | 147 | return nil 148 | } 149 | --------------------------------------------------------------------------------