Skip to content

bump github.com/daixiang0/gci from 0.2.9 to 0.3.0 #2532

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

Merged
merged 5 commits into from
Feb 14, 2022
Merged
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
Next Next commit
Add support for gci sections
Signed-off-by: Norman Gehrsitz <[email protected]>
  • Loading branch information
ngehrsitz committed Jan 31, 2022
commit 55748a8dbab374852d2a86c6c57d39330c245e73
16 changes: 12 additions & 4 deletions .golangci.example.yml
Original file line number Diff line number Diff line change
Expand Up @@ -295,10 +295,18 @@ linters-settings:
statements: -1

gci:
# Put imports beginning with prefix after 3rd-party packages.
# Only support one prefix.
# If not set, use `goimports.local-prefixes`.
local-prefixes: github.com/org/project
# Checks that no inline Comments are present
no-inlineComments: false
# Checks that no prefix Comments(comment lines above an import) are present
no-prefixComments: false
# Section configuration to compare against.
# Run gci print -h for a detailed explanation
sections:
- Standard
- Default
# Separators that should be present between sections
sectionSeparators:
- Newline

gocognit:
# Minimal code complexity to report
Expand Down
2 changes: 0 additions & 2 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@ linters-settings:
funlen:
lines: 100
statements: 50
gci:
local-prefixes: github.com/golangci/golangci-lint
goconst:
min-len: 2
min-occurrences: 3
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ require (
github.com/breml/errchkjson v0.2.1
github.com/butuzov/ireturn v0.1.1
github.com/charithe/durationcheck v0.0.9
github.com/daixiang0/gci v0.2.9
github.com/daixiang0/gci v0.3.0
github.com/denis-tingajkin/go-header v0.4.2
github.com/esimonov/ifshort v1.0.4
github.com/fatih/color v1.13.0
Expand Down
8 changes: 5 additions & 3 deletions go.sum

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

5 changes: 4 additions & 1 deletion pkg/config/linters_settings.go
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,10 @@ type FunlenSettings struct {
}

type GciSettings struct {
LocalPrefixes string `mapstructure:"local-prefixes"`
NoInlineComments bool `mapstructure:"no-inlineComments"`
NoPrefixComments bool `mapstructure:"no-prefixComments"`
Sections []string `mapstructure:"sections"`
SectionSeparator []string `mapstructure:"sectionSeparators"`
}

type GocognitSettings struct {
Expand Down
99 changes: 19 additions & 80 deletions pkg/golinters/gci.go
Original file line number Diff line number Diff line change
@@ -1,96 +1,35 @@
package golinters

import (
"bytes"
"fmt"
"sync"
"strings"

"github.com/daixiang0/gci/pkg/gci"
"github.com/pkg/errors"
"github.com/shazow/go-diff/difflib"
gciAnalyzer "github.com/daixiang0/gci/pkg/analyzer"
"golang.org/x/tools/go/analysis"

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

const gciName = "gci"

func NewGci() *goanalysis.Linter {
var mu sync.Mutex
var resIssues []goanalysis.Issue
differ := difflib.New()

analyzer := &analysis.Analyzer{
Name: gciName,
Doc: goanalysis.TheOnlyanalyzerDoc,
func NewGci(settings *config.GciSettings) *goanalysis.Linter {
analyzer := gciAnalyzer.Analyzer
var cfg map[string]map[string]interface{}
if settings != nil {
cfg = map[string]map[string]interface{}{
analyzer.Name: {
gciAnalyzer.NoInlineCommentsFlag: settings.NoInlineComments,
gciAnalyzer.NoPrefixCommentsFlag: settings.NoPrefixComments,
gciAnalyzer.SectionsFlag: strings.Join(settings.Sections, gciAnalyzer.SectionDelimiter),
gciAnalyzer.SectionSeparatorsFlag: strings.Join(settings.SectionSeparator, gciAnalyzer.SectionDelimiter),
},
}
}

return goanalysis.NewLinter(
gciName,
"Gci control golang package import order and make it always deterministic.",
"Gci controls golang package import order and makes it always deterministic.",
[]*analysis.Analyzer{analyzer},
nil,
).WithContextSetter(func(lintCtx *linter.Context) {
localFlag := lintCtx.Settings().Gci.LocalPrefixes
goimportsFlag := lintCtx.Settings().Goimports.LocalPrefixes
if localFlag == "" && goimportsFlag != "" {
localFlag = goimportsFlag
}

analyzer.Run = func(pass *analysis.Pass) (interface{}, error) {
var fileNames []string
for _, f := range pass.Files {
pos := pass.Fset.PositionFor(f.Pos(), false)
fileNames = append(fileNames, pos.Filename)
}

var issues []goanalysis.Issue

flagSet := gci.FlagSet{
LocalFlag: gci.ParseLocalFlag(localFlag),
}

for _, f := range fileNames {
source, result, err := gci.Run(f, &flagSet)
if err != nil {
return nil, err
}
if result == nil {
continue
}

diff := bytes.Buffer{}
_, err = diff.WriteString(fmt.Sprintf("--- %[1]s\n+++ %[1]s\n", f))
if err != nil {
return nil, fmt.Errorf("can't write diff header: %v", err)
}

err = differ.Diff(&diff, bytes.NewReader(source), bytes.NewReader(result))
if err != nil {
return nil, fmt.Errorf("can't get gci diff output: %v", err)
}

is, err := extractIssuesFromPatch(diff.String(), lintCtx.Log, lintCtx, gciName)
if err != nil {
return nil, errors.Wrapf(err, "can't extract issues from gci diff output %q", diff.String())
}

for i := range is {
issues = append(issues, goanalysis.NewIssue(&is[i], pass))
}
}

if len(issues) == 0 {
return nil, nil
}

mu.Lock()
resIssues = append(resIssues, issues...)
mu.Unlock()

return nil, nil
}
}).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue {
return resIssues
}).WithLoadMode(goanalysis.LoadModeSyntax)
cfg,
).WithLoadMode(goanalysis.LoadModeSyntax)
}
14 changes: 6 additions & 8 deletions pkg/golinters/gofmt_common.go
Original file line number Diff line number Diff line change
Expand Up @@ -226,16 +226,14 @@ func getErrorTextForLinter(lintCtx *linter.Context, linterName string) string {
text += " with -local " + lintCtx.Settings().Goimports.LocalPrefixes
}
case gciName:
text = "File is not `gci`-ed"
localPrefixes := lintCtx.Settings().Gci.LocalPrefixes
goimportsFlag := lintCtx.Settings().Goimports.LocalPrefixes
if localPrefixes == "" && goimportsFlag != "" {
localPrefixes = goimportsFlag
optionsText := []string{}
if lintCtx.Settings().Gci.NoInlineComments {
optionsText = append(optionsText, "NoInlineComments")
}

if localPrefixes != "" {
text += " with -local " + localPrefixes
if lintCtx.Settings().Gci.NoPrefixComments {
optionsText = append(optionsText, "NoPrefixComments")
}
text = fmt.Sprintf("File does not conform to the import format configured for `Gci`(%s)", strings.Join(optionsText, ","))
}
return text
}
Expand Down
4 changes: 3 additions & 1 deletion pkg/lint/lintersdb/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config {
var errorlintCfg *config.ErrorLintSettings
var exhaustiveCfg *config.ExhaustiveSettings
var exhaustiveStructCfg *config.ExhaustiveStructSettings
var gciCfg *config.GciSettings
var goModDirectivesCfg *config.GoModDirectivesSettings
var goMndCfg *config.GoMndSettings
var gosecCfg *config.GoSecSettings
Expand Down Expand Up @@ -139,6 +140,7 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config {
errorlintCfg = &m.cfg.LintersSettings.ErrorLint
exhaustiveCfg = &m.cfg.LintersSettings.Exhaustive
exhaustiveStructCfg = &m.cfg.LintersSettings.ExhaustiveStruct
gciCfg = &m.cfg.LintersSettings.Gci
goModDirectivesCfg = &m.cfg.LintersSettings.GoModDirectives
goMndCfg = &m.cfg.LintersSettings.Gomnd
gosecCfg = &m.cfg.LintersSettings.Gosec
Expand Down Expand Up @@ -292,7 +294,7 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config {
WithPresets(linter.PresetComplexity).
WithURL("https://github.com/ultraware/funlen"),

linter.NewConfig(golinters.NewGci()).
linter.NewConfig(golinters.NewGci(gciCfg)).
WithSince("v1.30.0").
WithPresets(linter.PresetFormatting, linter.PresetImport).
WithAutoFix().
Expand Down
16 changes: 8 additions & 8 deletions test/linters_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,11 +92,11 @@ func TestGciLocal(t *testing.T) {
rc := extractRunContextFromComments(t, sourcePath)
args = append(args, rc.args...)

cfg, err := yaml.Marshal(rc.config)
cfg, err := os.ReadFile(rc.configPath)
require.NoError(t, err)

testshared.NewLintRunner(t).RunWithYamlConfig(string(cfg), args...).
ExpectHasIssue("testdata/gci/gci.go:7: File is not `gci`-ed")
ExpectHasIssue("testdata/gci/gci.go:9:1: Expected '\\n', Found '\\t'")
}

func TestMultipleOutputs(t *testing.T) {
Expand All @@ -108,11 +108,11 @@ func TestMultipleOutputs(t *testing.T) {
rc := extractRunContextFromComments(t, sourcePath)
args = append(args, rc.args...)

cfg, err := yaml.Marshal(rc.config)
cfg, err := os.ReadFile(rc.configPath)
require.NoError(t, err)

testshared.NewLintRunner(t).RunWithYamlConfig(string(cfg), args...).
ExpectHasIssue("testdata/gci/gci.go:7: File is not `gci`-ed").
ExpectHasIssue("testdata/gci/gci.go:9:1: Expected '\\n', Found '\\t'").
ExpectOutputContains(`"Issues":[`)
}

Expand All @@ -125,11 +125,11 @@ func TestStderrOutput(t *testing.T) {
rc := extractRunContextFromComments(t, sourcePath)
args = append(args, rc.args...)

cfg, err := yaml.Marshal(rc.config)
cfg, err := os.ReadFile(rc.configPath)
require.NoError(t, err)

testshared.NewLintRunner(t).RunWithYamlConfig(string(cfg), args...).
ExpectHasIssue("testdata/gci/gci.go:7: File is not `gci`-ed").
ExpectHasIssue("testdata/gci/gci.go:9:1: Expected '\\n', Found '\\t'").
ExpectOutputContains(`"Issues":[`)
}

Expand All @@ -145,11 +145,11 @@ func TestFileOutput(t *testing.T) {
rc := extractRunContextFromComments(t, sourcePath)
args = append(args, rc.args...)

cfg, err := yaml.Marshal(rc.config)
cfg, err := os.ReadFile(rc.configPath)
require.NoError(t, err)

testshared.NewLintRunner(t).RunWithYamlConfig(string(cfg), args...).
ExpectHasIssue("testdata/gci/gci.go:7: File is not `gci`-ed").
ExpectHasIssue("testdata/gci/gci.go:9:1: Expected '\\n', Found '\\t'").
ExpectOutputNotContains(`"Issues":[`)

b, err := os.ReadFile(resultPath)
Expand Down
6 changes: 6 additions & 0 deletions test/testdata/configs/gci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
linters-settings:
gci:
sections:
- Standard
- Prefix(github.com/golangci/golangci-lint)
- Default
2 changes: 2 additions & 0 deletions test/testdata/gci.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
//args: -Egci
//config_path: testdata/configs/gci.yml
package testdata

import (
"fmt"

"github.com/golangci/golangci-lint/pkg/config"

"github.com/pkg/errors"
)

Expand Down
3 changes: 1 addition & 2 deletions test/testdata/gci/gci.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
//args: -Egci
//config: linters-settings.gci.local-prefixes=github.com/golangci/golangci-lint
//config_path: testdata/configs/gci.yml
package gci

import (
"fmt"

"github.com/golangci/golangci-lint/pkg/config"

"github.com/pkg/errors"
)

Expand Down