Skip to content

feat: add golicenser linter #5751

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions .golangci.next.reference.yml
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ linters:
- godot
- godox
- goheader
- golicenser
- gomoddirectives
- gomodguard
- goprintffuncname
Expand Down Expand Up @@ -165,6 +166,7 @@ linters:
- godot
- godox
- goheader
- golicenser
- gomoddirectives
- gomodguard
- goprintffuncname
Expand Down Expand Up @@ -1279,6 +1281,79 @@ linters:
# Default: ""
template-path: /path/to/my/template.tmpl

golicenser:
# Regexp used to detect license/copyright headers.
# This will be used to detect the existence of a copyright header in a file.
# If the first comment in a Go source file does not match this, then a license header will be generated.
# For the license header to be updated, it must also match the header matcher.
# Default: "(?i)copyright"
copyright-header-matcher: "(?i)copyright"

header:
# The project author name used in the `author` template variable.
# Required value.
author: "My Name"
# Regexp used to match the project author (`author` variable).
# Default: regexp-escaped value of `author`.
author-regexp: "(My Name|Your Name)"
# Style of comment to use in license headers.
# More information: https://github.com/joshuasing/golicenser#comment-styles
# Valid options are: `line`, `block`.
# Default: "line"
comment-style: "line"
# License header template (using Go text/template: https://pkg.go.dev/text/template).
# More information: https://github.com/joshuasing/golicenser#templates
# Built-in variables:
# - `year`: Copyright year(s) for the file. The format is configurable with `year-mode`.
# - `author`: The copyright author (provided by `author`).
# - `filename`: The current filename.
# Custom variables can be provided in `variables` below.
# Required value.
template: |-
Copyright (c) {{.year}} {{.author}}. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
# Path to file containing license header template.
# This is an alternative to `template`, and `template` will take priority if set.
# By default, if a path is relative, it is relative to the directory where the golangci-lint command is executed.
# The placeholder '${base-path}' is substituted with a path relative to the mode defined with `run.relative-path-mode`.
# The placeholder '${config-path}' is substituted with a path relative to the configuration file.
# Default: ""
template-path: /path/to/my/template.tmpl
# License header match regexp.
# More information: https://github.com/joshuasing/golicenser#matcher
# Matched headers will be updated or replaced by the header template.
# Default: regexp-escaped value of `template`.
matcher: |-
Copyright \(c\) {{.year}} {{.author}}.(\s*All rights reserved.)?
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
# Enable to regexp-escape the header matcher.
# Useful if you want to provide a license header instead of regexp expression.
# Default: false
matcher-escape: false
# Variables to provide to the header template.
# Due to a limitation of Viper, the configuration loader used by golangci-lint, variable names will always be
# provided as lowercase to the template.
# Default: {}
variables:
email:
regexp: "(.+)@mycompany\\.com"
project-name:
value: "My project"
# Copyright year formatting mode.
# More information: https://github.com/joshuasing/golicenser#year-modes
# Available year modes are:
# - `preserve`: Current year in new headers, existing year in updated headers.
# - `preserve-this-year-range`: Current year in new headers, existing year to current year in updated headers.
# - `preserve-modified-range`: Last modified year in new headers, existing year to last modified year in updated headers.
# - `this-year`: Current year.
# - `last-modified`: File last modified year.
# - `git-range`: Git history creation year to last modified year (e.g. `2022-2025`)
# - `git-modified-list`: List of all modified years from Git history (e.g. `2022, 2024, 2025`)
# Default: "preserve"
year-mode: "git-range"

