diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..899b995 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,11 @@ +version: 2 + +updates: + - package-ecosystem: gomod + directory: '/' + schedule: + interval: weekly + - package-ecosystem: github-actions + directory: '/' + schedule: + interval: weekly diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml new file mode 100644 index 0000000..d3a4601 --- /dev/null +++ b/.github/workflows/go.yml @@ -0,0 +1,28 @@ +name: Go + +on: + push: + branches: + - main + - v* + pull_request: + branches: + - main + - v* + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Set up Go + uses: actions/setup-go@v3 + with: + go-version: '>=1.19.0' + + - uses: actions/checkout@v3 + + - name: Build + run: go build -v ./... + + - name: Test + run: go test -v ./... diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml new file mode 100644 index 0000000..eba8477 --- /dev/null +++ b/.github/workflows/golangci-lint.yml @@ -0,0 +1,25 @@ +name: golangci-lint +on: + push: + tags: + - v* + branches: + - main + - v* + pull_request: +jobs: + golangci: + name: lint + runs-on: ubuntu-latest + steps: + - name: Set up Go + uses: actions/setup-go@v3 + with: + go-version: '>=1.19.0' + + - uses: actions/checkout@v3 + + - name: golangci-lint + uses: golangci/golangci-lint-action@v3.3.1 + with: + version: latest diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..1bdd5b2 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2022 The qiniu/version Authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index 5a36a00..7bbf2fb 100644 --- a/README.md +++ b/README.md @@ -1,21 +1,30 @@ -# version -fast way to add version information for your application +# qiniu/version -## Usage +A fast way to add assorted version information for your application. -Import this package in your application: +Note this is tailored primarily to Qiniu's internal needs, and may or may not +suit your specific case. + +## License + +`qiniu/version` is licensed under [the Apache 2.0 license](./LICENSE). + +## Quick start + +If you're in a hurry, just import the easy hook package: ```go -import _ "github.com/qiniu/version" +import _ "github.com/qiniu/version/v2/easyHook" ``` Build it with: ```shell -go build -ldflags "-X 'github.com/qiniu/version.BuildDate=$(date)'" . +go build -ldflags "-X 'github.com/qiniu/version/v2.BuildDate=$(date)'" . ``` -Then run your app with parameters `version` or `--version`, you will get output like: +Then run your app with `version`, `-version` or `--version`, and you will see +output like: ```shell ✗ ./examples version @@ -32,7 +41,21 @@ Also, there are some other useful options for your reference. For example: ```shell LDFLAGS="${LDFLAGS} \ - -X \"github.com/qiniu/version.GitTag=$(git describe --tags)\" \ - -X \"github.com/qiniu/version.BuildComments=${BUILDCOMMENTS}\" \ - -X \"github.com/qiniu/version.Name=${NAME}\" \ -``` \ No newline at end of file + -X \"github.com/qiniu/version/v2.GitTag=$(git describe --tags)\" \ + -X \"github.com/qiniu/version/v2.BuildComments=${BUILDCOMMENTS}\" \ + -X \"github.com/qiniu/version/v2.Name=${NAME}\" \ +``` + +Check the source code for details. + +## Advanced usage + +The easy hook package used in the above steps can bring about surprises. +For example, small programs designed to operate on a single input file path +argument will suddenly stop working with a path of `version`, because the +invocation `foo version` will be intercepted by this package and your `func main` +will not even have a chance to run. + +If you want more control, you may simply import `github.com/qiniu/version/v2` +and call `version.Print()` or consume the individual values exposed there, +to your own liking. diff --git a/doc.go b/doc.go index 3268b6d..2defdf0 100644 --- a/doc.go +++ b/doc.go @@ -1,5 +1,19 @@ -// package version defines the information for versioning binary -// usage: +// Package version provides access to some of your binary's versioning +// information. // -// import _ "github.com/qiniu/version" +// The easy way to integrate this package, but could bring about surprising +// behavior (read the source for details, it's just a one-liner!): +// +// import _ "github.com/qiniu/version/v2/easyHook" +// +// And if you want more control and less magic: +// +// import "github.com/qiniu/version/v2" +// +// func main() { +// // make use of one of the prepopulated values +// _ = version.GitCommit +// // or output in the package-standard format in your CLI handler +// version.Print() +// } package version diff --git a/easyHook/mod.go b/easyHook/mod.go new file mode 100644 index 0000000..2e21a46 --- /dev/null +++ b/easyHook/mod.go @@ -0,0 +1,17 @@ +package easyHook + +import ( + "os" + + "github.com/qiniu/version/v2" +) + +func init() { + // usages: version (or --version / -version) + if len(os.Args) > 1 && (os.Args[1] == "version" || os.Args[1] == "--version" || os.Args[1] == "-version") { + version.Print() + os.Exit(0) + } + + // TODO: expose version information via exporter as needed +} diff --git a/examples/.gitignore b/examples/.gitignore new file mode 100644 index 0000000..95811e0 --- /dev/null +++ b/examples/.gitignore @@ -0,0 +1 @@ +/main diff --git a/examples/Makefile b/examples/Makefile new file mode 100644 index 0000000..51fa6ac --- /dev/null +++ b/examples/Makefile @@ -0,0 +1,8 @@ +BUILDCOMMENT=package KODO.2022-11-30-14-16-28.tar.gz +GITTAG=`git describe --tags` +DATE=`date` +NAME=libversion +LDFLAGS="-X 'github.com/qiniu/version/v2.BuildDate=${DATE}' -X 'github.com/qiniu/version/v2.GitTag=${GITTAG}' -X 'github.com/qiniu/version/v2.BuildComments=${BUILDCOMMENT}' -X 'github.com/qiniu/version/v2.Name=${NAME}'" + +all: + go build -ldflags ${LDFLAGS} -v ./main.go diff --git a/examples/main.go b/examples/main.go index 6b3d94b..5682f71 100644 --- a/examples/main.go +++ b/examples/main.go @@ -3,7 +3,7 @@ package main import ( "fmt" - _ "github.com/qiniu/version" + _ "github.com/qiniu/version/v2/easyHook" ) func main() { diff --git a/go.mod b/go.mod index 9512f96..7580466 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,3 @@ -module github.com/qiniu/version +module github.com/qiniu/version/v2 go 1.19 diff --git a/makefile b/makefile deleted file mode 100644 index 0200a63..0000000 --- a/makefile +++ /dev/null @@ -1,8 +0,0 @@ -BUILDCOMMENT=package KODO.2022-11-30-14-16-28.tar.gz -GITTAG=`git describe --tags` -DATE=`date` -NAME=libversion -LDFLAGS="-X 'github.com/qiniu/version.BuildDate=${DATE}' -X 'github.com/qiniu/version.GitTag=${GITTAG}' -X 'github.com/qiniu/version.BuildComments=${BUILDCOMMENT}' -X 'github.com/qiniu/version.Name=${NAME}'" - -all: - go install -ldflags ${LDFLAGS} -v ./... \ No newline at end of file diff --git a/version.go b/version.go index 1a4486c..6349b02 100644 --- a/version.go +++ b/version.go @@ -2,88 +2,96 @@ package version import ( "fmt" - "os" "runtime" "runtime/debug" - "sync" ) const ( - unknownProperty = "N/A" + unknownProperty = "" ) -// Information of versioning +// Compiler is a convenient alias for runtime.Compiler. +const Compiler = runtime.Compiler + +// Version information var ( - // GoVersion is the version of the Go toolchain that built the binary(for example, "go1.19.2"). - // and will be filled via runtime.Version() automatically if not specified. + // GoVersion is the version of the Go toolchain used to build the binary + // (e.g. "go1.19.2"). + // It defaults to value of runtime.Version() if not explicitly overridden. GoVersion = unknownProperty - // GitCommit shows the revision identifier for the current commit or checkout. - // and will be filled via debug.BuildInfo.Settings automatically if not specified. + // GitCommit is the commit hash of the Git repository's HEAD at + // build-time. + // It defaults to the value as collected by the runtime/debug package if + // not explicitly overridden. GitCommit = unknownProperty - // GitCommitDate shows the time associated with GitCommit, in RFC3339 format - // and will be filled via debug.BuildInfo.Settings automatically if not specified. + // GitCommitDate is GitCommit's commit date in RFC3339 format. + // It defaults to the value as collected by the runtime/debug package if + // not explicitly overridden. GitCommitDate = unknownProperty - // GitTreeState shows "dirty" indicating the source tree had local modifications, otherwise it is invisible. + // GitTreeState becomes "dirty" if the source tree had local modifications + // at build-time. + // It stays empty otherwise and will not be shown in Print if this is the + // case. GitTreeState = unknownProperty - // GitTag shows latest tag if injected by go -ldflags, otherwise it is invisible. + // GitTag is meant to be injected with the tag name associated with + // GitCommit, by means of `go -ldflags` at build-time. + // It stays empty otherwise and will not be shown in Print if this is the + // case. GitTag = unknownProperty - // BuildDate shows the built time for the associated binary if injected by go -ldflags. otherwise it is invisible. + // BuildDate is meant to be injected with a string denoting the build time + // of the binary, by means of `go -ldflags` at build-time. + // It stays empty otherwise and will not be shown in Print if this is the + // case. BuildDate = unknownProperty - // Platform composes with GOARCH and GOOS automatically. + // Platform is a string in the form of "GOOS/GOARCH", e.g. "linux/amd64". Platform = unknownProperty - // Compiler shows the toolchain flag used (typically "gc") - Compiler = unknownProperty - // BuildComments provides extra information if needed. + // BuildComments can be used to associate arbitrary extra information with + // the binary, by means of injection via `go -ldflags` at build-time. BuildComments = unknownProperty - // Name shows the name of your binary if provided, otherwise it is invisible. + // Name is meant to be injected with the binary's intended name, by means + // of `go -ldflags` at build-time. + // It stays empty otherwise and will not be shown in Print if this is the + // case. Name = unknownProperty ) +// This is for preventing access to the unpopulated properties. func init() { - // usages: version (or --version / -version) - if len(os.Args) > 1 && (os.Args[1] == "version" || os.Args[1] == "--version" || os.Args[1] == "-version") { - Version() - os.Exit(0) - } - - // TODO: expose version information via exporter as needed + collectFromBuildInfo() + collectFromRuntime() } -var once sync.Once - -// Version prints the information of versioning -func Version() { - once.Do(func() { - collectFromBuildInfo() - collectFromRuntime() - }) +// Print prints out the collected version information. +func Print() { + xprintf := func(k string, v string) { + fmt.Printf("%s:\t%s\n", k, v) + } - format := "%s:\t%s\n" if Name != unknownProperty { - xprintf(format, "Name", Name) + xprintf("Name", Name) } - xprintf(format, "Go version", GoVersion) - xprintf(format, "Git commit", GitCommit) - xprintf(format, "Commit date", GitCommitDate) + xprintf("Go version", GoVersion) + xprintf("Git commit", GitCommit) + xprintf("Commit date", GitCommitDate) if GitTreeState != unknownProperty { - xprintf(format, "Git state", GitTreeState) + xprintf("Git state", GitTreeState) } if BuildDate != unknownProperty { - xprintf(format, "Built date", BuildDate) + xprintf("Build date", BuildDate) } if BuildComments != unknownProperty { - xprintf(format, "Built comments", BuildComments) + xprintf("Build comments", BuildComments) } - xprintf(format, "OS/Arch", Platform) - xprintf(format, "Compiler", Compiler) + xprintf("OS/Arch", Platform) + xprintf("Compiler", Compiler) if GitTag != unknownProperty { - xprintf(format, "Git tag", GitTag) + xprintf("Git tag", GitTag) } } @@ -124,13 +132,4 @@ func collectFromRuntime() { if Platform == unknownProperty { Platform = fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH) } - - if Compiler == unknownProperty { - Compiler = runtime.Compiler - } -} - -// xprintf prints a message to standard output. -func xprintf(format string, args ...interface{}) { - fmt.Printf(format, args...) }