Skip to content

Commit

Permalink
initial version from fortio.org/fortio/version + sample main
Browse files Browse the repository at this point in the history
  • Loading branch information
ldemailly committed Feb 12, 2023
1 parent d5f0b07 commit cb0d3df
Show file tree
Hide file tree
Showing 5 changed files with 309 additions and 0 deletions.
174 changes: 174 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
# Config for golanglint-ci

# output configuration options

# all available settings of specific linters
linters-settings:
gocritic:
disabled-checks:
- ifElseChain
dupl:
# tokens count to trigger issue, 150 by default
threshold: 100
exhaustive:
# indicates that switch statements are to be considered exhaustive if a
# 'default' case is present, even if all enum members aren't listed in the
# switch
default-signifies-exhaustive: false
funlen:
lines: 140
statements: 70
gocognit:
# minimal code complexity to report, 30 by default (but we recommend 10-20)
min-complexity: 42
nestif:
# minimal complexity of if statements to report, 5 by default
min-complexity: 4
gocyclo:
# minimal code complexity to report, 30 by default (but we recommend 10-20)
min-complexity: 30
godot:
# check all top-level comments, not only declarations
check-all: false
govet:
# report about shadowed variables
check-shadowing: true
# settings per analyzer
settings:
printf: # analyzer name, run `go tool vet help` to see all analyzers
funcs: # run `go tool vet help printf` to see available settings for `printf` analyzer
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Infof
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Warnf
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Errorf
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Fatalf
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Printf
- (github.com/golangci/golangci-lint/pkg/logutils.Log).FErrf
enable-all: true
disable-all: false
depguard:
list-type: blacklist
include-go-root: false
packages:
- github.com/sirupsen/logrus
packages-with-error-message:
# specify an error message to output when a blacklisted package is used
- github.com/sirupsen/logrus: "logging is allowed only by fortio.log"
lll:
# max line length, lines longer will be reported. Default is 120.
# '\t' is counted as 1 character by default, and can be changed with the tab-width option
line-length: 132
# tab width in spaces. Default to 1.
tab-width: 1
misspell:
# Correct spellings using locale preferences for US or UK.
# Default is to use a neutral variety of English.
# Setting locale to US will correct the British spelling of 'colour' to 'color'.
locale: US
ignore-words:
- fortio
nakedret:
# make an issue if func has more lines of code than this setting and it has naked returns; default is 30
max-func-lines: 30
nolintlint:
require-specific: true
whitespace:
multi-if: false # Enforces newlines (or comments) after every multi-line if statement
multi-func: false # Enforces newlines (or comments) after every multi-line function signature
gofumpt:
# Choose whether or not to use the extra rules that are disabled
# by default
extra-rules: false


linters:
disable:
# Deprecated ones:
- scopelint
- golint
- interfacer
- maligned
- varcheck
- structcheck
- nosnakecase
- deadcode
# Weird/bad ones:
- wsl
- nlreturn
- gochecknoinits
- gochecknoglobals
- gomnd
- testpackage
- wrapcheck
- exhaustivestruct
- tagliatelle
- nonamedreturns
- varnamelen
- exhaustruct # seems like a good idea at first but actually a pain and go does have zero values for a reason.
# TODO consider putting these back, when they stop being bugged (ifshort, wastedassign,...)
- paralleltest
- thelper
- forbidigo
- ifshort
- wastedassign
- cyclop
- forcetypeassert
- ireturn
enable-all: true
disable-all: false
# Must not use fast: true in newer golangci-lint or it'll just skip a bunch of linter instead of doing caching like before (!)
fast: false


issues:
# Excluding configuration per-path, per-linter, per-text and per-source
exclude-rules:
# Exclude some linters from running on tests files.
- path: _test\.go
linters:
- gocyclo
- errcheck
- dupl
- gosec
- gochecknoinits
- gochecknoglobals
- forcetypeassert
- nosnakecase
- noctx

# Exclude lll issues for long lines with go:generate
- linters:
- lll
source: "^//go:generate "
- linters:
- goerr113
text: "do not define dynamic errors"
- linters:
- govet
text: "fieldalignment:"
- linters:
- godox
text: "TODO"
- linters:
- nosnakecase
text: "grpc_|_SERVING|O_"

# Maximum issues count per one linter. Set to 0 to disable. Default is 50.
max-issues-per-linter: 0

