Skip to content
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

Update codes and re-enable in golangci-lint #64

Merged
merged 3 commits into from
May 30, 2022
Merged
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
82 changes: 82 additions & 0 deletions .github/workflows/gci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
name: gci

on:
pull_request:

jobs:
build:
name: Build ${{ matrix.target_os }}_${{ matrix.target_arch }} binaries
runs-on: ${{ matrix.os }}
env:
GOVER: 1.18
GOOS: ${{ matrix.target_os }}
GOARCH: ${{ matrix.target_arch }}
GOPROXY: https://proxy.golang.org
ARCHIVE_OUTDIR: dist/archives
TEST_OUTPUT_FILE_PREFIX: test_report
strategy:
matrix:
os: [ubuntu-latest, windows-2019, macOS-latest]
target_arch: [arm, arm64, amd64]
include:
- os: ubuntu-latest
target_os: linux
- os: windows-2019
target_os: windows
- os: macOS-latest
target_os: darwin
exclude:
- os: windows-2019
target_arch: arm
- os: windows-2019
target_arch: arm64
- os: macOS-latest
target_arch: arm
steps:
- name: Set up Go ${{ env.GOVER }}
uses: actions/setup-go@v2
with:
go-version: ${{ env.GOVER }}
- name: Check out code into the Go module directory
uses: actions/checkout@v2
- name: Cache Go modules (Linux)
if: matrix.target_os == 'linux'
uses: actions/cache@v3
with:
path: |
~/.cache/go-build
~/go/pkg/mod
key: ${{ matrix.target_os }}-${{ matrix.target_arch }}-go-${{ env.GOVER }}-build-${{ hashFiles('**/go.sum') }}
restore-keys: |
${{ matrix.target_os }}-${{ matrix.target_arch }}-go-${{ env.GOVER }}-build-
- name: Cache Go modules (Windows)
if: matrix.target_os == 'windows'
uses: actions/cache@v3
with:
path: |
~\AppData\Local\go-build
~\go\pkg\mod
key: ${{ matrix.target_os }}-${{ matrix.target_arch }}-go-${{ env.GOVER }}-build-${{ hashFiles('**/go.sum') }}
restore-keys: |
${{ matrix.target_os }}-${{ matrix.target_arch }}-go-${{ env.GOVER }}-build-
- name: Cache Go modules (macOS)
if: matrix.target_os == 'darwin'
uses: actions/cache@v3
with:
path: |
~/Library/Caches/go-build
~/go/pkg/mod
key: ${{ matrix.target_os }}-${{ matrix.target_arch }}-go-${{ env.GOVER }}-build-${{ hashFiles('**/go.sum') }}
restore-keys: |
${{ matrix.target_os }}-${{ matrix.target_arch }}-go-${{ env.GOVER }}-build-
- name: golangci-lint
if: matrix.target_arch == 'amd64' && matrix.target_os == 'linux'
uses: golangci/golangci-lint-action@v3.1.0
with:
version: ${{ env.GOLANGCILINT_VER }}
- name: Run make test
env:
COVERAGE_OPTS: "-coverprofile=coverage.txt -covermode=atomic"
if: matrix.target_arch == 'amd64'
run: make test

85 changes: 85 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# options for analysis running
run:
# default concurrency is a available CPU number
concurrency: 4

# timeout for analysis, e.g. 30s, 5m, default is 1m
deadline: 10m

# 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: they won't be analyzed;
# can use regexp here: generated.*, regexp is applied on full path;
# default value is empty list, but next dirs are always skipped independently
# from this option's value:
# third_party$, testdata$, examples$, Godeps$, builtin$
skip-dirs:

# 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.
skip-files:

# output configuration options
output:
# colored-line-number|line-number|json|tab|checkstyle, default is "colored-line-number"
format: tab

# 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


# all available settings of specific linters
linters-settings:
gci:
# Checks that no inline Comments are present.
# Default: false
no-inline-comments: false

# Checks that no prefix Comments(comment lines above an import) are present.
# Default: false
no-prefix-comments: false