gomoddirectives:
# Allow local `replace` directives.
# Default: false
Expand Down
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ require (
github.com/jgautheron/goconst v1.8.1
github.com/jingyugao/rowserrcheck v1.1.1
github.com/jjti/go-spancheck v0.6.4
github.com/joshuasing/golicenser v0.3.1
github.com/julz/importas v0.2.0
github.com/karamaru-alpha/copyloopvar v1.2.1
github.com/kisielk/errcheck v1.9.0
Expand Down Expand Up @@ -141,6 +142,7 @@ require (
github.com/Masterminds/semver/v3 v3.3.1 // indirect
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/bmatcuk/doublestar/v4 v4.8.1 // indirect
github.com/ccojocar/zxcvbn-go v1.0.2 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect
Expand Down
4 changes: 4 additions & 0 deletions go.sum

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

94 changes: 94 additions & 0 deletions jsonschema/golangci.next.jsonschema.json
Original file line number Diff line number Diff line change
Expand Up @@ -757,6 +757,7 @@
"godox",
"err113",
"goheader",
"golicenser",
"gomoddirectives",
"gomodguard",
"goprintffuncname",
Expand Down Expand Up @@ -1935,6 +1936,96 @@
{ "required": ["template-path"] }
]
},
"golicenserSettings": {
"type": "object",
"additionalProperties": false,
"properties": {
"copyright-header-matcher": {
"description": "Regexp used to detect license/copyright headers. This is used to detect the existence of any copyright header in a file.",
"type": "string",
"default": "(?i)copyright"
},
"header": {
"description": "License header settings.",
"type": "object",
"properties": {
"template": {
"description": "License header template (using Go text/template)\nhttps://github.com/joshuasing/golicenser#templates",
"type": "string",
"examples": [
"Copyright (c) {{.year}} {{.author}}. All rights reserved.\nUse of this source code is governed by a BSD-style\nlicense that can be found in the LICENSE file."
]
},
"template-path": {
"description": "Path to file containing license header template",
"type": "string",
"examples": [
"license.txt",
"license-header.txt"
]
},
"matcher": {
"description": "License header matcher regexp\nhttps://github.com/joshuasing/golicenser#matcher",
"type": "string",
"examples": [
"Copyright \\(c\\) {{.year}} {{.author}}(.|\\s<[email protected]>)"
]
},
"matcher-escape": {
"description": "Enable to regexp-escape the header matcher. Useful for providing a license template instead of regexp.",
"type": "boolean",
"default": false
},
"author": {
"description": "Project author name (used in the `author` template variable).",
"type": "string"
},
"author-regexp": {
"description": "Regexp used to match the project author (`author` variable)",
"type": "string"
},
"variables": {
"description": "Custom variables to provide to the header template\nNote: Due to a limitation of Viper, the configuration loader used by golangci-lint, variable names will always be provided as lowercase to the template.",
"type": "object",
"additionalProperties": false,
"patternProperties": {
"^[a-z\\-]+$": {
"type": "object",
"additionalProperties": false,
"properties": {
"value": {
"description": "Variable value",
"type": "string"
},
"regexp": {
"description": "Variable matcher regexp",
"type": "string"
}
}
}
}
},
"year-mode": {
"description": "Copyright year formatting mode.\nhttps://github.com/joshuasing/golicenser#year-modes",
"type": "string",
"enum": ["preserve", "preserve-this-year-range", "preserve-modified-range", "this-year", "last-modified", "git-range", "git-modified-list"],
"default": "preserve"
},
"comment-style": {
"description": "Style of comment to use in license headers.\nhttps://github.com/joshuasing/golicenser#comment-styles",
"type": "string",
"enum": ["line", "block"],
"default": "line"
}
},
"oneOf": [
{ "required": ["template", "author"] },
{ "required": ["template-path", "author"] }
]
}
},
"required": ["header"]
},
"goimportsSettings": {
"type": "object",
"additionalProperties": false,
Expand Down Expand Up @@ -4399,6 +4490,9 @@
"goheader": {
"$ref": "#/definitions/settings/definitions/goheaderSettings"
},
"golicenser": {
"$ref": "#/definitions/settings/definitions/golicenserSettings"
},
"gomoddirectives": {
"$ref": "#/definitions/settings/definitions/gomoddirectivesSettings"
},
Expand Down
23 changes: 23 additions & 0 deletions pkg/config/linters_settings.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,7 @@ type LintersSettings struct {
Godot GodotSettings `mapstructure:"godot"`
Godox GodoxSettings `mapstructure:"godox"`
Goheader GoHeaderSettings `mapstructure:"goheader"`
Golicenser GoLicenserSettings `mapstructure:"golicenser"`
GoModDirectives GoModDirectivesSettings `mapstructure:"gomoddirectives"`
Gomodguard GoModGuardSettings `mapstructure:"gomodguard"`
Gosec GoSecSettings `mapstructure:"gosec"`
Expand Down Expand Up @@ -510,6 +511,28 @@ type GoHeaderSettings struct {
TemplatePath string `mapstructure:"template-path"`
}

type GoLicenserSettings struct {
Header GoLicenserHeaderSettings `mapstructure:"header"`
CopyrightHeaderMatcher string `mapstructure:"copyright-header-matcher"`
}

type GoLicenserHeaderSettings struct {
Template string `mapstructure:"template"`
TemplatePath string `mapstructure:"template-path"`
Matcher string `mapstructure:"matcher"`
MatcherEscape bool `mapstructure:"matcher-escape"`
Author string `mapstructure:"author"`
AuthorRegexp string `mapstructure:"author-regexp"`
Variables map[string]GoLicenserVar `mapstructure:"variables"`
YearMode string `mapstructure:"year-mode"`
CommentStyle string `mapstructure:"comment-style"`
}

type GoLicenserVar struct {
Value string `mapstructure:"value"`
Regexp string `mapstructure:"regexp"`
}

type GoModDirectivesSettings struct {
ReplaceAllowList []string `mapstructure:"replace-allow-list"`
ReplaceLocal bool `mapstructure:"replace-local"`
Expand Down
94 changes: 94 additions & 0 deletions pkg/golinters/golicenser/golicenser.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package golicenser

import (
"fmt"
"os"
"strings"

"github.com/joshuasing/golicenser"
"golang.org/x/tools/go/analysis"

"github.com/golangci/golangci-lint/v2/pkg/config"
"github.com/golangci/golangci-lint/v2/pkg/goanalysis"
"github.com/golangci/golangci-lint/v2/pkg/golinters/internal"
)

const linterName = "golicenser"

func New(settings *config.GoLicenserSettings, replacer *strings.Replacer) *goanalysis.Linter {
conf, err := createConfig(settings, replacer)
if err != nil {
internal.LinterLogger.Fatalf("%s: parse year mode: %v", linterName, err)
}

analyzer, err := golicenser.NewAnalyzer(conf)
if err != nil {
internal.LinterLogger.Fatalf("%s: create analyzer: %v", linterName, err)
}

return goanalysis.NewLinter(
linterName,
"Powerful license header linter",
[]*analysis.Analyzer{analyzer},
nil,
).WithLoadMode(goanalysis.LoadModeSyntax)
}

func createConfig(settings *config.GoLicenserSettings, replacer *strings.Replacer) (golicenser.Config, error) {
if settings == nil {
return golicenser.Config{}, nil
}

header := golicenser.HeaderOpts{
Matcher: settings.Header.Matcher,
MatcherEscape: settings.Header.MatcherEscape,
Author: settings.Header.Author,
AuthorRegexp: settings.Header.AuthorRegexp,
Template: settings.Header.Template,
Variables: make(map[string]*golicenser.Var, len(settings.Header.Variables)),
}

// Template from config takes priority over template from 'template-path'.
if header.Template == "" && settings.Header.TemplatePath != "" {
b, err := os.ReadFile(replacer.Replace(settings.Header.TemplatePath))
if err != nil {
return golicenser.Config{}, fmt.Errorf("read the template file: %w", err)
}

// Use template from a file (trim newline from the end of file)
header.Template = strings.TrimSuffix(strings.TrimSuffix(string(b), "\n"), "\r")
}

var err error
if settings.Header.YearMode != "" {
header.YearMode, err = golicenser.ParseYearMode(settings.Header.YearMode)
if err != nil {
return golicenser.Config{}, fmt.Errorf("parse year mode: %w", err)
}
}

if settings.Header.CommentStyle != "" {
header.CommentStyle, err = golicenser.ParseCommentStyle(settings.Header.CommentStyle)
if err != nil {
return golicenser.Config{}, fmt.Errorf("parse comment style: %w", err)
}
}

for k, v := range settings.Header.Variables {
header.Variables[k] = &golicenser.Var{
Value: v.Value,
Regexp: v.Regexp,
}
}

return golicenser.Config{
Header: header,
CopyrightHeaderMatcher: settings.CopyrightHeaderMatcher,

// NOTE(ldez): not wanted for now.
// And an empty slice is used because of a wrong default inside the linter.
Exclude: []string{},
// NOTE(ldez): golangci-lint already handles concurrency.
MaxConcurrent: 1,
}, nil
}
19 changes: 19 additions & 0 deletions pkg/golinters/golicenser/golicenser_integration_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package golicenser

import (
"testing"

"github.com/golangci/golangci-lint/v2/test/testshared/integration"
)

func TestFromTestdata(t *testing.T) {
integration.RunTestdata(t)
}

func TestFix(t *testing.T) {
integration.RunFix(t)
}

func TestFixPathPrefix(t *testing.T) {
integration.RunFixPathPrefix(t)
}
Loading