From 47069136a6c94712c064dfea6846d62ccebe09e9 Mon Sep 17 00:00:00 2001 From: Lars Schneider Date: Mon, 23 Nov 2026 12:17:57 +0000 Subject: [PATCH 1/3] Reformat doc comments with gofmt Since Go 1.19, gofmt normalizes doc comments: code blocks use a single tab and list items use " - ". Apply that formatting so that newer gofmt versions leave the files unchanged. Refs #166 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d5946d63-5054-4db7-8484-2db48414dc6e --- git/gitconfig.go | 8 ++++---- git/reference.go | 2 +- internal/refopts/filter_value.go | 10 +++++----- sizes/output.go | 8 ++++---- 4 files changed, 14 insertions(+), 14 deletions(-) diff --git a/git/gitconfig.go b/git/gitconfig.go index 76b8422..33a66ba 100644 --- a/git/gitconfig.go +++ b/git/gitconfig.go @@ -90,10 +90,10 @@ func (config *Config) FullKey(key string) string { // a component boundary (i.e., at a '.'). If yes, it returns `true` // and the part of the key after the prefix; e.g.: // -// configKeyMatchesPrefix("foo.bar", "foo") → true, "bar" -// configKeyMatchesPrefix("foo.bar", "foo.") → true, "bar" -// configKeyMatchesPrefix("foo.bar", "foo.bar") → true, "" -// configKeyMatchesPrefix("foo.bar", "foo.bar.") → false, "" +// configKeyMatchesPrefix("foo.bar", "foo") → true, "bar" +// configKeyMatchesPrefix("foo.bar", "foo.") → true, "bar" +// configKeyMatchesPrefix("foo.bar", "foo.bar") → true, "" +// configKeyMatchesPrefix("foo.bar", "foo.bar.") → false, "" func configKeyMatchesPrefix(key, prefix string) (bool, string) { if prefix == "" { return true, key diff --git a/git/reference.go b/git/reference.go index e8a1aaf..fc16371 100644 --- a/git/reference.go +++ b/git/reference.go @@ -27,7 +27,7 @@ type Reference struct { // `Reference`. It is assumed that `line` is formatted like the output // of // -// git for-each-ref --format='%(objectname) %(objecttype) %(objectsize) %(refname)' +// git for-each-ref --format='%(objectname) %(objecttype) %(objectsize) %(refname)' func ParseReference(line string) (Reference, error) { words := strings.Split(line, " ") if len(words) != 4 { diff --git a/internal/refopts/filter_value.go b/internal/refopts/filter_value.go index 5dec209..34eb932 100644 --- a/internal/refopts/filter_value.go +++ b/internal/refopts/filter_value.go @@ -74,13 +74,13 @@ func (v *filterValue) Set(s string) error { // Interpret an option argument flexibly: // -// * If it is bracketed with `/` characters, treat it as a regexp. +// - If it is bracketed with `/` characters, treat it as a regexp. // -// * If it starts with `@`, then consider it a refgroup name. That -// refgroup must already be defined. Use its filter. This construct -// is only allowed at the top level. +// - If it starts with `@`, then consider it a refgroup name. That +// refgroup must already be defined. Use its filter. This construct +// is only allowed at the top level. // -// * Otherwise treat it as a prefix. +// - Otherwise treat it as a prefix. func (v *filterValue) interpretFlexibly(s string) (git.ReferenceFilter, error) { if len(s) >= 2 && strings.HasPrefix(s, "/") && strings.HasSuffix(s, "/") { pattern := s[1 : len(s)-1] diff --git a/sizes/output.go b/sizes/output.go index 037f905..28ed130 100644 --- a/sizes/output.go +++ b/sizes/output.go @@ -279,10 +279,10 @@ func (t *Threshold) Type() string { // A `pflag.Value` that can be used as a boolean option that sets a // `Threshold` variable to a fixed value. For example, // -// pflag.Var( -// sizes.NewThresholdFlagValue(&threshold, 30), -// "critical", "only report critical statistics", -// ) +// pflag.Var( +// sizes.NewThresholdFlagValue(&threshold, 30), +// "critical", "only report critical statistics", +// ) // // adds a `--critical` flag that sets `threshold` to 30. type thresholdFlagValue struct { From 4dc713d71def806170064ad67602344597353c4c Mon Sep 17 00:00:00 2001 From: Lars Schneider Date: Mon, 23 Nov 2026 12:17:57 +0000 Subject: [PATCH 2/3] Simplify code flagged by staticcheck Newer staticcheck releases report these patterns: * ST1006: omit unused `_` receiver names * ST1023: drop the redundant type in `nameStyle`'s declaration * QF1001: apply De Morgan's law to the JSON version checks * QF1002: use a tagged switch on the file mode No behavior change. Refs #166 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d5946d63-5054-4db7-8484-2db48414dc6e --- git-sizer.go | 6 +++--- git/ref_filter.go | 12 ++++++------ sizes/graph.go | 8 ++++---- sizes/path_resolver.go | 10 +++++----- 4 files changed, 18 insertions(+), 18 deletions(-) diff --git a/git-sizer.go b/git-sizer.go index 1ef9812..c042517 100644 --- a/git-sizer.go +++ b/git-sizer.go @@ -123,7 +123,7 @@ func main() { } func mainImplementation(ctx context.Context, stdout, stderr io.Writer, args []string) error { - var nameStyle sizes.NameStyle = sizes.NameStyleFull + nameStyle := sizes.NameStyleFull var cpuprofile string var jsonOutput bool var jsonVersion int @@ -249,10 +249,10 @@ func mainImplementation(ctx context.Context, stdout, stderr io.Writer, args []st return err } jsonVersion = v - if !(jsonVersion == 1 || jsonVersion == 2) { + if jsonVersion != 1 && jsonVersion != 2 { return fmt.Errorf("JSON version (read from gitconfig) must be 1 or 2") } - } else if !(jsonVersion == 1 || jsonVersion == 2) { + } else if jsonVersion != 1 && jsonVersion != 2 { return fmt.Errorf("JSON version must be 1 or 2") } } diff --git a/git/ref_filter.go b/git/ref_filter.go index 46aff66..be30a81 100644 --- a/git/ref_filter.go +++ b/git/ref_filter.go @@ -36,14 +36,14 @@ func (f intersection) Filter(refname string) bool { // If `f1` is `nil`, it is treated as including nothing. type include struct{} -func (_ include) Combine(f1, f2 ReferenceFilter) ReferenceFilter { +func (include) Combine(f1, f2 ReferenceFilter) ReferenceFilter { if f1 == nil { return f2 } return union{f1, f2} } -func (_ include) Inverted() Combiner { +func (include) Inverted() Combiner { return Exclude } @@ -61,7 +61,7 @@ func (f union) Filter(refname string) bool { // If `f1` is `nil`, it is treated as including everything. type exclude struct{} -func (_ exclude) Combine(f1, f2 ReferenceFilter) ReferenceFilter { +func (exclude) Combine(f1, f2 ReferenceFilter) ReferenceFilter { if f1 == nil { return inverse{f2} } @@ -69,7 +69,7 @@ func (_ exclude) Combine(f1, f2 ReferenceFilter) ReferenceFilter { } -func (_ exclude) Inverted() Combiner { +func (exclude) Inverted() Combiner { return include{} } @@ -77,7 +77,7 @@ var Exclude exclude type allReferencesFilter struct{} -func (_ allReferencesFilter) Filter(_ string) bool { +func (allReferencesFilter) Filter(_ string) bool { return true } @@ -85,7 +85,7 @@ var AllReferencesFilter allReferencesFilter type noReferencesFilter struct{} -func (_ noReferencesFilter) Filter(_ string) bool { +func (noReferencesFilter) Filter(_ string) bool { return false } diff --git a/sizes/graph.go b/sizes/graph.go index 2101a00..535dc58 100644 --- a/sizes/graph.go +++ b/sizes/graph.go @@ -517,8 +517,8 @@ func (r *treeRecord) initialize(g *Graph, oid git.OID, tree *git.Tree) error { } name := entry.Name - switch { - case entry.Filemode&0o170000 == 0o40000: + switch entry.Filemode & 0o170000 { + case 0o40000: // Tree listener := func(size TreeSize) { // This listener is called when the tree pointed to by @@ -542,12 +542,12 @@ func (r *treeRecord) initialize(g *Graph, oid git.OID, tree *git.Tree) error { } r.entryCount.Increment(1) - case entry.Filemode&0o170000 == 0o160000: + case 0o160000: // Commit (i.e., submodule) r.size.addSubmodule(name) r.entryCount.Increment(1) - case entry.Filemode&0o170000 == 0o120000: + case 0o120000: // Symlink g.pathResolver.RecordTreeEntry(oid, name, entry.OID) diff --git a/sizes/path_resolver.go b/sizes/path_resolver.go index 275d19a..d66ea0b 100644 --- a/sizes/path_resolver.go +++ b/sizes/path_resolver.go @@ -58,15 +58,15 @@ func (n NullPathResolver) RequestPath(oid git.OID, objectType string) *Path { } } -func (_ NullPathResolver) ForgetPath(p *Path) {} +func (NullPathResolver) ForgetPath(p *Path) {} -func (_ NullPathResolver) RecordName(name string, oid git.OID) {} +func (NullPathResolver) RecordName(name string, oid git.OID) {} -func (_ NullPathResolver) RecordTreeEntry(oid git.OID, name string, childOID git.OID) {} +func (NullPathResolver) RecordTreeEntry(oid git.OID, name string, childOID git.OID) {} -func (_ NullPathResolver) RecordCommit(oid, tree git.OID) {} +func (NullPathResolver) RecordCommit(oid, tree git.OID) {} -func (_ NullPathResolver) RecordTag(oid git.OID, tag *git.Tag) {} +func (NullPathResolver) RecordTag(oid git.OID, tag *git.Tag) {} type InOrderPathResolver struct { lock sync.Mutex From 5d68b1efc1126e4fe18c0b064e4e65e1124c594b Mon Sep 17 00:00:00 2001 From: Lars Schneider Date: Mon, 23 Nov 2026 12:17:57 +0000 Subject: [PATCH 3/3] Require Go 1.26 and lint with golangci-lint v2 go.mod still declared `go 1.17`, a release that has been unsupported for years. Raise it to `go 1.26`, the oldest supported release. Don't go higher: gitrpcd builds the vendored git-sizer with Go 1.26. golangci-lint 1.43.0 can't lint code that requires a newer Go release, so move lint.yml to golangci-lint 2.15.0 and Go 1.27.4 and port .golangci.toml to the v2 format. v2 dropped errcheck's default `ignore = "fmt:.*"`, so exclude the `fmt.Fprint*` functions explicitly. Exclude the new noctx check for exec.Command. Fix the new findings: newer gosec flags `os.Create` with a variable path (G304), and prealloc flags `append` to a literal. Use `slices.Concat` for the latter, which needs Go 1.22 and therefore can't land before the go.mod change. Refs #166 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d5946d63-5054-4db7-8484-2db48414dc6e --- .github/workflows/lint.yml | 6 +- .golangci.toml | 457 +++++--------------------------- git-sizer.go | 2 +- git/git.go | 7 +- go.mod | 2 +- go.sum | 27 -- internal/testutils/repoutils.go | 6 +- sizes/output.go | 1 - 8 files changed, 73 insertions(+), 435 deletions(-) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 70182e0..eb56833 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -23,7 +23,7 @@ jobs: - name: Set up Go uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 with: - go-version: 1.17 + go-version: '1.27.4' - name: Check out code uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -33,7 +33,7 @@ jobs: go mod verify go mod download - LINT_VERSION=1.43.0 + LINT_VERSION=2.15.0 curl -fsSL https://github.com/golangci/golangci-lint/releases/download/v${LINT_VERSION}/golangci-lint-${LINT_VERSION}-linux-amd64.tar.gz | \ tar xz --strip-components 1 --wildcards \*/golangci-lint mkdir -p bin && mv golangci-lint bin/ @@ -54,6 +54,6 @@ jobs: assert-nothing-changed go fmt ./... assert-nothing-changed go mod tidy - bin/golangci-lint run --out-format=github-actions --timeout=3m || STATUS=$? + bin/golangci-lint run --timeout=3m || STATUS=$? exit $STATUS diff --git a/.golangci.toml b/.golangci.toml index 362ac4f..5909cee 100644 --- a/.golangci.toml +++ b/.golangci.toml @@ -1,317 +1,68 @@ -[linters] - # This file is intended to be used by your IDE to show you what linting - # issues exist in the code as you work on it. The github actions will run - # only the Tier 1 linters against the whole codebase (see - # .golangci-repo.toml, but it should be the same as the tier 1 list here). - # The tier 2 and 3 linters will run only against the files you change in a - # PR, so that you can clean up as you go. - # - # To see what issues will be present on just the PR files, you can run - # golangci-lint run --new-from-rev=origin/main +version = "2" - # format of this list: - # "lintername", # description - # reason it's enabled - enable = [ - # - # Full Repo Scan - Linters that find bugs. - # +[run] + timeout = "5m" + issues-exit-code = 1 + tests = true +[linters] + # The `standard` set adds errcheck, govet, ineffassign, staticcheck and + # unused. In v2, staticcheck includes gosimple and stylecheck, and + # unused replaces deadcode, structcheck and varcheck. + default = "standard" + enable = [ "bodyclose", # checks whether HTTP response body is closed successfully - # Forgetting to close an HTTP body can be a memory leak + "depguard", # checks if package imports are in a list of acceptable packages "durationcheck", # check for two durations multiplied together - # this is probably a rare bug, but should have basically zero false positives. - "errcheck", # finds unchecked error returns - # Checking all errors is just good dev practice. + "err113", # checks that you use errors.Is and don't define your own errors except as package variables + "errname", # checks that sentinel errors are prefixed with Err and error types are suffixed with Error "errorlint", # finds code that will cause problems with the error wrapping scheme introduced in Go 1.13 - # This ensures you use errors.Is instead of == to compare errors, to avoid bugs with wrapping. - "exportloopref", # catch bugs resulting from referencing variables on range scope - # variables initialized in for loops change with each loop, which can cause bugs. "forcetypeassert", # finds type asserts where you don't use the v, ok format - # if you do v := foo.(bar) and foo is not a bar, this will panic, and that's bad. - "gocritic", # Provides many diagnostics that check for bugs, performance and style issues. - # This is highly configurable, see the gocritic config section below. - "goerr113", # checks that you use errors.Is and don't define your own errors except as package variables. - # If you don't use errors.Is, then your code can break if someone wraps an error before they - # return it. Creating errors with errors.New("some message") makes a magic error that no one - # can handle, so either create it as a sentinel, or give it a type that people can check against. - "goimports", # check that all code is formatted with goimports - # Formating is good. goimports is better (and formats imports slightly differently than gofmt). - "gosec", # Inspects source code for security problems - # high quality linter that finds real bugs - "govet", # reports suspicious constructs like printf calls that don't have the right # of arguments - # high quality, low false positives - "ineffassign", # Detects when assignments to existing variables are not used - # this finds bugs all the time, where you assign to a value but then never use - # the assigned value due to shadowing etc. - "nolintlint", # Reports ill-formed or insufficient nolint directives - # ensures that you don't typo nolint comments. and that you justify them with why you are ignoring a linter here. - "rowserrcheck", # checks whether Err of rows is checked successfully - # finds bugs in SQL code - "sqlclosecheck", # Checks that sql.Rows and sql.Stmt are closed. - # easy and finds bugs - "typecheck", # parses and type-checks Go code - # probably unnecessary, but shouldn't hurt anything - "wastedassign", # finds wasted assignment statements. - # can find bugs where you assign something but never use it - - # - # PR Scan - less critical, but should be fixed as we go along - # - - "deadcode", # Finds unused code - # dead code can be a bug or just confusing for the next dev - "depguard", # checks if package imports are in a list of acceptable packages - # this is useful for ensuring people use the company-standard packages for logging etc. - "errname", # Checks that sentinel errors are prefixed with the Err and error types are suffixed with the Error. - # This is standard practice and makes it easy to find error types and sentinels in the code. - "gochecknoinits", # Checks that no init functions are present in Go code - # init is bad, and is almost never necessary, nor is it a good idea. - "godot", # Check if comments end in a period - # this is a recommended Go style, and not only makes your doc comments look more - # professional, it ensures that you don't stop a comment in the middle and forget - # to write the end of it. - #"godox", # detects use of FIXME, TODO and other comment keywords - # These should be issues in an issue tracker, not comments in the code. - "gosimple", # tells you where you can simplify your code - # simple is good + "gochecknoinits", # checks that no init functions are present in Go code + "gocritic", # provides many diagnostics that check for bugs, performance and style issues + "godot", # check if comments end in a period + "gosec", # inspects source code for security problems "makezero", # checks that you don't accidentally make a slice w/ nonzero length and then append to it - # this can cause bugs where you make a slice of length 5 and then append 5 items to it, - # giving you a length of 10 where the first 5 are all zero values. - "misspell", # Finds commonly misspelled English words in comments - # we all suck at spelling and tpying - "nakedret", # Finds naked returns in functions greater than a specified function length - # naked returns are evil - #"nestif", # Reports deeply nested if statements - # deeply nested ifs are hard to read - "nilerr", # Finds the code that returns nil even if it checks that the error is not nil. - # finds fairly common bug - "noctx", # noctx finds sending http request without context.Context - # you should always use context so we can cancel external requests - "prealloc", # Finds slice declarations that could potentially be preallocated - # this can save some memory and copying, otherwise append guesses how big to make slices and may need to - # copy all items in a slice to a bigger one. + "misspell", # finds commonly misspelled English words in comments + "nakedret", # finds naked returns in functions greater than a specified function length + "nilerr", # finds the code that returns nil even if it checks that the error is not nil + "noctx", # finds sending http request without context.Context + "nolintlint", # reports ill-formed or insufficient nolint directives + "prealloc", # finds slice declarations that could potentially be preallocated "predeclared", # find code that shadows one of Go's predeclared identifiers - # you can make a variable called "true", but it's a bad idea. - #"revive", # finds common style mistakes - # style and other mistakes that you really should listen to. - "staticcheck", # go vet on steroids, applying a ton of static analysis checks - # encompasses many linters in one, good stuff - "structcheck", # Finds unused struct fields - # can find bugs or trim unused fields to save memory - #"tparallel", # tparallel detects inappropriate usage of t.Parallel() - # likely a rare problem, but should have low false positives - "unconvert", # Remove unnecessary type conversions - # can save a little memory, unlikely to have false positives - "unused", # Checks for unused constants, variables, functions and types - # may have false positives, should watch this one - "varcheck", # Finds unused global variables and constants - # may have false positives, should watch this one - ] - - # we don't bother putting anything in disable, since we manually enable each linter. - # See the bottom of the file for disabled linters. - disable = [] - - -[run] - # options for analysis running - # Increase timeout from default 1m, first pre-cache run can take a bit in CI/CD - timeout = "5m" - - # default concurrency is the available CPU number - # concurrency = 4 - - # exit code when at least one issue was found, default is 1 - issues-exit-code = 1 - - # include test files or not, default is true - tests = true - - # list of build tags, all linters use it. Default is empty list. - build-tags = [] - - # which dirs to skip: issues from them won't be reported; - # can use regexp here: generated.*, regexp is applied on full path; - # default value is empty list, but default dirs are skipped independently - # from this option's value (see skip-dirs-use-default). - # "/" will be replaced by current OS file path separator to properly work - # on Windows. - skip-dirs = [] - - # default is true. Enables skipping of directories: - # vendor$, third_party$, testdata$, examples$, Godeps$, builtin$ - skip-dirs-use-default = true - - # which files to skip: they will be analyzed, but issues from them - # won't be reported. Default value is empty list, but there is - # no need to include all autogenerated files, we confidently recognize - # autogenerated files. If it's not please let us know. - # "/" will be replaced by current OS file path separator to properly work - # on Windows. - skip-files = [] - - # by default isn't set. If set we pass it to "go list -mod={option}". From "go help modules": - # If invoked with -mod=readonly, the go command is disallowed from the implicit - # automatic updating of go.mod described above. Instead, it fails when any changes - # to go.mod are needed. This setting is most useful to check that go.mod does - # not need updates, such as in a continuous integration and testing system. - # If invoked with -mod=vendor, the go command assumes that the vendor - # directory holds the correct copies of dependencies and ignores - # the dependency descriptions in go.mod. - modules-download-mode = "" - - # Allow multiple parallel golangci-lint instances running. - # If false (default) - golangci-lint acquires file lock on start. - allow-parallel-runners = false - - -[output] - # colored-line-number|line-number|json|tab|checkstyle|code-climate|junit-xml|github-actions - # default is "colored-line-number" - format = "colored-line-number" - - # print lines of code with issue, default is true - print-issued-lines = true - - # print linter name in the end of issue text, default is true - print-linter-name = true - - # make issues output unique by line, default is true - uniq-by-line = true - - # add a prefix to the output file references; default is no prefix - path-prefix = "" - - # sorts results by: filepath, line and column - sort-results = true - - - -# options to enable differentiating between error and warning severities -[severity] - # GitHub Actions annotations support error and warning only: - # https://docs.github.com/en/free-pro-team@latest/actions/reference/workflow-commands-for-github-actions#setting-an-error-message - default-severity = "error" - - # If set to true severity-rules regular expressions become case sensitive. - # The default value is false. - case-sensitive = false - - # Default value is empty list. - # When a list of severity rules are provided, severity information will be added to lint - # issues. Severity rules have the same filtering capability as exclude rules except you - # are allowed to specify one matcher per severity rule. - # Only affects out formats that support setting severity information. - # [[severity.rules]] - # linters = [ - # "revive", - # ] - # severity = "warning" - -[issues] - # List of regexps of issue texts to exclude, empty list by default. - # Please document every exception here so we know what we're suppressing and why. - exclude = [ - # err113 doesn't like it when people use errors.New("abc"). - # That's kinda valid but also kind of a PITA if you don't actually want - # to define static errors everywhere, and no one actually depends on them. - ".*do not define dynamic errors, use wrapped static errors instead.*" - ] - - # 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 - - # The default value is false. If set to true exclude and exclude-rules - # regular expressions become case sensitive. - # exclude-case-sensitive = false - - # This flag suppresses lint issues from several linters, overriding any other configuration you have set. - # It defaults to true. - # NEVER remove this configuration. If you want to suppress something, do so explicitly elsewhere. - exclude-use-default = false - - # The list of ids of default excludes to include or disable. By default it's empty. - # We shouldn't ever need this, since we turn off default excludes. - include = [] - - # Show only new issues: if there are unstaged changes or untracked files, - # only those changes are analyzed, else only changes in HEAD~ are analyzed. - # It's a super-useful option for integration of golangci-lint into existing - # large codebase. It's not practical to fix all existing issues at the moment - # of integration: much better don't allow issues in new code. - # Default is false. - new = false - - # Show only new issues created in git patch with set file path. - # new-from-patch = "path/to/patch/file" - - # Show only new issues created after git revision `REV` - # new-from-rev = "REV" - - # Fix found issues (if it's supported by the linter). Default is false. - fix = false - - # reduce noise in some linters that don't necessarily need to be run in tests - [[issues.exclude-rules]] - path = "_test\\.go" - linters = ["errcheck", "gosec", "gocyclo", "noctx", "govet"] - -# -# Specific Linter Settings -# - -[linters-settings.depguard] - # ban some modules with replacements - list-type = "blacklist" - include-go-root = true - packages = [ - # we shouldn't use pkg/error anymore - "github.com/pkg/error", + "rowserrcheck", # checks whether Err of rows is checked successfully + "sqlclosecheck", # checks that sql.Rows and sql.Stmt are closed + "unconvert", # remove unnecessary type conversions + "wastedassign", # finds wasted assignment statements ] - [[linters-settings.depguard.packages-with-error-message]] - "github.com/pkg/error" = "Please use stdlib errors module" +[linters.settings.depguard.rules.main] + [[linters.settings.depguard.rules.main.deny]] + pkg = "github.com/pkg/error" + desc = "Please use stdlib errors module" -[linters-settings.errcheck] - # report about not checking of errors in type assertions: `a := b.(MyStruct)`; - # default is false: such cases aren't reported by default. +[linters.settings.errcheck] check-type-assertions = true - - # report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`; - # default is false: such cases aren't reported by default. check-blank = false + # golangci-lint v1 ignored all of package `fmt` by default. + exclude-functions = [ + "fmt.Fprint", + "fmt.Fprintf", + "fmt.Fprintln", + ] - # path to a file containing a list of functions to exclude from checking - # see https://github.com/kisielk/errcheck#excluding-functions for details - exclude = "" - - # list of functions to exclude from checking, where each entry is a single function to exclude. - # see https://github.com/kisielk/errcheck#excluding-functions for details - exclude-functions = [] - -[linters-settings.errorlint] - # Check whether fmt.Errorf uses the %w verb for formatting errors. See the readme for caveats +[linters.settings.errorlint] errorf = true - # Check for plain type assertions and type switches asserts = false - # Check for plain error comparisons comparison = false -[linters-settings.gocritic] - # Enable multiple checks by tags, run `GL_DEBUG=gocritic golangci-lint run` to see all tags and checks. - # Empty list by default. See https://github.com/go-critic/go-critic#usage -> section "Tags". +[linters.settings.gocritic] enabled-tags = [ "diagnostic", "performance", "style", ] disabled-checks = [ - # import shadow warns if a variable shadow the name of an imported package. - # kind of noisy, doesn't actually hurt anything, just may be momentarily confusing. "importShadow", "preferStringWriter", "paramTypeCombine", @@ -320,124 +71,40 @@ "elseif", "whyNoLint", ] - - # HugeParam: warn if passing huge parameters by value; consider passing pointers instead. - [linters-settings.gocritic.settings.hugeParam] - # increase threshold from default (80 bytes) to 256 bytes. + [linters.settings.gocritic.settings.hugeParam] sizeThreshold = 256 +[linters.settings.govet] + enable = ["httpresponse"] - - -[linters-settings.goimports] - # Goimports checks whether code was formatted with goimports. - # uncomment if we want to enforce having GitHub-owned packages sorted into a separate section - #local-prefixes = "github.com/github/" - -[linters-settings.govet] - enable = [ "httpresponse" ] - -[linters-settings.gosec] +[linters.settings.gosec] excludes = [ "G301", # Expect directory permissions to be 0750 or less. See umask. "G307", # deferring methods with errors. This duplicates errcheck, and I don't want to have to use two nolints. ] - -[linters-settings.nolintlint] - # adds some protections around nolint directives - - # Enable to ensure that nolint directives are all used. Default is true. +[linters.settings.nolintlint] allow-unused = false - # Disable to ensure that nolint directives don't have a leading space. Default is true. - allow-leading-space = false - # Exclude following linters from requiring an explanation. Default is []. - allow-no-explanation = [] - # Enable to require an explanation of nonzero length after each nolint directive. Default is false. require-explanation = false - # Enable to require nolint directives to mention the specific linter being suppressed. Default is false. require-specific = true +[[linters.exclusions.rules]] + # The noctx `exec.Command` check is new in golangci-lint v2. Passing a + # context to all git commands is a separate change. + linters = ["noctx"] + text = "os/exec.Command must not be called" +[[linters.exclusions.rules]] + path = "_test\\.go" + linters = ["errcheck", "gosec", "gocyclo", "noctx", "govet"] +[[linters.exclusions.rules]] + path = "\\.go$" + text = ".*do not define dynamic errors, use wrapped static errors instead.*" -# List of linters supported by golangci-lint that we intentionally do not use. -# Intentionally formatted the same as the "enabled" list, so you can just move one -# up to that list to enable it. -# list is in the form - # "name", # description - # reason to disable - +[issues] + max-issues-per-linter = 0 + max-same-issues = 0 - # "asciicheck", # checks that your code does not contain non-ASCII identifiers - # Honestly not sure why anyone cares? - # "cyclop", # checks function and package cyclomatic complexity - # Too hard to know when you trip over this, and I feel like it needs a human - # to understand if a function is too complex. - # "dogsled", # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) - # This doesn't seem to be a common problem, nor a source of bugs. It would be - # better to have a linter that just tells you not to return 4 things in the - # first place. - # "dupl", # Tool for code clone detection - # This feels too likely to have high false positives on trivial code, and miss - # more complicated duplicates. - # "exhaustive", # checks exhaustiveness of enum switch statements - # This tends to hit a lot of false positives, and can lead to a lot of nolint statements. - # Definitely could be useful for specific repos of focused libraries where you know you - # update enums a lot, and want to make sure your switch statements stay up to date. - # "exhaustivestruct", # Checks if all struct's fields are initialized - # This is generally a feature, not a bug. Requiring a //nolint whenever you partially - # initialize a struct would be pretty annoying. - # "forbidigo", # Can be configured to forbids specific identifiers, like fmt.Printf, for example. - # This can actually be really useful, but needs a deep understanding of patterns - # we want devs to avoid in our specific repos. Definitely look into it if you have - # a list of "don't use XYZ" items. - # "funlen", # Tool for detection of long functions - # We could maybe put this in with a pretty big size limit, but it feels like it would be - # of limited benefit and cause grumbling. - # "gci", # control golang package import order and make it always deterministic - # I haven't really had a problem with this, when using goimports, so I'm not sure it's useful. - # "gochecknoglobals", # check that no global variables exist - # this is actually good to have on, but I'm afraid it would cause more heartburn than good. - # "gocognit", # Computes and checks the cognitive complexity of functions - # Too hard to know when you trip over this, and I feel like it needs a human - # to understand if a function is too complex. - # "goconst", # Finds repeated strings that could be replaced by a constant - # magic strings are bad, but I feel like this could reduce adoption of the linter. - # "gofmt", # checks whether code was gofmt-ed. - # use goimports instead, they have slightly different formatting. - # "gofumpt", # checks whether code is gofumpt-ed - # use goimports instead, they have slightly different formatting. - # "goheader", # checks if file header matches a pattern - # useful for companies that mandate a copyright header on every file. That's not github. - # "golint", # unmaintained - # "gomnd", # an analyzer to detect magic numbers - # just too noisy - # "ifshort", # makes sure you use if err := foo(); err != nil - # this is really more personal preference, and sometimes can hinder readability. - # "importas", # enforces consistent import aliases - # this is kind of a special case for avoiding import collisions, and not really needed for us. - # "interfacer", # unmaintined - # "lll" # reports long lines - # duplicated by other checks - # "nlreturn", # nlreturn checks for a new line before return and branch statements to increase code clarity - # I'm not a monster, newline if you like, or not. - # "paralleltest", # paralleltest detects missing usage of t.Parallel() method in your Go test - # parallel tests are good, but packages are already run in parallel, so it's not a huge gain. - # "promlinter", # Check Prometheus metrics naming via promlint - # enable if you use prometheus - # "scopelint", # unmaintained - # "tagliatelle", # Checks that struct tags match a certain format (camelcase, snakecase etc) - # likely to cause a lot of false positives if you're making tags for other people's APIs - # "testpackage", # makes you use a separate _test package - # I actually think this is a bad idea in general, and I would want a linter that does the opposite. - # "thelper", # detects golang test helpers without t.Helper() - # t.Helper is sometimes useful and sometimes not. - # "unparam", # Reports unused function parameters - # seems likely to have false positives - # "whitespace", # finds extra newlines at the beginning of functions and if statements - # I like this, but I feel like it would be too nitpicky for most people - # "wrapcheck", # Checks that errors returned from external packages are wrapped - # I mean, yeah, but you don't *always* need to wrap, that gets excesssive. - # "wsl", # Whitespace Linter - Forces you to use empty lines! - # meh, I'm not that much of a control freak +[formatters] + enable = ["goimports"] diff --git a/git-sizer.go b/git-sizer.go index c042517..9dd2bc3 100644 --- a/git-sizer.go +++ b/git-sizer.go @@ -219,7 +219,7 @@ func mainImplementation(ctx context.Context, stdout, stderr io.Writer, args []st } if cpuprofile != "" { - f, err := os.Create(cpuprofile) + f, err := os.Create(cpuprofile) //nolint:gosec // The user chooses the path. if err != nil { return fmt.Errorf("couldn't set up cpuprofile file: %w", err) } diff --git a/git/git.go b/git/git.go index ef3cbc6..2e0af79 100644 --- a/git/git.go +++ b/git/git.go @@ -8,6 +8,7 @@ import ( "os" "os/exec" "path/filepath" + "slices" ) // ObjectType represents the type of a Git object ("blob", "tree", @@ -133,7 +134,7 @@ func (repo *Repository) IsFull() (bool, error) { } func (repo *Repository) GitCommand(callerArgs ...string) *exec.Cmd { - args := []string{ + args := slices.Concat([]string{ // Disable replace references when running our commands: "--no-replace-objects", @@ -141,9 +142,7 @@ func (repo *Repository) GitCommand(callerArgs ...string) *exec.Cmd { // want to set the grafts file to `/dev/null` below (to // disable grafts even where they are supported): "-c", "advice.graftFileDeprecated=false", - } - - args = append(args, callerArgs...) + }, callerArgs) //nolint:gosec // `gitBin` is chosen carefully, and the rest of // the args have been checked. diff --git a/go.mod b/go.mod index 9db294d..7aa5736 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/github/git-sizer -go 1.17 +go 1.26 require ( github.com/cli/safeexec v1.0.0 diff --git a/go.sum b/go.sum index 5c5d0a9..99a98ee 100644 --- a/go.sum +++ b/go.sum @@ -1,6 +1,5 @@ github.com/cli/safeexec v1.0.0 h1:0VngyaIyqACHdcMNWfo6+KdUYnqEr2Sg+bSP1pdF+dI= github.com/cli/safeexec v1.0.0/go.mod h1:Z/D4tTN8Vs5gXYHDCbaM1S/anmEDnJb1iW0+EJ5zx3Q= -github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -23,36 +22,10 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= go.uber.org/goleak v1.2.0 h1:xqgm/S+aQvhWFTtR0XK3Jvg7z8kGV8P4X14IzwN3Eqk= go.uber.org/goleak v1.2.0/go.mod h1:XJYK+MuIchqpmGmUSAzotztawfKvYLUIgg7guXrwVUo= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= -golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= -golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/internal/testutils/repoutils.go b/internal/testutils/repoutils.go index e14e487..be26fb1 100644 --- a/internal/testutils/repoutils.go +++ b/internal/testutils/repoutils.go @@ -7,6 +7,7 @@ import ( "os" "os/exec" "path/filepath" + "slices" "strings" "testing" "time" @@ -150,8 +151,7 @@ func CleanGitEnv() []string { func (repo *TestRepo) GitCommand(t *testing.T, args ...string) *exec.Cmd { t.Helper() - gitArgs := []string{"-C", repo.Path} - gitArgs = append(gitArgs, args...) + gitArgs := slices.Concat([]string{"-C", repo.Path}, args) //nolint:gosec // The args all come from the test code. cmd := exec.Command("git", gitArgs...) @@ -229,7 +229,7 @@ func (repo *TestRepo) AddFile(t *testing.T, relativePath, contents string) { } filename := filepath.Join(repo.Path, relativePath) - f, err := os.Create(filename) + f, err := os.Create(filename) //nolint:gosec // The path comes from the test code. require.NoErrorf(t, err, "creating file %q", filename) _, err = f.WriteString(contents) require.NoErrorf(t, err, "writing to file %q", filename) diff --git a/sizes/output.go b/sizes/output.go index 28ed130..87ec9bd 100644 --- a/sizes/output.go +++ b/sizes/output.go @@ -470,7 +470,6 @@ func (s *HistorySize) contents(refGroups []RefGroup) tableContents { metric := counts.Metric binary := counts.Binary - //nolint:prealloc // The length is not known in advance. var rgis []tableContents for _, rg := range refGroups { if rg.Symbol == "" {