├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── VERSION ├── git.go ├── git_test.go ├── integration-test ├── app-different-package │ ├── VERSION │ ├── main.go │ └── mypkg │ │ └── version.go ├── app-empty │ └── main.go ├── app-example │ └── main.go ├── app-extra-ldflags │ └── main.go ├── app-versioned │ ├── VERSION │ └── main.go └── test.bats ├── ldflags.go ├── ldflags_test.go ├── main.go ├── main_test.go ├── values.go ├── values_test.go └── version.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Binary 2 | govvv 3 | govvv_*amd64* 4 | 5 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 6 | *.o 7 | *.a 8 | *.so 9 | 10 | # Folders 11 | _obj 12 | _test 13 | 14 | # Architecture specific extensions/prefixes 15 | *.[568vq] 16 | [568vq].out 17 | 18 | *.cgo1.go 19 | *.cgo2.c 20 | _cgo_defun.c 21 | _cgo_gotypes.go 22 | _cgo_export.* 23 | 24 | _testmain.go 25 | 26 | *.exe 27 | *.test 28 | *.prof 29 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: required 2 | language: go 3 | go: go1.6 4 | install: 5 | - go get -u github.com/golang/lint/golint 6 | - go get -u github.com/mitchellh/gox 7 | - go get -u github.com/stretchr/testify/require 8 | - sudo add-apt-repository ppa:duggan/bats --yes 9 | - sudo apt-get update -qq 10 | - sudo apt-get install -qq bats 11 | before_script: 12 | - git config --global user.email "test@example.com" 13 | - git config --global user.name "Test User" 14 | script: 15 | - test -z "$(gofmt -s -l -w . | tee /dev/stderr)" 16 | - test -z "$(golint . | tee /dev/stderr)" 17 | - test -z "$(go vet -v ./... | tee /dev/stderr)" 18 | - go list ./... | grep -v '/integration-test/' | xargs go test -v -cover 19 | - go install 20 | - bats integration-test 21 | before_deploy: 22 | - gox -gocmd=govvv -os="linux windows darwin" -arch=amd64 . 23 | deploy: 24 | provider: releases 25 | api_key: 26 | secure: Q71IUY7Lsu4sSIF8pIwmRMmQU78cd8Z2iEJr1xmQkN1PRw98aYK9Zc39mgWmC0a4TumIKhgyevN1hKym+v94U1699Ia+lj+2tEQGGpm+lTzXglQHxu5GYD+6i/N5q7UN0UiM9+M18+6y2Q3qakohDLA+Pc4y8U9dvS97L0mVPdDTyd+SWubw/3NBqF6qag4YVNQrnp5M6iBnE0RdM47h5oX2civQESmQgyK5KJ8ZxNJ1dLehAxwVMO7DrwrcfEMURNT5Hta+v2cllGyHoK2Eb0HidvyhyVMCWfkSezOWL93rMjTmU/t/WmhH6fNcZyPxfiusWnYhVSYgMtguJWHGZ5vcdeNEqirIFHrjfYb2odmA8LEcj+5u4UMPO82rZNzMiM0SwntQ5Bx+uT7IHjvvu6yGaRNTBEq+9N+cPeuuiT1IGjr4WPjz1giCOUv9s9T9ZBWLJk4uDFv6+q0agcNzsRUEO3CI6oqMLPtB+hvTtBpJqFL07ev1CqhWCNoqO22VP0Fya928O5LKafrba0UsbPkJzvIDX29HEKeaOF7sloF8PDYa7nKoMI/7ZZYXfsZE2AlfWTvoFVXnDYVPTSxWyicLNNHQl5mjODYbV6UaExtbiOPn88bHsaBfZyFotXLZOuyT4KuORsYTtzOWjqy2ccdeQE9mUOMy0OLOY9v9zWc= 27 | file: 28 | - govvv_linux_amd64 29 | - govvv_darwin_amd64 30 | - govvv_windows_amd64.exe 31 | on: 32 | repo: ahmetb/govvv 33 | tags: true 34 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2016 Ahmet Alp Balkan 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # govvv 2 | 3 | The simple Go binary versioning tool that wraps the `go build` command. 4 | 5 | > :warning::warning::warning: **DEPRECATED:** Go now offers [build info](https://pkg.go.dev/runtime/debug#BuildInfo) natively. Please migrate to use that instead. I am no longer planning to maintain this project. 6 | 7 | ![](https://cl.ly/0U2m441v392Q/intro-1.gif) 8 | 9 | Stop worrying about `-ldflags` and **`go get github.com/ahmetb/govvv`** now. 10 | 11 | ## Build Variables 12 | 13 | | Variable | Description | Example | 14 | |----------|-------------|---------| 15 | | **`main.GitCommit`** | short commit hash of source tree | `0b5ed7a` | 16 | | **`main.GitBranch`** | current branch name the code is built off | `master` | 17 | | **`main.GitState`** | whether there are uncommitted changes | `clean` or `dirty` | 18 | | **`main.GitSummary`** | output of `git describe --tags --dirty --always` | `v1.0.0`,
`v1.0.1-5-g585c78f-dirty`,
`fbd157c` | 19 | | **`main.BuildDate`** | RFC3339 formatted UTC date | `2016-08-04T18:07:54Z` | 20 | | **`main.Version`** | contents of `./VERSION` file, if exists, or the value passed via the `-version` option | `2.0.0` | 21 | 22 | ## Using govvv is easy 23 | 24 | Just add the build variables you want to the `main` package and run: 25 | 26 | | old | :sparkles: new :sparkles: | 27 | | -------------|-----------------| 28 | | `go build` | `govvv build` | 29 | | `go install` | `govvv install` | 30 | 31 | ## Version your app with govvv 32 | 33 | Create a `VERSION` file in your build root directory and add a `Version` 34 | variable to your `main` package. 35 | 36 | ![](https://cl.ly/3Q1K1R2D3b2K/intro-2.gif) 37 | 38 | Do you have your own way of specifying `Version`? No problem: 39 | 40 | ## govvv lets you specify custom `-ldflags` 41 | 42 | Your existing `-ldflags` argument will still be preserved: 43 | 44 | govvv build -ldflags "-X main.BuildNumber=$buildnum" myapp 45 | 46 | and the `-ldflags` constructed by govvv will be appended to your flag. 47 | 48 | ## Don’t want to depend on `govvv`? It’s fine! 49 | 50 | You can just pass a `-print` argument and `govvv` will just print the 51 | `go build` command with `-ldflags` for you and will not execute the go tool: 52 | 53 | $ govvv build -print 54 | go build \ 55 | -ldflags \ 56 | "-X main.GitCommit=57b9870 -X main.GitBranch=dry-run -X main.GitState=dirty -X main.Version=0.1.0 -X main.BuildDate=2016-08-08T20:50:21Z" 57 | 58 | Still don’t want to wrap the `go` tool? Well, try `-flags` to retrieve the LDFLAGS govvv prepares: 59 | 60 | $ go build -ldflags="$(govvv -flags)" 61 | 62 | ## Want to use a different package? 63 | 64 | You can pass a `-pkg` argument with the full package name, and `govvv` will 65 | set the build variables in that package instead of `main`. For example: 66 | 67 | ``` 68 | # build with govvv 69 | $ govvv build -pkg github.com/myacct/myproj/mypkg 70 | 71 | # build with go 72 | $ go build -ldflags="$(govvv -flags -pkg $(go list ./mypkg))" 73 | ``` 74 | ## Want to use a different version? 75 | 76 | You can pass a `-version` argument with the desired version, and `govvv` will 77 | use the specified version instead of obtaining it from the `./VERSION` file. 78 | For example: 79 | 80 | ``` 81 | # build with govvv 82 | $ govvv build -version 1.2.3 83 | 84 | # build with go 85 | $ go build -ldflags="$(govvv -flags -version 1.2.3)" 86 | ``` 87 | 88 | ## Try govvv today 89 | 90 | $ go get github.com/ahmetb/govvv 91 | 92 | ------ 93 | 94 | govvv is distributed under [Apache 2.0 License](LICENSE). 95 | 96 | Copyright 2016 Ahmet Alp Balkan 97 | 98 | ------ 99 | 100 | [![Build Status](https://travis-ci.org/ahmetb/govvv.svg?branch=master)](https://travis-ci.org/ahmetb/govvv) 101 | -------------------------------------------------------------------------------- /VERSION: -------------------------------------------------------------------------------- 1 | 0.2.0 2 | -------------------------------------------------------------------------------- /git.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "os/exec" 7 | "strings" 8 | ) 9 | 10 | type git struct { 11 | dir string 12 | } 13 | 14 | func (g git) exec(args ...string) (string, error) { 15 | var errOut bytes.Buffer 16 | c := exec.Command("git", args...) 17 | c.Dir = g.dir 18 | c.Stderr = &errOut 19 | out, err := c.Output() 20 | outStr := strings.TrimSpace(string(out)) 21 | if err != nil { 22 | err = fmt.Errorf("git: error=%q stderr=%s", err, string(errOut.Bytes())) 23 | } 24 | return outStr, err 25 | } 26 | 27 | // Commit returns the short git commit hash. 28 | func (g git) Commit() (string, error) { 29 | return g.exec("rev-parse", "--short", "HEAD") 30 | } 31 | 32 | // State returns the repository state indicating whether 33 | // it is "clean" or "dirty". 34 | func (g git) State() (string, error) { 35 | out, err := g.exec("status", "--porcelain") 36 | if err != nil { 37 | return "", err 38 | } 39 | if len(out) > 0 { 40 | return "dirty", nil 41 | } 42 | return "clean", nil 43 | } 44 | 45 | // Branch returns the branch name. If it is detached, 46 | // or an error occurs, returns "HEAD". 47 | func (g git) Branch() string { 48 | out, err := g.exec("symbolic-ref", "-q", "--short", "HEAD") 49 | if err != nil { 50 | // might be failed due to another reason, but assume it's 51 | // exit code 1 from `git symbolic-ref` in detached state. 52 | return "HEAD" 53 | } 54 | return out 55 | } 56 | 57 | // Summary returns the output of "git describe --tags --dirty --always". 58 | func (g git) Summary() (string, error) { 59 | out, err := g.exec("describe", "--tags", "--dirty", "--always") 60 | if err != nil { 61 | return "", err 62 | } 63 | return out, err 64 | } 65 | -------------------------------------------------------------------------------- /git_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "io/ioutil" 5 | "os" 6 | "os/exec" 7 | "testing" 8 | 9 | "github.com/stretchr/testify/require" 10 | ) 11 | 12 | func TestGitExists(t *testing.T) { 13 | _, err := exec.LookPath("git") 14 | require.Nil(t, err, "error: %+v", err) 15 | } 16 | 17 | func TestCommit_failsOnEmptyRepo(t *testing.T) { 18 | repo := newRepo(t) 19 | defer os.RemoveAll(repo.dir) 20 | 21 | _, err := repo.Commit() 22 | require.NotNil(t, err) 23 | } 24 | 25 | func TestCommit(t *testing.T) { 26 | repo := newRepo(t) 27 | defer os.RemoveAll(repo.dir) 28 | 29 | mkCommit(t, repo, "commit 1") 30 | c1, err := repo.Commit() 31 | require.Nil(t, err) 32 | require.Regexp(t, "^[0-9a-f]{4,15}$", c1) 33 | 34 | mkCommit(t, repo, "commit 2") 35 | c2, err := repo.Commit() 36 | require.Nil(t, err) 37 | require.Regexp(t, "^[0-9a-f]{4,15}$", c2) 38 | 39 | // commit hash changed 40 | require.NotEqual(t, c1, c2) 41 | } 42 | 43 | func TestState(t *testing.T) { 44 | repo := newRepo(t) 45 | defer os.RemoveAll(repo.dir) 46 | 47 | s1, err := repo.State() 48 | require.Nil(t, err) 49 | require.EqualValues(t, "clean", s1) 50 | 51 | f, err := ioutil.TempFile(repo.dir, "") // contaminate 52 | require.Nil(t, err, "failed to create test file") 53 | f.Close() 54 | 55 | s2, err := repo.State() 56 | require.Nil(t, err) 57 | require.EqualValues(t, "dirty", s2) 58 | 59 | require.Nil(t, os.Remove(f.Name()), "failed to rm test file") 60 | 61 | s3, err := repo.State() 62 | require.Nil(t, err) 63 | require.EqualValues(t, "clean", s3) 64 | } 65 | 66 | func TestBranch(t *testing.T) { 67 | repo := newRepo(t) 68 | defer os.RemoveAll(repo.dir) 69 | 70 | // default branch "master" 71 | mkCommit(t, repo, "commit 1") 72 | mkCommit(t, repo, "commit 2") 73 | require.EqualValues(t, "master", repo.Branch()) 74 | 75 | // move into detached state: "HEAD" 76 | _, err := repo.exec("checkout", "HEAD~1") 77 | require.Nil(t, err) 78 | require.EqualValues(t, "HEAD", repo.Branch()) 79 | 80 | // checkout into another branch 81 | _, err = repo.exec("checkout", "-b", "foo") 82 | require.Nil(t, err) 83 | require.EqualValues(t, "foo", repo.Branch()) 84 | } 85 | 86 | func TestSummary(t *testing.T) { 87 | repo := newRepo(t) 88 | defer os.RemoveAll(repo.dir) 89 | 90 | // no tags yet, should be just short commit number 91 | mkCommit(t, repo, "commit 1") 92 | s, err := repo.Summary() 93 | require.Nil(t, err) 94 | require.Regexp(t, "^[0-9a-f]{4,15}$", s) 95 | 96 | // if commit is a tag, tag is returned 97 | _, err = repo.exec("tag", "v1.0.0") 98 | require.Nil(t, err) 99 | s, err = repo.Summary() 100 | require.Nil(t, err) 101 | require.EqualValues(t, "v1.0.0", s) 102 | 103 | // add 3 more commits, it should be in format v1.0.0-2-* 104 | mkCommit(t, repo, "commit 2") 105 | mkCommit(t, repo, "commit 3") 106 | s, err = repo.Summary() 107 | require.Nil(t, err) 108 | require.Regexp(t, "^v1.0.0-2-.*$", s) 109 | 110 | // add a dirty file 111 | f, err := ioutil.TempFile(repo.dir, "") // contaminate 112 | require.Nil(t, err, "failed to create test file") 113 | f.Close() 114 | _, err = repo.exec("add", f.Name()) 115 | require.Nil(t, err) 116 | s, err = repo.Summary() 117 | require.Nil(t, err) 118 | require.Regexp(t, ".*-dirty$", s) 119 | } 120 | 121 | // Test utilities 122 | 123 | func newRepo(t *testing.T) git { 124 | dir, err := ioutil.TempDir("", "gitrepo") 125 | require.Nil(t, err, "failed to create test dir") 126 | 127 | repo := git{dir} 128 | _, err = repo.exec("init", "-q", dir) 129 | require.Nil(t, err, "failed to initialize git repo") 130 | return repo 131 | } 132 | 133 | func mkCommit(t *testing.T, repo git, msg string) { 134 | _, err := repo.exec("commit", "--allow-empty", "--message", msg) 135 | require.Nil(t, err, "failed to commit: %+v", err) 136 | } 137 | -------------------------------------------------------------------------------- /integration-test/app-different-package/VERSION: -------------------------------------------------------------------------------- 1 | 2.0.1-app-different-package 2 | -------------------------------------------------------------------------------- /integration-test/app-different-package/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/ahmetb/govvv/integration-test/app-different-package/mypkg" 6 | ) 7 | 8 | func main() { 9 | fmt.Printf("Version=%s\n", mypkg.Version) 10 | fmt.Printf("BuildDate=%s\n", mypkg.BuildDate) 11 | fmt.Printf("GitCommit=%s\n", mypkg.GitCommit) 12 | fmt.Printf("GitBranch=%s\n", mypkg.GitBranch) 13 | fmt.Printf("GitState=%s\n", mypkg.GitState) 14 | fmt.Printf("GitSummary=%s\n", mypkg.GitSummary) 15 | } 16 | -------------------------------------------------------------------------------- /integration-test/app-different-package/mypkg/version.go: -------------------------------------------------------------------------------- 1 | package mypkg 2 | 3 | var ( 4 | // These fields are populated by govvv 5 | BuildDate string 6 | GitCommit string 7 | GitBranch string 8 | GitState string 9 | GitSummary string 10 | Version string 11 | ) 12 | -------------------------------------------------------------------------------- /integration-test/app-empty/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println("Hello, world!") 7 | } 8 | -------------------------------------------------------------------------------- /integration-test/app-example/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | var ( 6 | // These fields are populated by govvv 7 | Version = "untouched" 8 | BuildDate string 9 | GitCommit string 10 | GitBranch string 11 | GitState string 12 | GitSummary string 13 | ) 14 | 15 | func main() { 16 | fmt.Printf("Version=%s\n", Version) 17 | fmt.Printf("BuildDate=%s\n", BuildDate) 18 | fmt.Printf("GitCommit=%s\n", GitCommit) 19 | fmt.Printf("GitBranch=%s\n", GitBranch) 20 | fmt.Printf("GitState=%s\n", GitState) 21 | fmt.Printf("GitSummary=%s\n", GitSummary) 22 | } 23 | -------------------------------------------------------------------------------- /integration-test/app-extra-ldflags/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | var ( 6 | // GitCommit is provided by govvv 7 | GitCommit string 8 | 9 | // MyVariable is provided by user via -ldflags 10 | MyVariable string 11 | ) 12 | 13 | func main() { 14 | fmt.Printf("MyVariable=%s\n", MyVariable) 15 | fmt.Printf("GitCommit=%s\n", GitCommit) 16 | } 17 | -------------------------------------------------------------------------------- /integration-test/app-versioned/VERSION: -------------------------------------------------------------------------------- 1 | 2.0.1-app-versioned 2 | -------------------------------------------------------------------------------- /integration-test/app-versioned/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // Version comes from ./VERSION 6 | var Version string 7 | 8 | func main() { 9 | fmt.Printf("Version=%s\n", Version) 10 | } 11 | -------------------------------------------------------------------------------- /integration-test/test.bats: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bats 2 | 3 | @test "govvv exists" { 4 | command -v govvv 5 | } 6 | 7 | @test "checks not enough arguments" { 8 | run govvv 9 | echo "$output" 10 | [ "$status" -ne 0 ] 11 | [[ "$output" == *"not enough arguments"** ]] 12 | } 13 | 14 | @test "whitelists certain go commands" { 15 | run govvv doc 16 | echo "$output" 17 | [ "$status" -ne 0 ] 18 | [[ "$output" == *'only works with "build", "install" and "list". try "go doc" instead'** ]] 19 | } 20 | 21 | @test "fails on go tool failure and redirects output" { 22 | run govvv build -invalid-arg 23 | echo "$output" 24 | [ "$status" -ne 0 ] 25 | [[ "$output" == *'flag provided but not defined: -invalid-arg'** ]] 26 | } 27 | 28 | @test "govvv build - dry run" { 29 | run govvv build -v -print 30 | echo "$output" 31 | [ "$status" -eq 0 ] 32 | [[ "$output" == *"go build \\"* ]] 33 | [[ "$output" == *"-ldflags"* ]] 34 | } 35 | 36 | @test "govvv -flags" { 37 | run govvv -flags 38 | echo "$output" 39 | [ "$status" -eq 0 ] 40 | [[ "$output" =~ ^-X\ .* ]] 41 | } 42 | 43 | @test "govvv list" { 44 | run govvv list ./integration-test/app-empty 45 | echo "$output" 46 | [ "$status" -eq 0 ] 47 | } 48 | 49 | @test "govvv build - program with no compile-time variables" { 50 | tmp="${BATS_TMPDIR}/a.out" 51 | run govvv build -o "$tmp" ./integration-test/app-empty 52 | echo "$output" 53 | [ "$status" -eq 0 ] 54 | 55 | run "$tmp" 56 | echo "$output" 57 | [ "$status" -eq 0 ] 58 | [[ "$output" == "Hello, world!" ]] 59 | } 60 | 61 | @test "govvv install - works" { 62 | run govvv install ./integration-test/app-empty 63 | echo "$output" 64 | [ "$status" -eq 0 ] 65 | 66 | run app-empty 67 | echo "$output" 68 | [ "$status" -eq 0 ] 69 | [[ "$output" == "Hello, world!" ]] 70 | } 71 | 72 | @test "govvv build - program with compile-time variables" { 73 | tmp="${BATS_TMPDIR}/a.out" 74 | run bash -c "cd ${BATS_TEST_DIRNAME}/app-example && govvv build -o ${tmp}" 75 | echo "$output" 76 | [ "$status" -eq 0 ] 77 | 78 | run "$tmp" 79 | echo "$output" 80 | [ "$status" -eq 0 ] 81 | 82 | [[ "${lines[0]}" == "Version=untouched" ]] 83 | [[ "${lines[1]}" == "BuildDate="*Z ]] 84 | [[ "${lines[2]}" =~ ^GitCommit=[0-9a-f]{4,15}$ ]] 85 | [[ "${lines[3]}" =~ ^GitBranch=(.*)$ ]] 86 | [[ "${lines[4]}" =~ ^GitState=(clean|dirty)$ ]] 87 | [[ "${lines[5]}" =~ ^GitSummary=(.*)$ ]] 88 | } 89 | 90 | @test "govvv build - compile-time variables in different package" { 91 | tmp="${BATS_TMPDIR}/a.out" 92 | 93 | run bash -c "cd ${BATS_TEST_DIRNAME}/app-different-package && govvv build -pkg github.com/ahmetb/govvv/integration-test/app-different-package/mypkg -o $tmp" 94 | echo "$output" 95 | [ "$status" -eq 0 ] 96 | 97 | run "$tmp" 98 | echo "$output" 99 | [ "$status" -eq 0 ] 100 | 101 | [[ "${lines[0]}" == "Version=2.0.1-app-different-package" ]] 102 | [[ "${lines[1]}" == "BuildDate="*Z ]] 103 | [[ "${lines[2]}" =~ ^GitCommit=[0-9a-f]{4,15}$ ]] 104 | [[ "${lines[3]}" =~ ^GitBranch=(.*)$ ]] 105 | [[ "${lines[4]}" =~ ^GitState=(clean|dirty)$ ]] 106 | [[ "${lines[5]}" =~ ^GitSummary=(.*)$ ]] 107 | } 108 | 109 | @test "govvv -flags and -pkg" { 110 | 111 | run bash -c "cd ${BATS_TEST_DIRNAME}/app-different-package && govvv -flags -pkg github.com/ahmetb/govvv/integration-test/app-different-package/mypkg" 112 | echo "$output" 113 | [ "$status" -eq 0 ] 114 | 115 | [[ "$output" =~ -X\ github.com/ahmetb/govvv/integration-test/app-different-package/mypkg\.Version=2.0.1-app-different-package ]] 116 | } 117 | 118 | @test "govvv build - preserves given -ldflags" { 119 | tmp="${BATS_TMPDIR}/a.out" 120 | run govvv build -o "$tmp" -ldflags="-X main.MyVariable=myValue" ./integration-test/app-extra-ldflags 121 | echo "$output" 122 | [ "$status" -eq 0 ] 123 | 124 | run "$tmp" 125 | echo "$output" 126 | [ "$status" -eq 0 ] 127 | [[ "${lines[0]}" == "MyVariable=myValue" ]] 128 | [[ "${lines[1]}" =~ ^GitCommit=[0-9a-f]{4,15}$ ]] 129 | } 130 | 131 | @test "govvv build - reads Version from ./VERSION file" { 132 | tmp="${BATS_TMPDIR}/a.out" 133 | run bash -c "cd ${BATS_TEST_DIRNAME}/app-versioned && govvv build -o ${tmp} ." 134 | echo "$output" 135 | [ "$status" -eq 0 ] 136 | 137 | run "$tmp" 138 | echo "$output" 139 | [ "$status" -eq 0 ] 140 | [[ "$output" == "Version=2.0.1-app-versioned" ]] 141 | } 142 | 143 | @test "govvv build - reads Version from -version option" { 144 | tmp="${BATS_TMPDIR}/a.out" 145 | run bash -c "cd ${BATS_TEST_DIRNAME}/app-example && govvv build -o ${tmp} -version 1.2.3-command-line" 146 | [ "$status" -eq 0 ] 147 | echo "$output" 148 | [ "$status" -eq 0 ] 149 | 150 | run "$tmp" 151 | echo "$output" 152 | [ "$status" -eq 0 ] 153 | 154 | [[ "${lines[0]}" == "Version=1.2.3-command-line" ]] 155 | [[ "${lines[1]}" == "BuildDate="*Z ]] 156 | [[ "${lines[2]}" =~ ^GitCommit=[0-9a-f]{4,15}$ ]] 157 | [[ "${lines[3]}" =~ ^GitBranch=(.*)$ ]] 158 | [[ "${lines[4]}" =~ ^GitState=(clean|dirty)$ ]] 159 | [[ "${lines[5]}" =~ ^GitSummary=(.*)$ ]] 160 | } 161 | 162 | @test "govvv build - ./VERSION file overridden by -version option" { 163 | tmp="${BATS_TMPDIR}/a.out" 164 | run bash -c "cd ${BATS_TEST_DIRNAME}/app-versioned && govvv build -o ${tmp} -version 1.2.3-command-line" 165 | echo "$output" 166 | [ "$status" -eq 0 ] 167 | 168 | run "$tmp" 169 | echo "$output" 170 | [ "$status" -eq 0 ] 171 | [[ "$output" == "Version=1.2.3-command-line" ]] 172 | } 173 | 174 | @test "govvv compiled with govvv" { 175 | touch main.go 176 | run govvv install 177 | echo "$output" 178 | [ "$status" -eq 0 ] 179 | 180 | run govvv 181 | echo "$output" 182 | [[ "${lines[1]}" =~ ^version:\ (.*)@[0-9a-f]{4,15}-(dirty|clean)$ ]] 183 | } 184 | -------------------------------------------------------------------------------- /ldflags.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "strings" 7 | ) 8 | 9 | // mkLdFlags will generate a string compatible to use in "go build --ldflags" 10 | // with provided values. 11 | func mkLdFlags(values map[string]string) (string, error) { 12 | var b bytes.Buffer 13 | var i int 14 | for k, v := range values { 15 | if len(strings.Fields(k)) > 1 { 16 | return "", fmt.Errorf("cannot make ldflags for %q: key contains whitespaces", k) 17 | } 18 | if len(strings.Fields(v)) > 1 { 19 | v = fmt.Sprintf("'%s'", v) // surround it with single quotes 20 | } 21 | 22 | i++ 23 | b.WriteString(fmt.Sprintf("-X %s=%s", k, v)) 24 | if i != len(values) { 25 | b.WriteByte(' ') 26 | } 27 | } 28 | return b.String(), nil 29 | } 30 | 31 | // addLdFlags appends the specified ldflags value to args right after the 32 | // "build" or "install" arguments. If a -ldflags argument is already present, it 33 | // normalizes the argument (converts [-ldflags, val] into [-ldflags=val]) and 34 | // appends the given ldflags value. 35 | func addLdFlags(args []string, ldflags string) ([]string, error) { 36 | if ldIdx := findArg(args, "-ldflags"); ldIdx != -1 { // -ldflag exists, normalize and append 37 | args = normalizeArg(args, "-ldflags") 38 | args[ldIdx] = appendToFlag(args[ldIdx], ldflags) 39 | return args, nil 40 | } 41 | 42 | // -ldflags argument does not exist in args. 43 | // find where to insert the new argument (after "build" or "install") 44 | insertIdx := findArg(args, "build") 45 | if insertIdx == -1 { 46 | insertIdx = findArg(args, "install") 47 | } 48 | if insertIdx == -1 { 49 | return nil, fmt.Errorf("cannot locate where to append -ldflags") 50 | } 51 | 52 | // allocate a new slice to prevent modifying the old one 53 | newArgs := make([]string, insertIdx+1, len(args)+2) 54 | copy(newArgs, args[:insertIdx+1]) 55 | newArgs = append(newArgs, "-ldflags", ldflags) 56 | newArgs = append(newArgs, args[insertIdx+1:]...) 57 | return newArgs, nil 58 | } 59 | 60 | // appendToFlag appends val to -arg or -arg=... format. If the flag is missing a 61 | // value, it adds a "=" to the flag before appending the value. If a value 62 | // already exists, inserts a space character before appending the value. 63 | func appendToFlag(arg, val string) string { 64 | if !strings.ContainsRune(arg, '=') { 65 | arg = arg + "=" 66 | } 67 | if arg[len(arg)-1] != '=' && arg[len(arg)-1] != ' ' { 68 | arg += " " 69 | } 70 | arg += val 71 | return arg 72 | } 73 | 74 | // findArgs looks for 'arg' or 'arg=...' values in args and returns its index or 75 | // -1 if not found. 76 | func findArg(args []string, arg string) int { 77 | key := arg + "=" 78 | for i, v := range args { 79 | if v == arg || strings.HasPrefix(v, key) { 80 | return i 81 | } 82 | } 83 | return -1 84 | } 85 | 86 | // normalize finds the -arg in the args and concats its value to the same 87 | // argument. e.g. [-arg, foo] will be converted to [-arg="foo"] only once. 88 | func normalizeArg(args []string, arg string) []string { 89 | idx := -1 90 | for i, v := range args { 91 | if v == arg { 92 | idx = i 93 | break 94 | } 95 | } 96 | if idx == -1 || idx == len(args)-1 { // not found OR -arg has no succeding element 97 | return args 98 | } 99 | newArg := fmt.Sprintf("%s=%s", args[idx], args[idx+1]) // merge values 100 | args[idx] = newArg // modify the arg 101 | return append(args[:idx+1], args[idx+2:]...) 102 | } 103 | -------------------------------------------------------------------------------- /ldflags_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/require" 7 | ) 8 | 9 | func Test_mkldFlags_fails(t *testing.T) { 10 | _, err := mkLdFlags(map[string]string{"key space": "val"}) 11 | require.NotNil(t, err) 12 | require.Contains(t, err.Error(), "key contains whitespaces") 13 | 14 | _, err = mkLdFlags(map[string]string{"key": "val space"}) 15 | require.Nil(t, err, "values can have spaces") 16 | } 17 | 18 | func Test_mkldFlags(t *testing.T) { 19 | { // empty 20 | out, err := mkLdFlags(map[string]string{}) 21 | require.Nil(t, err) 22 | require.Empty(t, out) 23 | } 24 | { // normal input 25 | out, err := mkLdFlags(map[string]string{ 26 | "key1": "val1", 27 | "key2": "val 2", 28 | }) 29 | require.Nil(t, err) 30 | expected := []string{ 31 | "-X key1=val1 -X key2='val 2'", 32 | "-X key2='val 2' -X key1=val1"} 33 | 34 | if out != expected[0] && out != expected[1] { 35 | t.Fatalf("output: %q, expected: either %q --or-- %q", out, expected[0], expected[1]) 36 | } 37 | } 38 | } 39 | 40 | func Test_addLdFlags(t *testing.T) { 41 | type testcase struct { 42 | in []string 43 | out []string 44 | } 45 | validateCases := func(tc []testcase, ldflagsVal string) { 46 | for _, c := range tc { 47 | out, err := addLdFlags(c.in, ldflagsVal) 48 | require.Nil(t, err) 49 | require.Equal(t, c.out, out, "input args=%#v", c.in) 50 | } 51 | } 52 | 53 | { // cannot find where to append ldflags 54 | _, err := addLdFlags([]string{"a", "b", "c"}, "NEW VALUE") 55 | require.NotNil(t, err) 56 | require.EqualError(t, err, "cannot locate where to append -ldflags") 57 | } 58 | { 59 | // modifies existing -ldflags 60 | val := "NEW" 61 | cases := []testcase{ 62 | { 63 | []string{"build", "-ldflags"}, 64 | []string{"build", "-ldflags=NEW"}, 65 | }, 66 | { 67 | []string{"build", "-ldflags", "OLD"}, 68 | []string{"build", "-ldflags=OLD NEW"}, 69 | }, 70 | { 71 | []string{"-v", "build", "-ldflags=OLD"}, 72 | []string{"-v", "build", "-ldflags=OLD NEW"}, 73 | }, 74 | } 75 | validateCases(cases, val) 76 | } 77 | { // adds it after "build" or "install" 78 | val := "NEW VALUE" 79 | cases := []testcase{ 80 | { 81 | []string{"build"}, 82 | []string{"build", "-ldflags", val}, 83 | }, 84 | { 85 | []string{"install"}, 86 | []string{"install", "-ldflags", val}, 87 | }, 88 | { 89 | []string{"build", "-v"}, 90 | []string{"build", "-ldflags", val, "-v"}, 91 | }, 92 | { 93 | []string{"-v", "build", "."}, 94 | []string{"-v", "build", "-ldflags", val, "."}, 95 | }, 96 | { 97 | []string{"build", "-aflag", "-v", "."}, 98 | []string{"build", "-ldflags", val, "-aflag", "-v", "."}, 99 | }, 100 | } 101 | validateCases(cases, val) 102 | } 103 | } 104 | 105 | func Test_appendToFlag(t *testing.T) { 106 | v := "VALUE" 107 | cases := []struct{ in, out string }{ 108 | {"-arg", "-arg=VALUE"}, 109 | {"-arg=", "-arg=VALUE"}, 110 | {"-arg=OLD", "-arg=OLD VALUE"}, 111 | {"-arg=OLD ", "-arg=OLD VALUE"}, 112 | } 113 | for _, c := range cases { 114 | out := appendToFlag(c.in, v) 115 | require.Equal(t, c.out, out, "input=%q", cases) 116 | } 117 | } 118 | 119 | func Test_findArg(t *testing.T) { 120 | cases := []struct { 121 | in []string 122 | key string 123 | out int 124 | }{ 125 | {[]string{"foo", "bar", "quux"}, "none", -1}, 126 | {[]string{"foo", "bar", "quux"}, "bar", 1}, 127 | {[]string{"foo", "bar=val", "quux"}, "bar", 1}, 128 | {[]string{"foo", "bar=val", "quux"}, "bar", 1}, 129 | {[]string{"-arg1=bar", "-arg2"}, "-arg1", 0}, 130 | {[]string{"-arg1=foo", "-arg2=foo"}, "-arg2", 1}, 131 | {[]string{"-foo", "--bar"}, "-bar", -1}, 132 | } 133 | for _, c := range cases { 134 | out := findArg(c.in, c.key) 135 | require.EqualValues(t, c.out, out, "key=%q args=%#v", c.key, c.in) 136 | } 137 | } 138 | 139 | func Test_normalizeArg(t *testing.T) { 140 | cases := []struct { 141 | arg string 142 | in, out []string 143 | }{ 144 | { // arg has no value 145 | "-foo", 146 | []string{"a", "b", "-foo"}, 147 | []string{"a", "b", "-foo"}, 148 | }, 149 | { // normalize at the end 150 | "-key1", 151 | []string{"a", "b", "-key1", "value"}, 152 | []string{"a", "b", "-key1=value"}, 153 | }, 154 | { // normalize at the beginning 155 | "-key2", 156 | []string{"-key2", "value", "a", "b"}, 157 | []string{"-key2=value", "a", "b"}, 158 | }, 159 | { // already in desired format 160 | "-key3", 161 | []string{"a", "b", "-key3=value"}, 162 | []string{"a", "b", "-key3=value"}, 163 | }, 164 | } 165 | for _, c := range cases { 166 | out := normalizeArg(c.in, c.arg) 167 | require.EqualValues(t, c.out, out, "arg=%q input: %#v", c.arg, c.in) 168 | } 169 | } 170 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "log" 7 | "os" 8 | "os/exec" 9 | "strconv" 10 | "strings" 11 | ) 12 | 13 | func init() { 14 | log.SetFlags(0) 15 | } 16 | 17 | const ( 18 | defaultPackage = "main" 19 | flDryRun = "-print" 20 | flDryRunPrintLdFlags = "-flags" 21 | flPackage = "-pkg" 22 | flVersion = "-version" 23 | ) 24 | 25 | var ( 26 | // govvvDirectives is mapping of govvv directives, which must be elided 27 | // when constructing the final go tool command, to a boolean which 28 | // indicates whether the directive takes an argument or not. 29 | govvvDirectives = map[string]bool{ 30 | flDryRun: false, 31 | flDryRunPrintLdFlags: false, 32 | flPackage: true, 33 | flVersion: true} 34 | ) 35 | 36 | func main() { 37 | args := os.Args 38 | if len(args) < 2 { 39 | log.Println(`govvv: not enough arguments (try "govvv build .")`) 40 | log.Printf("version: %s", versionString()) 41 | os.Exit(1) 42 | } else if args[1] != "build" && args[1] != "install" && args[1] != "list" && !isGovvvDirective(args[1]) { 43 | // do not wrap the entire 'go tool' 44 | // "list" is wrapped to be compatible with mitchellh/gox. 45 | log.Fatalf(`govvv: only works with "build", "install" and "list". try "go %s" instead`, args[1]) 46 | } 47 | 48 | wd, err := os.Getwd() 49 | if err != nil { 50 | log.Fatalf("govvv: cannot get working directory: %v", err) 51 | } 52 | 53 | versionValues, err := GetFlags(wd, args) 54 | if err != nil { 55 | log.Fatalf("failed to collect values: %v", err) 56 | } 57 | 58 | ldflags, err := mkLdFlags(versionValues) 59 | if err != nil { 60 | log.Fatalf("failed to compile values: %v", err) 61 | } 62 | 63 | if _, ok := collectGovvvDirective(args, flDryRunPrintLdFlags); ok { 64 | fmt.Print(ldflags) 65 | return 66 | } 67 | 68 | args = args[1:] // rm executable name 69 | 70 | if args[0] == "build" || args[0] == "install" { 71 | args, err = addLdFlags(args, ldflags) 72 | if err != nil { 73 | log.Fatalf("failed to add ldflags to args: %v", err) 74 | } 75 | } 76 | 77 | if _, ok := collectGovvvDirective(args, flDryRun); ok { 78 | fmt.Println(goToolDryRunCmd(args)) 79 | return 80 | } 81 | 82 | args = scrubGovvvDirectives(args) 83 | 84 | if err := execGoTool(args); err != nil { 85 | log.Fatalf("go tool: %v", err) 86 | } 87 | } 88 | 89 | // execGoTool invokes "go" with given arguments and passes the current 90 | // process' standard streams. 91 | func execGoTool(args []string) error { 92 | cmd := exec.Command("go", args...) 93 | cmd.Stdout, cmd.Stderr, cmd.Stdin = os.Stdout, os.Stderr, os.Stdin 94 | return cmd.Run() 95 | } 96 | 97 | // goToolDryRunCmd returns a POSIX shell-compatible command that would normally 98 | // get executed. Not guaranteed to quote and escape the args very well. 99 | func goToolDryRunCmd(args []string) string { 100 | var b bytes.Buffer 101 | b.WriteString("go") 102 | b.WriteRune(' ') 103 | printed := false 104 | for _, v := range scrubGovvvDirectives(args) { 105 | if printed { 106 | b.WriteString(" \\\n") 107 | b.WriteString("\t") 108 | } 109 | 110 | if strings.ContainsAny(v, " \"'\n\t") { 111 | v = strconv.QuoteToASCII(v) 112 | } 113 | b.WriteString(v) 114 | printed = true 115 | 116 | } 117 | return b.String() 118 | } 119 | 120 | // isGovvvDirective returns true if the arg is a govvv directive, and false 121 | // otherwise. 122 | func isGovvvDirective(arg string) bool { 123 | _, ok := govvvDirectives[arg] 124 | return ok 125 | } 126 | 127 | // scrubGovvvDirectives filters out govvv directs to return a clean set of args 128 | // that can be passed to the go command. 129 | func scrubGovvvDirectives(args []string) (filtered []string) { 130 | filtered = []string{} 131 | skipping := 0 132 | for _, arg := range args { 133 | if skipping > 0 { 134 | skipping-- 135 | continue 136 | } 137 | if hasArgument, ok := govvvDirectives[arg]; ok { 138 | if hasArgument { 139 | skipping = 1 140 | } 141 | } else { 142 | filtered = append(filtered, arg) 143 | } 144 | } 145 | return filtered 146 | } 147 | 148 | // collectGovvvDirective searches the args array for a directive and a possible 149 | // argument for that directive. It returns that argument, or "", if the 150 | // directive takes none, and an indication if the directive was actually found. 151 | func collectGovvvDirective(args []string, directive string) (argument string, ok bool) { 152 | for i, arg := range args { 153 | if directive == arg { 154 | hasArgument, _ := govvvDirectives[arg] 155 | if !hasArgument { 156 | return "", true 157 | } else if i+1 < len(args) { 158 | return args[i+1], true 159 | } else { 160 | break 161 | } 162 | } 163 | } 164 | return "", false 165 | } 166 | -------------------------------------------------------------------------------- /main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/stretchr/testify/require" 5 | "testing" 6 | ) 7 | 8 | func TestIsGovvvDirective(t *testing.T) { 9 | for directive := range govvvDirectives { 10 | require.True(t, isGovvvDirective(directive)) 11 | } 12 | 13 | require.False(t, isGovvvDirective("-o")) 14 | } 15 | 16 | func TestScrubGovvvDirectives(t *testing.T) { 17 | require.Equal(t, []string{}, []string{}, "scrubGovvvDirectives should be fine with an empty arg array") 18 | 19 | require.Equal(t, []string{"build", "-o", "a.out"}, scrubGovvvDirectives([]string{"build", "-o", "a.out"}), 20 | "scrubGovvvDirectives should not touch normal go args") 21 | 22 | require.Equal(t, []string{}, scrubGovvvDirectives([]string{"-flags"}), 23 | "scrubGovvvDirectives should scrub -flags") 24 | 25 | require.Equal(t, []string{"build", "-o", "a.out"}, scrubGovvvDirectives([]string{"build", "-o", "a.out", "-print"}), 26 | "scrubGovvvDirectives should scrub -print") 27 | 28 | require.Equal(t, []string{"build", "-o", "a.out"}, 29 | scrubGovvvDirectives([]string{"build", "-o", "a.out", "-pkg", "github.com/ahmetb/govvv"}), 30 | "scrubGovvvDirectives should scrub -pkg and its argument") 31 | } 32 | 33 | func TestCollectGovvvDirective(t *testing.T) { 34 | argument, ok := collectGovvvDirective([]string{}, flDryRun) 35 | require.False(t, ok) 36 | require.Equal(t, "", argument, "collectGovvvDirective should be fine with an empty arg array") 37 | 38 | argument, ok = collectGovvvDirective([]string{"build", "-o", "a.out", "-print"}, flDryRun) 39 | require.True(t, ok) 40 | require.Equal(t, "", argument, "collectGovvvDirective should find -print") 41 | 42 | argument, ok = collectGovvvDirective([]string{"-flags"}, flDryRunPrintLdFlags) 43 | require.True(t, ok) 44 | require.Equal(t, "", argument, "collectGovvvDirective should find -flags") 45 | 46 | argument, ok = collectGovvvDirective([]string{"build", "-o", "a.out", "-pkg", "github.com/ahmetb/govvv"}, flPackage) 47 | require.True(t, ok) 48 | require.Equal(t, "github.com/ahmetb/govvv", argument, "collectGovvvDirective should find -pkg") 49 | 50 | argument, ok = collectGovvvDirective([]string{"build", "-o", "a.out", "-pkg"}, flPackage) 51 | require.False(t, ok) 52 | require.Equal(t, "", argument, "collectGovvvDirective should catch missing argument for -pkg") 53 | } 54 | -------------------------------------------------------------------------------- /values.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "io/ioutil" 7 | "os" 8 | "path/filepath" 9 | "time" 10 | ) 11 | 12 | const versionFile = "VERSION" 13 | 14 | // GetFlags collects data to be passed as ldflags. 15 | func GetFlags(dir string, args []string) (map[string]string, error) { 16 | repo := git{dir} 17 | gitBranch := repo.Branch() 18 | gitCommit, err := repo.Commit() 19 | if err != nil { 20 | return nil, fmt.Errorf("failed to get commit: %v", err) 21 | } 22 | gitState, err := repo.State() 23 | if err != nil { 24 | return nil, fmt.Errorf("failed to get repository state: %v", err) 25 | } 26 | gitSummary, err := repo.Summary() 27 | if err != nil { 28 | return nil, fmt.Errorf("failed to get repository summary: %v", err) 29 | } 30 | 31 | // prefix keys with package to be used by ldflags -X 32 | pkg := defaultPackage 33 | if value, ok := collectGovvvDirective(args, flPackage); ok { 34 | pkg = value 35 | } 36 | 37 | v := map[string]string{ 38 | pkg + ".BuildDate": date(), 39 | pkg + ".GitCommit": gitCommit, 40 | pkg + ".GitBranch": gitBranch, 41 | pkg + ".GitState": gitState, 42 | pkg + ".GitSummary": gitSummary, 43 | } 44 | 45 | // calculate the version 46 | if value, ok := collectGovvvDirective(args, flVersion); ok { 47 | v[pkg+".Version"] = value 48 | } else { 49 | value, err := versionFromFile(dir) 50 | if err != nil { 51 | return nil, err 52 | } else if value != "" { 53 | v[pkg+".Version"] = value 54 | } 55 | } 56 | 57 | return v, nil 58 | } 59 | 60 | // date returns the UTC date formatted in RFC 3339 layout. 61 | func date() string { 62 | return time.Now().UTC().Format(time.RFC3339) 63 | } 64 | 65 | // versionFromFile looks for a file named VERSION in dir if it exists and 66 | // returns its contents by trimming the whitespace around it. If the file 67 | // does not exist, it does not return any errors 68 | func versionFromFile(dir string) (string, error) { 69 | fp := filepath.Join(dir, versionFile) 70 | b, err := ioutil.ReadFile(fp) 71 | if os.IsNotExist(err) { 72 | return "", nil 73 | } 74 | if err != nil { 75 | return "", fmt.Errorf("failed to read version file %s: %v", fp, err) 76 | } 77 | return string(bytes.TrimSpace(b)), nil 78 | } 79 | -------------------------------------------------------------------------------- /values_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "io/ioutil" 5 | "os" 6 | "path/filepath" 7 | "testing" 8 | 9 | "github.com/stretchr/testify/require" 10 | ) 11 | 12 | func TestGetFlags_error(t *testing.T) { 13 | repo := newRepo(t) 14 | defer os.RemoveAll(repo.dir) 15 | 16 | _, err := GetFlags(repo.dir, []string{}) 17 | require.NotNil(t, err) 18 | require.Contains(t, err.Error(), "failed to get commit") 19 | } 20 | 21 | func Test_date(t *testing.T) { 22 | v := date() 23 | require.Regexp(t, "^[0-9]{4}(-[0-9]{2}){2}T([0-9]{2}:){2}[0-9]{2}Z$", v) 24 | } 25 | 26 | func TestGetFlags(t *testing.T) { 27 | // prepare the repo 28 | repo := newRepo(t) 29 | defer os.RemoveAll(repo.dir) 30 | mkCommit(t, repo, "commit 1") 31 | mkCommit(t, repo, "commit 2") 32 | 33 | // read the flags 34 | fl, err := GetFlags(repo.dir, []string{}) 35 | require.Nil(t, err) 36 | 37 | // validate the flags 38 | require.Regexp(t, "^[0-9]{4}(-[0-9]{2}){2}T([0-9]{2}:){2}[0-9]{2}Z$", fl["main.BuildDate"]) 39 | require.Regexp(t, "^[0-9a-f]{4,15}$", fl["main.GitCommit"]) 40 | require.Equal(t, "master", fl["main.GitBranch"]) 41 | require.Equal(t, "clean", fl["main.GitState"]) 42 | require.Equal(t, fl["main.GitCommit"], fl["main.GitSummary"]) 43 | } 44 | 45 | func TestGetFlags_versionDefault(t *testing.T) { 46 | // prepare the repo 47 | repo := newRepo(t) 48 | defer os.RemoveAll(repo.dir) 49 | mkCommit(t, repo, "commit 1") 50 | 51 | // there is no main.Version flag 52 | fl, err := GetFlags(repo.dir, []string{}) 53 | require.Nil(t, err) 54 | require.NotContains(t, fl, "main.Version") 55 | } 56 | 57 | func TestGetFlags_justVersionFlag(t *testing.T) { 58 | // prepare the repo 59 | repo := newRepo(t) 60 | defer os.RemoveAll(repo.dir) 61 | mkCommit(t, repo, "commit 1") 62 | 63 | // -version is specified and there is no VERSION file 64 | fl, err := GetFlags(repo.dir, []string{flVersion, "2.0.0-RC01"}) 65 | require.Nil(t, err) 66 | require.Equal(t, "2.0.0-RC01", fl["main.Version"]) 67 | } 68 | 69 | func TestGetFlags_versionFile(t *testing.T) { 70 | // prepare the repo 71 | repo := newRepo(t) 72 | defer os.RemoveAll(repo.dir) 73 | mkCommit(t, repo, "commit 1") 74 | 75 | // add version file and get the value back 76 | require.Nil(t, ioutil.WriteFile(filepath.Join(repo.dir, "VERSION"), []byte("2.0.0-beta\n"), 0600)) 77 | fl, err := GetFlags(repo.dir, []string{}) 78 | require.Nil(t, err) 79 | require.Equal(t, "2.0.0-beta", fl["main.Version"]) 80 | } 81 | 82 | func TestGetFlags_versionFlagOverrides(t *testing.T) { 83 | // prepare the repo 84 | repo := newRepo(t) 85 | defer os.RemoveAll(repo.dir) 86 | mkCommit(t, repo, "commit 1") 87 | 88 | // add version file 89 | require.Nil(t, ioutil.WriteFile(filepath.Join(repo.dir, "VERSION"), []byte("2.0.0-beta\n"), 0600)) 90 | 91 | // -version is specified and there is na VERSION file (flag takes precedence) 92 | fl, err := GetFlags(repo.dir, []string{flVersion, "2.0.0-RC01"}) 93 | require.Nil(t, err) 94 | require.Equal(t, "2.0.0-RC01", fl["main.Version"]) 95 | } 96 | 97 | func TestGetFlags_versionFileError(t *testing.T) { 98 | // prepare the repo 99 | repo := newRepo(t) 100 | defer os.RemoveAll(repo.dir) 101 | mkCommit(t, repo, "commit 1") 102 | 103 | // add version file and get the value back 104 | require.Nil(t, ioutil.WriteFile(filepath.Join(repo.dir, "VERSION"), []byte("2.0.0-beta\n"), 0000)) 105 | fl, err := GetFlags(repo.dir, []string{}) 106 | require.Nil(t, fl) 107 | require.Contains(t, err.Error(), "failed to read version file") 108 | } 109 | 110 | func TestGetFlags_pkgFlag(t *testing.T) { 111 | // prepare the repo 112 | repo := newRepo(t) 113 | defer os.RemoveAll(repo.dir) 114 | mkCommit(t, repo, "commit 1") 115 | mkCommit(t, repo, "commit 2") 116 | 117 | // read the flags for custom package 118 | pkg := "github.com/acct/coolproject/version" 119 | fl, err := GetFlags(repo.dir, []string{flPackage, pkg}) 120 | require.Nil(t, err) 121 | 122 | // validate the flags 123 | require.Contains(t, fl, pkg+".BuildDate") 124 | require.Contains(t, fl, pkg+".GitCommit") 125 | require.Contains(t, fl, pkg+".GitBranch") 126 | require.Contains(t, fl, pkg+".GitState") 127 | require.Contains(t, fl, pkg+".GitSummary") 128 | } 129 | 130 | func Test_versionFromFile_notFound(t *testing.T) { 131 | dir := tmpDir(t) 132 | defer os.RemoveAll(dir) 133 | 134 | v, err := versionFromFile(dir) 135 | require.Equal(t, "", v) 136 | require.Nil(t, err) 137 | } 138 | 139 | func Test_versionFromFile_error(t *testing.T) { 140 | dir := tmpDir(t) 141 | defer os.RemoveAll(dir) 142 | 143 | require.Nil(t, ioutil.WriteFile(filepath.Join(dir, "VERSION"), nil, 0200)) // // no read perms 144 | 145 | _, err := versionFromFile(dir) 146 | require.NotNil(t, err) 147 | require.Contains(t, err.Error(), "failed to read version file") 148 | } 149 | 150 | func Test_versionFromFile(t *testing.T) { 151 | dir := tmpDir(t) 152 | defer os.RemoveAll(dir) 153 | 154 | require.Nil(t, ioutil.WriteFile(filepath.Join(dir, "VERSION"), []byte("\t 0.6.0.0 \n "), 0600)) // // no read perms 155 | 156 | v, err := versionFromFile(dir) 157 | require.Nil(t, err) 158 | require.Equal(t, "0.6.0.0", v) 159 | } 160 | 161 | // Test utilities 162 | 163 | func tmpDir(t *testing.T) string { 164 | dir, err := ioutil.TempDir("", "") 165 | require.Nil(t, err, "failed to create test directory") 166 | return dir 167 | } 168 | -------------------------------------------------------------------------------- /version.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | var ( 6 | // Version is populated at compile time by govvv from ./VERSION 7 | Version string 8 | 9 | // GitCommit is populated at compile time by govvv. 10 | GitCommit string 11 | 12 | // GitState is populated at compile time by govvv. 13 | GitState string 14 | ) 15 | 16 | func versionString() string { 17 | if Version == "" { 18 | return "N/A" 19 | } 20 | return fmt.Sprintf("%s@%s-%s", Version, GitCommit, GitState) 21 | } 22 | --------------------------------------------------------------------------------