# Maximum count of issues with the same text. Set to 0 to disable. Default is 3.
max-same-issues: 0

severity:
# Default value is empty string.
# Set the default severity for issues. If severity rules are defined and the issues
# do not match or no severity is provided to the rule this will be the default
# severity applied. Severities should match the supported severity names of the
# selected out format.
# - Code climate: https://docs.codeclimate.com/docs/issues#issue-severity
# - Checkstyle: https://checkstyle.sourceforge.io/property_types.html#severity
# - Github: https://help.github.com/en/actions/reference/workflow-commands-for-github-actions#setting-an-error-message
default-severity: error

# The default value is false.
# If set to true severity-rules regular expressions become case sensitive.
case-sensitive: false
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,10 @@
# version
Reusable wrappers/utils to extract version(s) from golang Buildinfo included in `go install`ed binaries

```golang
import fortio.org/version

var shortVersion, longVersion, fullVersion := version.FromBuildInfo()
```

Complete example in [sample/simpleMain.go](sample/simpleMain.go)
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module fortio.org/version

go 1.18
45 changes: 45 additions & 0 deletions sample/simpleMain.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package main

import (
"flag"
"fmt"
"log"
"os"

"fortio.org/version"
)

var shortVersion, longVersion, fullVersion = version.FromBuildInfo()

var programName = "fortio.org/version sample main"

func usage(msg string, args ...interface{}) {
os := flag.CommandLine.Output()
fmt.Fprintf(os, "%s %s usage:\n\t%s [flags]\nflags:\n",
programName, shortVersion, flag.CommandLine.Name())
flag.PrintDefaults()
if msg != "" {
fmt.Fprintf(os, msg, args...)
fmt.Fprintln(os)
}
}

func main() { os.Exit(Main()) }

func Main() int {
buildInfo := flag.Bool("buildinfo", false, "Show full build info and exit.")
flag.Usage = func() { usage("") }
flag.Parse()
if *buildInfo {
fmt.Print(fullVersion)
return 0
}
numArgs := len(flag.Args())
if numArgs != 0 {
usage("No argument expected, got %d.", numArgs)
return 1
}
log.Printf("%s started %s\n", programName, longVersion)
// ... do something ...
return 0
}
79 changes: 79 additions & 0 deletions version.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// Copyright 2017-2023 Fortio 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.

// Package version wraps golang BuildInfo for easy versioning of
// go binaries (installed or built through go install).
package version // import "fortio.org/version"
import (
"fmt"
"log"
"runtime"
"runtime/debug"
"strings"
)

// FromBuildInfo can be called by other programs to get their version strings (short,long and full)
// automatically added by go 1.18+ when doing `go install project@vX.Y.Z`
// and is also used for fortio itself.
func FromBuildInfo() (short, long, full string) {
return FromBuildInfoPath("")
}

func normalizeVersion(version string) string {
// skip leading v, assumes the project use `vX.Y.Z` tags.
short := strings.TrimLeft(version, "v")
// '(devel)' messes up the release-tests paths
if short == "(devel)" || short == "" {
short = "dev"
}
return short
}

func getVersion(binfo *debug.BuildInfo, path string) (short, sum, mainPath, base string) {
mainPath = binfo.Main.Path
base = normalizeVersion(binfo.Main.Version)
if path == "" || path == mainPath {
sum = binfo.Main.Sum
short = base
return
}
// try to find the right module in deps
short = path + " not found in buildinfo"
for _, m := range binfo.Deps {
if path == m.Path {
short = strings.TrimLeft(m.Version, "v")
sum = m.Sum
return
}
}
return
}

// FromBuildInfoPath returns the version of as specific module if that module isn't already the main one.
// Used by Fortio library version init to remember it's own version.
func FromBuildInfoPath(path string) (short, long, full string) {
binfo, ok := debug.ReadBuildInfo()
if !ok {
full = "fortio version module error, no build info"
log.Print("Error calling debug.ReadBuildInfo() for fortio version module")
return
}
short, sum, mainPath, base := getVersion(binfo, path)
long = short + " " + sum + " " + binfo.GoVersion + " " + runtime.GOARCH + " " + runtime.GOOS
if short != base {
long = long + " (in " + mainPath + " " + base + ")"
}
full = fmt.Sprintf("%s\n%v", long, binfo.String())
return
}

0 comments on commit cb0d3df

Please sign in to comment.