Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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

Draft
joshuasing wants to merge 3 commits into golangci:main
base: main
Choose a base branch
Loading
from joshuasing:joshua/golicenser
Draft
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
review
  • Loading branch information
ldez committed Apr 19, 2025
commit a314c0edeb8b50159bb1b65d21a0483eca9d2f44
61 changes: 21 additions & 40 deletions .golangci.next.reference.yml
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -1282,7 +1282,25 @@ linters:
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:
Expand All @@ -1295,15 +1313,13 @@ linters:
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: "${config-path}/license.txt"

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.
Expand All @@ -1312,30 +1328,19 @@ linters:
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

# 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)"

# 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:
value: "me@mycompany.com"
regexp: "(.+)@mycompany\\.com"
projectname: "My project"

project-name:
value: "My project"
# Copyright year formatting mode.
# More information: https://github.com/joshuasing/golicenser#year-modes
# Available year modes are:
Expand All @@ -1349,30 +1354,6 @@ linters:
# Default: "preserve"
year-mode: "git-range"

# 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"

# List of file globs (doublestar) or regexps to match excluded paths.
# To use regexp, prefix the string with `r!`.
# Default: ["**/testdata/**"]
exclude:
- "**/testdata/**"
- "r!(.+)_test\\.go"

# Maximum number of Go routines to use when analysing files.
# Default: 2 * the number of logical CPUs usable by the current process.
max-concurrent: 100

# 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"

gomoddirectives:
# Allow local `replace` directives.
# Default: false
Expand Down
52 changes: 15 additions & 37 deletions jsonschema/golangci.next.jsonschema.json
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -1940,6 +1940,11 @@
"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",
Expand Down Expand Up @@ -1982,28 +1987,21 @@
"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": {
"^.+$": {
"oneOf": [
{
"^[a-z\\-]+$": {
"type": "object",
"additionalProperties": false,
"properties": {
"value": {
"description": "Variable value",
"type": "string"
},
{
"type": "object",
"properties": {
"value": {
"description": "Variable value",
"type": "string"
},
"regexp": {
"description": "Variable matcher regexp",
"type": "string"
}
},
"required": ["value"]
"regexp": {
"description": "Variable matcher regexp",
"type": "string"
}
]
}
}
}
},
Expand All @@ -2024,26 +2022,6 @@
{ "required": ["template", "author"] },
{ "required": ["template-path", "author"] }
]
},
"exclude": {
"description": "List of file globs (doublestar) or regexps to match excluded paths. To use regexp, prefix the string with `r!`.",
"type": "array",
"items": {
"type": "string"
},
"default": [
"**/testdata/**"
]
},
"max-concurrent": {
"description": "Maximum number of Go routines to use when analysing files.",
"type": "integer",
"minimum": 0
},
"copyright-header-regexp": {
"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"
}
},
"required": ["header"]
Expand Down
20 changes: 9 additions & 11 deletions pkg/config/linters_settings.go
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -513,21 +513,19 @@ type GoHeaderSettings struct {

type GoLicenserSettings struct {
Header GoLicenserHeaderSettings `mapstructure:"header"`
Exclude []string `mapstructure:"exclude"`
MaxConcurrent int `mapstructure:"max-concurrent"`
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]any `mapstructure:"variables"`
YearMode string `mapstructure:"year-mode"`
CommentStyle string `mapstructure:"comment-style"`
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 {
Expand Down
138 changes: 65 additions & 73 deletions pkg/golinters/golicenser/golicenser.go
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package golicenser

import (
"fmt"
"os"
"strings"

"github.com/go-viper/mapstructure/v2"
"github.com/joshuasing/golicenser"
"golang.org/x/tools/go/analysis"

Expand All @@ -13,79 +13,12 @@ import (
"github.com/golangci/golangci-lint/v2/pkg/golinters/internal"
)

const (
linterName = "golicenser"
linterDesc = "Powerful license header linter"
)
const linterName = "golicenser"

func New(settings *config.GoLicenserSettings, replacer *strings.Replacer) *goanalysis.Linter {
var conf golicenser.Config
if settings != nil {
// Template from config takes priority over template from template-path.
template := settings.Header.Template
if template == "" && settings.Header.TemplatePath != "" {
b, err := os.ReadFile(replacer.Replace(settings.Header.TemplatePath))
if err != nil {
internal.LinterLogger.Fatalf("%s: read template file: %v", linterName, err)
}
// Use template from file (trim newline from end of file)
template = strings.TrimSuffix(string(b), "\n")
}

var err error
var yearMode golicenser.YearMode
if ym := settings.Header.YearMode; ym != "" {
yearMode, err = golicenser.ParseYearMode(ym)
if err != nil {
internal.LinterLogger.Fatalf("%s: parse year mode: %v", linterName, err)
}
}

var commentStyle golicenser.CommentStyle
if cs := settings.Header.CommentStyle; cs != "" {
commentStyle, err = golicenser.ParseCommentStyle(cs)
if err != nil {
internal.LinterLogger.Fatalf("%s: parse comment style: %v", linterName, err)
}
}

vars := make(map[string]*golicenser.Var, len(settings.Header.Variables))
for k, v := range settings.Header.Variables {
if s, ok := v.(string); ok {
vars[k] = &golicenser.Var{Value: s}
continue
}

var glVar config.GoLicenserVar
if err := mapstructure.Decode(v, &glVar); err != nil {
internal.LinterLogger.Fatalf("%s: decode variable %s: %v", linterName, k, err)
}
vars[k] = &golicenser.Var{
Value: glVar.Value,
Regexp: glVar.Regexp,
}
}

conf = golicenser.Config{
Header: golicenser.HeaderOpts{
Template: template,
Matcher: settings.Header.Matcher,
MatcherEscape: settings.Header.MatcherEscape,
Author: settings.Header.Author,
AuthorRegexp: settings.Header.AuthorRegexp,
Variables: vars,
YearMode: yearMode,
CommentStyle: commentStyle,
},
Exclude: settings.Exclude,
MaxConcurrent: settings.MaxConcurrent,
CopyrightHeaderMatcher: settings.CopyrightHeaderMatcher,
}
}

if conf.Header.Template == "" || conf.Header.Author == "" {
// User did not set template or author, disable golicenser.
return goanalysis.NewLinter(linterName, linterDesc, nil, nil)
conf, err := createConfig(settings, replacer)
if err != nil {
internal.LinterLogger.Fatalf("%s: parse year mode: %v", linterName, err)
}

analyzer, err := golicenser.NewAnalyzer(conf)
Expand All @@ -95,8 +28,67 @@ func New(settings *config.GoLicenserSettings, replacer *strings.Replacer) *goana

return goanalysis.NewLinter(
linterName,
linterDesc,
"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
}
4 changes: 2 additions & 2 deletions pkg/golinters/golicenser/testdata/golicenser-fix.yml
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@ linters:
email:
value: "test@example.com"
regexp: "(.+)@example\\.com"
projectname: "golangci-lint"
exclude: [] # By default, testdata is excluded.
projectname:
value: "golangci-lint"
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,5 @@ linters:
email:
value: "test@example.com"
regexp: "(.+)@example\\.com"
projectname: "golangci-lint"
exclude: [] # By default, testdata is excluded.
projectname:
value: "golangci-lint"
Loading

AltStyle によって変換されたページ (->オリジナル) /