# Section configuration to compare against.
# Section names are case-insensitive and may contain parameters in ().
# Default: ["standard", "default"]
sections:
- standard # Captures all standard packages if they do not match another section.
- default # Contains all imports that could not be matched to another section type.
- prefix(github.com/daixiang0/gci) # Groups all imports with the specified Prefix.

# Separators that should be present between sections.
# Default: ["newLine"]
section-separators:
- newLine

gofmt:
# simplify code: gofmt with `-s` option, true by default
simplify: true
goimports:
# put imports beginning with prefix after 3rd-party packages;
# it's a comma-separated list of prefixes
local-prefixes: github.com/daixiang0/gci

linters:
fast: false
enable:
- gofmt
- gofumpt
- goimports
- gci
disable-all: true

issues:
exclude:
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,13 @@ Flags:

```

**Note**::

The old style is only for local tests, `golangci-lint` uses new style.

## Examples

Run `gci write --Section Standard --Section Default --Section "Prefix(github.com/daixiang0/gci)" main.go` and you will handle following cases:
Run `gci write --Section Standard --Section Default --Section "Prefix(github.com/daixiang0/gci)" main.go` and you will handle following cases:

### simple case

Expand Down
1 change: 1 addition & 0 deletions cmd/gci/completion.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ func subCommandOrGoFileCompletion(cmd *cobra.Command, args []string, toComplete
}
return goFileCompletion(cmd, args, toComplete)
}

func goFileCompletion(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return []string{"go"}, cobra.ShellCompDirectiveFilterFileExt
}
4 changes: 1 addition & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@ import (
"github.com/daixiang0/gci/cmd/gci"
)

var (
version = "0.3"
)
var version = "0.3"

func main() {
e := gci.NewExecutor(version)
Expand Down
47 changes: 30 additions & 17 deletions pkg/analyzer/analyzer.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,21 @@ import (
"go/token"
"strings"

"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"

"github.com/daixiang0/gci/pkg/configuration"
"github.com/daixiang0/gci/pkg/gci"
"github.com/daixiang0/gci/pkg/io"

"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"github.com/daixiang0/gci/pkg/log"
)

const (
NoInlineCommentsFlag = "noInlineComments"
NoPrefixCommentsFlag = "noPrefixComments"
SectionsFlag = "Sections"
SectionSeparatorsFlag = "SectionSeparators"
SectionDelimiter = ";"
SectionDelimiter = ","
)

var (
Expand All @@ -34,6 +35,9 @@ func init() {
Analyzer.Flags.BoolVar(&noPrefixComments, NoPrefixCommentsFlag, false, "If comments above an input should be present")
Analyzer.Flags.StringVar(&sectionsStr, SectionsFlag, "", "Specify the Sections format that should be used to check the file formatting")
Analyzer.Flags.StringVar(&sectionSeparatorsStr, SectionSeparatorsFlag, "", "Specify the Sections that are inserted as Separators between Sections")

log.InitLogger()
defer log.L().Sync()
}

var Analyzer = &analysis.Analyzer{
Expand All @@ -44,8 +48,6 @@ var Analyzer = &analysis.Analyzer{
}

func runAnalysis(pass *analysis.Pass) (interface{}, error) {
// TODO input validation

var fileReferences []*token.File
// extract file references for all files in the analyzer pass
for _, pkgFile := range pass.Files {
Expand Down Expand Up @@ -80,17 +82,7 @@ func runAnalysis(pass *analysis.Pass) (interface{}, error) {
case -1:
// no difference
default:
diffPos := file.Position(file.Pos(diffIdx))
// prevent invalid access to array
fileRune := "nil"
formattedRune := "nil"
if len(fileRunes)-1 >= diffIdx {
fileRune = fmt.Sprintf("%q", fileRunes[diffIdx])
}
if len(formattedRunes)-1 >= diffIdx {
formattedRune = fmt.Sprintf("%q", formattedRunes[diffIdx])
}
pass.Reportf(file.Pos(diffIdx), "Expected %s, Found %s at %s[line %d,col %d]", formattedRune, fileRune, filePath, diffPos.Line, diffPos.Column)
pass.Reportf(file.Pos(diffIdx), "fix by `%s %s`", generateCmdLine(*gciCfg), filePath)
}
}
return nil, nil
Expand Down Expand Up @@ -126,6 +118,27 @@ func parseGciConfiguration() (*gci.GciConfiguration, error) {
var sectionSeparatorStrings []string
if sectionSeparatorsStr != "" {
sectionSeparatorStrings = strings.Split(sectionSeparatorsStr, SectionDelimiter)
fmt.Println(sectionSeparatorsStr)
}
return gci.GciStringConfiguration{fmtCfg, sectionStrings, sectionSeparatorStrings}.Parse()
}

func generateCmdLine(cfg gci.GciConfiguration) string {
result := "gci write"

if cfg.FormatterConfiguration.NoInlineComments {
result += " --NoInlineComments "
}

if cfg.FormatterConfiguration.NoPrefixComments {
result += " --NoPrefixComments "
}

for _, s := range cfg.Sections.String() {
result += fmt.Sprintf(" --Section \"%s\" ", s)
}
for _, s := range cfg.SectionSeparators.String() {
result += fmt.Sprintf(" --SectionSeparator %s ", s)
}
return result
}
4 changes: 2 additions & 2 deletions pkg/gci/configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ package gci
import (
"io/ioutil"

"gopkg.in/yaml.v3"

"github.com/daixiang0/gci/pkg/configuration"
sectionsPkg "github.com/daixiang0/gci/pkg/gci/sections"

"gopkg.in/yaml.v3"
)

type GciConfiguration struct {
Expand Down
10 changes: 6 additions & 4 deletions pkg/gci/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ type InvalidImportSplitError struct {
}

func (i InvalidImportSplitError) Error() string {
return fmt.Sprintf("seperating the inline comment from the import yielded an invalid number of segments: %v", i.segments)
return fmt.Sprintf("separating the inline comment from the import yielded an invalid number of segments: %v", i.segments)
}

func (i InvalidImportSplitError) Is(err error) bool {
Expand All @@ -53,16 +53,18 @@ type InvalidAliasSplitError struct {
}

func (i InvalidAliasSplitError) Error() string {
return fmt.Sprintf("seperating the alias from the path yielded an invalid number of segments: %v", i.segments)
return fmt.Sprintf("separating the alias from the path yielded an invalid number of segments: %v", i.segments)
}

func (i InvalidAliasSplitError) Is(err error) bool {
_, ok := err.(InvalidAliasSplitError)
return ok
}

var MissingImportStatementError = FileParsingError{errors.New("no import statement present in File")}
var ImportStatementNotClosedError = FileParsingError{errors.New("import statement not closed")}
var (
MissingImportStatementError = FileParsingError{errors.New("no import statement present in File")}
ImportStatementNotClosedError = FileParsingError{errors.New("import statement not closed")}
)

type FileParsingError struct {
error
Expand Down
4 changes: 2 additions & 2 deletions pkg/gci/errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ import (
"errors"
"testing"

"github.com/stretchr/testify/assert"

importPkg "github.com/daixiang0/gci/pkg/gci/imports"
sectionsPkg "github.com/daixiang0/gci/pkg/gci/sections"

"github.com/stretchr/testify/assert"
)

func TestErrorMatching(t *testing.T) {
Expand Down
3 changes: 1 addition & 2 deletions pkg/gci/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,10 @@ func formatGoFile(input []byte, cfg GciConfiguration) ([]byte, error) {

// Takes unsorted imports as byte array and formats them according to the specified sections
func formatImportBlock(input []byte, cfg GciConfiguration) ([]byte, error) {
//strings.ReplaceAll(input, "\r\n", linebreak)
lines := strings.Split(string(input), constants.Linebreak)
imports, err := parseToImportDefinitions(lines)
if err != nil {
return nil, fmt.Errorf("an error occured while trying to parse imports: %w", err)
return nil, fmt.Errorf("an error occurred while trying to parse imports: %w", err)
}
log.L().Debug(fmt.Sprintf("Parsed imports in file: %v", imports))

Expand Down
Loading