GithubHelp home page GithubHelp logo

daixiang0 / gci Goto Github PK

View Code? Open in Web Editor NEW
365.0 365.0 62.0 223 KB

GCI, a tool that control golang package import order and make it always deterministic.

License: BSD 3-Clause "New" or "Revised" License

Go 99.49% Makefile 0.51%

gci's Introduction

Hi there ๐Ÿ‘‹

  • ๐Ÿ”ญ Dapr\Thanos\Golangci-lint Maintainer
  • ๐Ÿ‘ฏ Mircosoft MVP
  • ๐Ÿ“ซ How to reach me: [email protected]

gci's People

Contributors

alexandear avatar artuross avatar avorima avatar ccoveille avatar charleskorn avatar cornelk avatar daixiang0 avatar danxmoran avatar dnovikoff avatar dreamacro avatar ebati avatar glightfoot avatar imsingee avatar jufemaiz avatar kwo avatar ldez avatar lukeshu avatar matheusalcantarazup avatar matthewhughes934 avatar mhofstetter avatar mnencia avatar ngehrsitz avatar omertuc avatar oscr avatar petr-korobeinikov avatar ryokusnadi avatar svilgelm avatar sylr avatar terryhowe avatar zaibon avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

gci's Issues

upgrading to v0.2.5 results in `exit 1` without any other change

@dependabot tried to automatically update the version of gci we are using -> berty/berty#2771


It results in gci terminating with exit 1 without any useful logging information:

moul@fwrz:~/go/src/berty.tech/berty/go (dependabot/go_modules/github.com/daixiang0/gci-0.2.5) $ go run github.com/daixiang0/gci -d -local berty.tech .
skip file cmd/berty/doc.go since no import
skip file cmd/berty/mini/doc.go since no import
skip file cmd/berty/mini/example_test.go since no import
skip file cmd/berty-doctor/example_test.go since no import
skip file cmd/betabot/example_test.go since no import
skip file cmd/rdvp/doc.go since no import
[...] // skipping annoying logs
skip file pkg/username/others.go since no import
skip file pkg/username/username.go since no import
exit status 1

I also tried removing the -local option, but still the exit 1 issue


FYI, here is our setup:

  • latest go version
  • go modules
  • canonical URLs (berty.tech/berty is mapped to github.com/berty/berty)
  • we're using the official way of using major versions berty.tech/berty/v2 is not a real folders, but is clearly defined in the go.mod

I'm sorry, I don't have enough knowledge of your project's internals to give you more details, but I think this comes from #22

Thank you very much, and take care

gci wants to remove comment `// ANCHOR_END: Conditions`

Hi ๐Ÿ‘‹

When running latest gci on cluster-api I got 3 findings:

api/v1alpha3/condition_types.go:96: File is not `gci`-ed with -skip-generated -s standard,default (gci)

// ANCHOR_END: Conditions
api/v1alpha4/condition_types.go:96: File is not `gci`-ed with -skip-generated -s standard,default (gci)

// ANCHOR_END: Conditions
api/v1beta1/condition_types.go:93: File is not `gci`-ed with -skip-generated -s standard,default (gci)

// ANCHOR_END: Conditions

For example https://github.com/kubernetes-sigs/cluster-api/blob/6bf351bf9d8514267131b14ac80cca6ced2ab271/api/v1alpha3/condition_types.go#L97

Example with debug info enabled

2022-07-19T00:22:06.019+0200	DEBUG	gci/gci.go:116	Loaded File: /home/oscr/go/src/k8s.io/kubernetes-sig/cluster-api/api/v1alpha3/condition_types.go
2022-07-19T00:22:06.019+0200	DEBUG	format/format.go:41	Matched import &{599 627 corev1 k8s.io/api/core/v1} to section default
2022-07-19T00:22:06.019+0200	DEBUG	format/format.go:41	Matched import &{628 674 metav1 k8s.io/apimachinery/pkg/apis/meta/v1} to section default
--- /home/oscr/go/src/k8s.io/kubernetes-sig/cluster-api/api/v1alpha3/condition_types.go
+++ /home/oscr/go/src/k8s.io/kubernetes-sig/cluster-api/api/v1alpha3/condition_types.go
@@ -93,5 +93,3 @@
 
 // Conditions provide observations of the operational state of a Cluster API resource.
 type Conditions []Condition
-
-// ANCHOR_END: Conditions

Are these correct findings?
Is there a way to ignore these findings other than not linting the file?

Duplicate imports with different aliases end up with the same alias

Given the following imports:

import (
    "path/to/import/a"
    b "path/to/import/a"
)

After running the fixer on a file they will end up like this:

import (
    b "path/to/import/a"
    b "path/to/import/a"
)

Which messes up the code quite a bit. IMHO this shouldn't be allowed by the compiler in the first place, but (sadly) it is.

Note: I use golangci-lint 1.30.0

Formatter request: sort methods

Hi @daixiang0,
Can you build a project to sort methods of a struct or interface?

type a struct{}

func (*a) C(){}
func (*a) D(){}
func (*a) A(){}
func (*a) B(){}
func (*a) Y(){}

this code should be

type a struct{}

func (*a) A(){}
func (*a) B(){}
func (*a) C(){}
func (*a) D(){}
func (*a) Y(){}

Thank you!

Handle newlines in blocks caused by conflict with goimports

Multi-line comments separated with newlines cause conflicts with goimports.

Given:

package proc

import (
	"github.com/a/b"
	"github.com/local/foo"

	// A multi-line comment explaining what this dependency
	// is used for or what it initializes.
	_ "github.com/client/auth"
)
sections:
  - Standard
  - Default
  - Prefix(github.com/local)

The result is:

package proc

import (
	"github.com/a/b"
	// A multi-line comment explaining what this dependency
	// is used for or what it initializes.
	_ "github.com/client/auth"

	"github.com/local/foo"
)

But goimports will format it as:

package proc

import (
	"github.com/a/b"

	// A multi-line comment explaining what this dependency
	// is used for or what it initializes.
	_ "github.com/client/auth"

	"github.com/local/foo"
)

This means that the two cannot be used together, e.g. with golangci-lint.

Support for go modules (automatically infer module path)?

Hi,

at $company, we have a bunch of Go projects named gitlab.$company.com/$project.

All projects use Go modules, i.e. there's a go.mod containing module gitlab.$company.com/$project.

$ head -1 go.mod
module gitlab.$company.com/$project

However, gci doesn't seem to make use of this information, compare the output of the following gci runs (with and without -local flag):

$ gci -d -local gitlab.$company.com/$project queue/client.go
[no output]
$ gci -d queue/client.go
--- queue/client.go.orig        2021-01-25 11:25:02.582529319 +0100
+++ queue/client.go     2021-01-25 11:25:02.582529319 +0100
@@ -11,7 +11,6 @@
 
        ws "nhooyr.io/websocket"
        "nhooyr.io/websocket/wsjson"
-
        "gitlab.$company.com/$project/turn"
 )

The client.go contains this import block:

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"sync"
	"time"

	ws "nhooyr.io/websocket"
	"nhooyr.io/websocket/wsjson"

	"gitlab.$company.com/$project/turn"
)

Would this be a valid feature request? I'd like gci to lookup and use the module path when invoked without -local.

"skip file since no import" output breaks use-case of outputting to stdout

After #41 merges I was hoping to be able to use gci as part of a chain of formatting tools, roughly:

gofmt main.go | gci > main.formatted.go

This use-case doesn't work for files with no imports, because gci prints "skip file main.go since no import" to stdout instead of the contents of the file.

It would be better if the "skip file" message was printed to stderr instead of stdout. If -w is passed the tool can still bail out early, but if -w is missing then the file contents should still be printed to stdout.

Known Issue List

All issues in this list are planned to fix(not listed in order):

  • Comments are not formatted
  • Blank can be more than one between Name and Path in an import block #108
  • Blank can be more than one between Path and Comment in an import block #108
  • Miss imports completion
  • Miss imports deduplication
  • Cannot handle multiple imports group #106
  • Remove Analyzer layer and fully use analyzer syntax

The conflict with goimports like #76 only provides a workaround now.

GCI is way too verbose

With the new version I have a massive output like

$ find . -name '*.go' | xargs gci write

// ...
2022/02/07 09:54:53 Loaded File: pkg/query/products_test.go
2022/02/07 09:54:53 Skipping correctly formatted File: cmd/refresh_contentful/query_merchants_test.go
2022/02/07 09:54:53 Skipping correctly formatted File: cmd/http/main_test.go
2022/02/07 09:54:53 Skipping correctly formatted File: pkg/resource/utils.go
2022/02/07 09:54:53 Loaded File: pkg/query/params.go
2022/02/07 09:54:53 Skipping correctly formatted File: pkg/resource/product.go
2022/02/07 09:54:53 Skipping correctly formatted File: pkg/query/search_image.go
2022/02/07 09:54:53 Skipping correctly formatted File: pkg/graphql/relay/connection_test.go
// ...

Also it goes to stderr, so I can't even choose to only showing errors by piping stdout to /dev/null. I think all those things should be part of debug and in stdin.

gci write --local option in v0.3.2

In v0.3.2 --local option is deprecated?

Write modifies the specified files in-place

Usage:
  gci write path... [flags]

Aliases:
  write, overwrite

Flags:
      --NoInlineComments           Drops inline comments while formatting
      --NoPrefixComments           Drops comment lines above an import statement while formatting
  -s, --Section strings            Sections define how inputs will be processed. Section names are case-insensitive and may contain parameters in (). A section can contain a Prefix and a Suffix section which is delimited by ":". These sections can be used for formatting and will only be rendered if the main section contains an entry.
                                   Comment(your text here) | CommentLine(your text here) - Prints the specified indented comment
                                   Def | Default - Contains all imports that could not be matched to another section type
                                   NL | NewLine - Prints an empty line
                                   Prefix(gitlab.com/myorg) | pkgPrefix(gitlab.com/myorg) - Groups all imports with the specified Prefix. Imports will be matched to the longest Prefix.
                                   Std | Standard - Captures all standard packages if they do not match another section
                                    (default [Standard,Default])
  -x, --SectionSeparator strings   SectionSeparators are inserted between Sections (default [NewLine])
  -d, --debug                      Enables debug output from the formatter
  -h, --help                       help for write

feature: support multiple local import groups

The company I work for have a preference to arrange the import groupings as follows:

  • stdlib
  • third-party
  • same github organization (or probably just other projects belonging to the company)
  • current project

While goimport can't handle spotting the difference between the last two and sorting the different imports into the desired groups, it also doesn't combine them into a single grouping either. It would be nice if gci could be told of an additional grouping to distinguish between the last two import groups.

Prefixes with capital letters are ignored

With the following config:

sections:
  - Standard
  - Default
  - Prefix(github.com/Azure)

I would expect that the imports are formatted as so:

import (
	"fmt"

	"github.com/golang"

	"github.com/Azure/go-autorest/autorest"
)

However, as of v0.4.0 it appears that having a capital letter in the prefix, in this case the A in Azure, results in the prefix being ignored. So instead I am getting:

import (
	"fmt"

	"github.com/Azure/go-autorest/autorest"
	"github.com/golang"
)

0.6.0 has extra newline bug with multi custom prefix

test 0.4.3 and 0.5.0 is OK.

with 0.6.0, when we have both org level Prefix and project level Prefix, but the imports does not contians any org level Prefix things, it will put extra newline before project level Preifx

with command:

gci diff  -s standard -s default -s 'Prefix(code.example.com)' -s 'Prefix(code.example.com/foo/bar/project)' --skip-generated .

so I have org level Prefix code.example.com

and

project level Prefix code.example.com/foo/bar/project

a.go for re-produce:

package demo

import (
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"

	"code.example.com/foo/bar/project/constant"
 )

test 0.4.3 and 0.5.0 will not change this.

go install github.com/daixiang0/[email protected]

# or

go install github.com/daixiang0/[email protected]

but 0.6.0 will:

go install github.com/daixiang0/[email protected]
--- a.go
+++ a.go
@@ -4,5 +4,6 @@
 	"go.mongodb.org/mongo-driver/bson"
 	"go.mongodb.org/mongo-driver/mongo/options"
 
+
 	"code.example.com/foo/bar/project/constant"
  )

Group dot imports

AFAICT gci is not able to group dot imports together. It would be nice to be able to configure this.

Usage help is incorrect

Usage:
  gci [-diff | -write] [-local localPackageURLs] path... [flags]
  gci [command]

So I do what it says:

$ gci -write -local istio.io pkg/jwt/jwt.go
Error: unknown shorthand flag: 'r' in -rite

I try this as well:

 gci write -local istio.io pkg/jwt/jwt.go
Error: unknown shorthand flag: 'l' in -local

Separate local packages from 3rd party with newline?

My normal company policy is "standard lib/company packages/3rd party" groups, each separated by newlines.
Basically "most" to "least" trusted packages.
I see that I can define "local" packages from 3rd party packages so they are at the end, but is there a way have a new line between them? e.g.

import (
	"bytes"

	"github.com/aws/aws-sdk-go-v2/aws"

	"awesomeLocalEnterpriseGit.company.com/pkg1"
)

Suggestion: Change or allow optional flag to accept inline comments for imports

An example in a migration source file is as follows (pre-gci run):

import (
	"github.com/golang-migrate/migrate/v4"
	_ "github.com/golang-migrate/migrate/v4/database/postgres" // database migration drivers
	_ "github.com/golang-migrate/migrate/v4/source/file"       // database migration drivers
	_ "github.com/lib/pq"                                      // database drivers
	"github.com/pkg/errors"
)

When _ a import, it requires a comment, for good reason. However, gci dictates that the comments should be above the imports, however that isn't adequate when changed simply to the following:

import (
	"github.com/golang-migrate/migrate/v4"
	// database migration drivers
	_ "github.com/golang-migrate/migrate/v4/database/postgres"
	// database migration drivers
	_ "github.com/golang-migrate/migrate/v4/source/file"
	// database drivers
	_ "github.com/lib/pq"
	"github.com/pkg/errors"
)

This isn't what gci wants either. Fixing it to be gci compliant:

import (
	"github.com/golang-migrate/migrate/v4"

	// database migration drivers
	_ "github.com/golang-migrate/migrate/v4/database/postgres"

	// database migration drivers
	_ "github.com/golang-migrate/migrate/v4/source/file"

	// database drivers
	_ "github.com/lib/pq"
	"github.com/pkg/errors"
)

Perhaps it's just personal opinion, but when there are multiple comments required in the import block, it looks a lot more readable and concise to allow for them to be inline. If a comment requires a new line above them, it indicates to me that the following block of imports all pertain to that comment and not just the one directly below it (e.g. ".../pkg/errors" isn't a database driver).

I would love to hear opinions on this for one way or another.

panic: runtime error: index out of range [-1]

I found a testcase that causes a runtime panic in gci:

$ cat config/config_fuzz.go 
package config

import (
//      "os"
)
$ gci config
panic: runtime error: index out of range [-1]

goroutine 1 [running]:
github.com/daixiang0/gci/pkg/gci.(*pkg).fmt(0xc00011c0a0, 0x1, 0x1, 0x0)
        .../go/src/github.com/daixiang0/gci/pkg/gci/gci.go:130 +0xb0a
github.com/daixiang0/gci/pkg/gci.processFile(0xc000126020, 0x15, 0x51fbc0, 0xc000128008, 0xc00011c040, 0x0, 0x0)
        .../go/src/github.com/daixiang0/gci/pkg/gci/gci.go:297 +0x33a
github.com/daixiang0/gci/pkg/gci.visitFile.func1(0xc000126020, 0x15, 0x520b60, 0xc000110b60, 0x0, 0x0, 0x4aec7d, 0xc000110b60)
        .../go/src/github.com/daixiang0/gci/pkg/gci/gci.go:249 +0xb3
path/filepath.walk(0xc000126020, 0x15, 0x520b60, 0xc000110b60, 0xc000104290, 0x0, 0x0)
        .../go/go/src/path/filepath/path.go:360 +0x423
path/filepath.walk(0x7ffed58acf99, 0x6, 0x520b60, 0xc000110a90, 0xc000104290, 0x0, 0xc00010cec0)
        .../go/go/src/path/filepath/path.go:384 +0x2fe
path/filepath.Walk(0x7ffed58acf99, 0x6, 0xc000104290, 0x0, 0x0)
        .../go/go/src/path/filepath/path.go:406 +0x105
github.com/daixiang0/gci/pkg/gci.WalkDir(0x7ffed58acf99, 0x6, 0xc00011c040, 0xc0001109c0, 0x0)
        .../go/src/github.com/daixiang0/gci/pkg/gci/gci.go:256 +0x4d
main.main()
        .../go/src/github.com/daixiang0/gci/main.go:56 +0x1c5

AFAICS len(ret) is 0 in gci/pkg/gci/gci.go:

   130          if ret[len(ret)-1] == linebreak {
   131                  ret = ret[:len(ret)-1]
   132          }

panic: runtime error: slice bounds out of range

$ gci -local istio.io -w main.go
panic: runtime error: slice bounds out of range [630:619]

goroutine 1 [running]:
github.com/daixiang0/gci/pkg/gci.processFile(0x7ffd12f2fb49, 0x7, 0x51df20, 0xc00000e010, 0xc00000c060, 0x0, 0x0)
        /home/howardjohn/go/pkg/mod/github.com/daixiang0/[email protected]/pkg/gci/gci.go:288 +0xc3d
github.com/daixiang0/gci/pkg/gci.ProcessFile(...)
        /home/howardjohn/go/pkg/mod/github.com/daixiang0/[email protected]/pkg/gci/gci.go:261
main.main()
        /home/howardjohn/go/pkg/mod/github.com/daixiang0/[email protected]/main.go:58 +0x237
$ cat main.go
// +build integ
// Copyright Istio Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package telemetry

import (
        "fmt"
        "os"

        "istio.io/istio/pkg/test/framework/resource"
        )

        _ = resource.Cluster
        _ = fmt.Println
        _ = os.Stdout

Use `ast` to parse codes

Now we parse codes based on strings, difficulty handling complex situations, current parse logic is much long, design to switch to use ast package to parse codes, may learn goimports.

Follow semver

vMAJOR.MINOR.PATCH

When you add a new feature, you have to increment MINOR part of the version.
When you fix a bug, you have to increment PATCH part of the version.

https://semver.org/

Local flag not working with non URL package names

In my project I'm using single name like foo instead of full URL package names (e.g. github.com/user/foo). In cases like this local flag is not used and packages are not grouped after 3rd party packages.

Example

Here is a simplified example of the problem.

Go version: 1.15.1
GCI version: 0.2.4

go.mod

module foo

go 1.15

main.go

package main

import (
	"fmt"

	"foo/bar"
)

func main() {
	fmt.Println("foo", bar.Bar())
}

Actual output

> gci -d -local foo main.go
diff -u main.go.orig main.go
--- main.go.orig        2020-09-23 12:48:27.973264200 +0200
+++ main.go     2020-09-23 12:48:27.973822200 +0200
@@ -2,7 +2,6 @@
 
 import (
        "fmt"
-
        "foo/bar"
 )

Expected output

The expected behavior should be for command to pass without errors.

Expected '\t', found '\n' in import section with comments

Hi,

When using gci with golangci-lint, gci will report an error if a comment is above a package, like so:

package main

import (
	"fmt"
                               <- gci: Expected '\t', Found '\n' at main.go[line 5,col 1]
	// Foobar
	"net/http"
)

func main() {
	fmt.Println("foobar")
	fmt.Println(http.MethodGet)
}

This issue has been reported on the golangci-lint repo

.golangci.yaml

linters:
  disable-all: true
  enable:
    - gci

Gci version

$ gci -v
gci version 0.3

gci formats template string

Hello!

I have a valid template:

// example.go
package example

import "text/template"

var tmpl = template.Must(template.New("example").Parse(`
package {{ .Package }}

import (
	"fmt"

	{{ range $, $i := .Imports }}
		{{ $i }}
	{{ end }}
)
`))

Run gci (v0.2.8):

 gci -w example.go 

Now I have invalid template:

# example.go
package example

import "text/template"

var tmpl = template.Must(template.New("example").Parse(`
package {{ .Package }}

import (
	"fmt"

	{{ $i
	{{ end
	{{ range
)
`))

๐Ÿ˜ข

Support for stdin like goimports gofmt etc.

These tools usually support reading from stdin.
This means that you can pipe the output through each tool.

For example cat $file | goimports | gci -local "$(go list -m)" | gofmt -s would do each tool in a row without writing to disk.

errors when using import alias, zap package since version 0.3.0

We are using gci as part of golangci-lint. Ever since version 0.3.0, we have been getting errors where previous versions have worked.

This error seems like it's expecting everything to import from github.com, however we use zap which comes from go.uber.org.

Expected 'i', Found 'o'
"go.uber.org/zap"

We also get this, which seems to be related to using aliases

Expected '"', Found 'l'
log "github.com/sirupsen/logrus"

This version also seems to not like blank lines between our third party libraries and internal imports.
Expected '\t', Found '\n'

import package questions

when i import packages as the following, cannot pass the gci check

import (
	_ "crypto/sha256" // initialize crypto/sha256 to enable sha256 algorithm
	_ "crypto/sha512" // initialize crypto/sha512 to enable sha512 algorithm
	"strings"

	"github.com/distribution/distribution/v3/reference"
)

but when i modify the format to the following, it can pass the gci check

import (

	// initialize crypto/sha256 to enable sha256 algorithm
	_ "crypto/sha256"

	// initialize crypto/sha512 to enable sha512 algorithm
	_ "crypto/sha512"
	"strings"

	"github.com/distribution/distribution/v3/reference"
)

is this verification reasonable?
comments of the import package should be preceded by a blank line,
and the comments and the imported packages cannot be on the same line

Add support for multi-line comments

When running this formatter against our code, we noticed that it was removing all but the last line from multi-line block comments on imports.

It looks like this is referenced as a TODO in the README ("Support multiple lines of comment in import block"), but just wanted to call it out as an explicit issue / feature request.

Example

For example, for a file like this:

package example

import (
	// A block comment about why this package is being imported.
	//
	// More information about why this package is being imported.
	_ "github.com/example/nested"
)
...

Expected output

We expected nothing to happen to this file. The multi-line comment block would be treated as associated with the import below it and kept together.

Actual output

The formatter removes all but the last line of the comment.

> gci -d .
diff -u example.go.orig example.go
--- example.go.orig	2020-09-01 08:10:37.000000000 -0700
+++ example.go	2020-09-01 08:10:37.000000000 -0700
@@ -1,8 +1,7 @@
 package example
 
 import (
-	// A block comment about why this package is being imported.
-	//
+
 	// More information about why this package is being imported.
 	_ "github.com/example/nested"
 )

Ignore generated code

It would be nice if auto-generated code files could be skipped when fixing imports. The files could be identified by a Code generated by ... comment or a name pattern like zz.*.go or *.generated.go.
golangci-lint already implemented skipping auto-generated files, but manually running gci on the project will still cause diffs after every time the code is re-generated.

The tags v0.2.2, v0.2.3, v0.2.4 are on dangling commits

The tags v0.2.2, v0.2.3, v0.2.4 are on dangling commits: the commits are neither on the master branch nor on any other branch

I think that the master branch has been push forced.

tags commits
$ git show-ref --tags
e4abc2084b7411538e8db74cebabe6aa7c72db22 refs/tags/v0.1
66f1df783cb2a34683b8b8b9d158ef42240f0003 refs/tags/v0.2
1a47373a044d81e018e9dcae476a4c2402466c7d refs/tags/v0.2.1
a5f5d21eae6a166bae1457dcba44f4674acb002a refs/tags/v0.2.2
d625c55f0e9b970038f12155479831555a817f78 refs/tags/v0.2.3
c177722c22ed950e3f367331f2b9486421b6f070 refs/tags/v0.2.3.1
d625c55f0e9b970038f12155479831555a817f78 refs/tags/v0.2.4
4ad32334d5f2f22af98acd6b44a1e1b3f0b5ca38 refs/tags/v0.2.5
$ git log --oneline --decorate --tags --no-walk
4ad3233 (HEAD -> master, tag: v0.2.5, origin/master, origin/HEAD) allow non-URL local package names (#22)
d625c55 (tag: v0.2.4, tag: v0.2.3) Refactor gci.Run
a5f5d21 (tag: v0.2.2) remove duplicate blank in comment
c177722 (tag: v0.2.3.1) Remove extra space
1a47373 (tag: v0.2.1) Fix -d option cannot work
66f1df7 (tag: v0.2) Update README
e4abc20 (tag: v0.1) Add linebreak before comment line, same as goimport
all commits from all the branches
$ git log --oneline --decorate --graph --branches
* 4ad3233 (HEAD -> master, tag: v0.2.5, origin/master, origin/HEAD) allow non-URL local package names (#22)
* c177722 (tag: v0.2.3.1) Remove extra space
* 1a47373 (tag: v0.2.1) Fix -d option cannot work
* 0d8d190 Fix panic when comment occur in the last line
* 66f1df7 (tag: v0.2) Update README
* 106b42d refactor and implement go/analyzer
* e4abc20 (tag: v0.1) Add linebreak before comment line, same as goimport
* e0e26a3 Refactor and add testcase
* beed208 Update README
* dccec63 implement gci
* 2fa5e49 Update readme
* 05aafe0 Initial commit

I created a branch ghost based on the tag v0.2.4 and I can see the rewrite of the history:

dangling commits
$ git log --oneline --decorate --graph --branches 
* 4ad3233 (HEAD -> master, tag: v0.2.5, origin/master, origin/HEAD) allow non-URL local package names (#22)
* c177722 (tag: v0.2.3.1) Remove extra space
| * d625c55 (tag: v0.2.4, tag: v0.2.3, ghost) Refactor gci.Run
| * 6a40cd1 Remove extra space
| * a5f5d21 (tag: v0.2.2) remove duplicate blank in comment
| * 2c513d1 fix wrong exit code
|/  
* 1a47373 (tag: v0.2.1) Fix -d option cannot work
* 0d8d190 Fix panic when comment occur in the last line
* 66f1df7 (tag: v0.2) Update README
* 106b42d refactor and implement go/analyzer
* e4abc20 (tag: v0.1) Add linebreak before comment line, same as goimport
* e0e26a3 Refactor and add testcase
* beed208 Update README
* dccec63 implement gci
* 2fa5e49 Update readme
* 05aafe0 Initial commit

@daixiang0 I think that you have to reconcile the history, the following commands will catch the dangling commits:

git fetch
git checkout master
git pull origin master
git branch ghost v0.2.4
git merge ghost -m "chore: catch dangling commits"
git branch -D ghost
git push origin master

After that, you have to create a new release (v0.2.6).

Note: you don't have to push force. You just have to copy-paste my commands.

golangci/golangci-lint#1521 (comment)
golangci/golangci-lint#1521 (comment)

Running error: gci: failed to diff: exec: \"diff\": executable file not found in $PATH

Hi,
I'm using a custom docker files, that does not contain a diff tool, and the golangci-lint fails with an error:

level=warning msg="[runner] Can't run linter goanalysis_metalinter: gci: failed to diff: exec: \"diff\": executable file not found in $PATH"
level=error msg="Running error: gci: failed to diff: exec: \"diff\": executable file not found in $PATH"

Please get rid of usage the diff tool, please use the github.com/shazow/go-diff/difflib library, example of ho to use it you can find here: https://github.com/golangci/golangci-lint/blob/master/pkg/golinters/gofumpt.go#L62

Please, support inline "// nolint:..." comments

I have a project using sha1 package. And multiple linters checks are run against the project.
gosec linter warns about the sha1 package usage, but I do not plan to change the package, so I want to suppress the warning with the "// nolint:gosec" inline comment,

	"crypto/sha1" // nolint:gosec

after that the gci linter check produces the error about the sources that are not gci-ed.
After passing the sources through gci (which moves the inline comment up to the previous line),

	// nolint:gosec
	"crypto/sha1"

Now gosec linter complains again.

The deadlock/deadloop...

How to make both linters happy?

What's the meaning of 'local'?

Normally, these imported pkgs should be seen as three categories:

  1. built-in pkg
  2. in-this-pkg dependency
  3. 3rd external dependency
    they will be seperated by newline, from top to down.

I noticed that '-local $prefix' will make the pkgs beginning with the $prefix the bottom of the import block.
But from the first the view, I would think 'local' means in-this-pkg dependency

fix me, Please!

Stop skip file log output

skip file x.go since no import

I exec gci all files in project. I want to stop many skip file log outputs.

Checksum mismatch for v0.2.3

The most recently tagged release appears to not match what the Go sum database presents:

go: downloading github.com/daixiang0/gci v0.2.3
go get github.com/daixiang0/gci@upgrade: github.com/daixiang0/[email protected]: verifying module: checksum mismatch
	downloaded: h1:+mP3cW9wrL1wxE+2qqUt99Xx3eSM1lsqqOveAMZqA4A=
	sum.golang.org: h1:wg2R5t3NwFSmsGZDaD1mjiv0aRqktnaijE9f4SeLqu0=

SECURITY ERROR
This download does NOT match the one reported by the checksum server.
The bits may have been replaced on the origin server, or an attacker may
have intercepted the download attempt.

For more information, see 'go help module-auth'.

If you've force pushed (either commits or the tags), this will break the checksumming Go does to make sure that builds are reproducible and secure.

You may want to tag a v0.2.4 in order to make the latest version usable, as at the moment the latest version won't be importable by consumers like golangci-lint.

"Error: an error occured while trying to parse imports: path is missing starting quotes" on valid Go file

If I have a file that contains this content:

package main

import (
	/*
		#include "types.h"
	*/
	"C"
)

...and invoke gci with gci diff --debug file.go, I get this error:

2022/03/01 11:42:07 Loaded File: file.go
Error: an error occured while trying to parse imports: path is missing starting quotes

Is this expected? I can't see what the issue is.

Removing the /* ... */ causes gci to not fail with an error, but I can't remove that comment as cgo relies on it.

Comment for ignored import

Given the following import section:

import (
    // ...
    _ "net/http/pprof" // register pprof HTTP handlers #nosec
)

gci tries to fix it as

import (
    // ...

    // register pprof HTTP handlers #nosec
    _ "net/http/pprof"
)

Is this on purpose? As far as I know it's a good practice to have a comment explaining why an import is being ignored and it's more readable on the same line.

Regression in golangci-lint

We recently update golangci-lint and it broke gci, forcing us to disable it.

To reproduce:

istio/istio@3a245f8

$ golangci-lint run --fix -c ./common/config/.golangci-format.yml istioctl/pkg/util/proto/messageslice.go
istioctl/pkg/util/proto/messageslice.go:21:1: Expected '\t', Found '\n' at istioctl/pkg/util/proto/messageslice.go[line 21,col 1] (gci)

^

Can also run in our docker build:

./common/scripts/run.sh golangci-lint run --fix -c ./common/config/.golangci-format.yml istioctl/pkg/util/proto/messageslice.go

Error: an error occurred while trying to parse imports: Found non-letter character '.' in Alias: .

When gci try to analyze a file that use dot imports, an error is occurred.

Consider the following file:

package main

import (
	. "fmt"
)

func main() {
	Println("test")
}

When running using the following command:
gci --write --local . testdata main.go

This error is returned:

Using the old parameters is deprecated, please use the named subcommands!
2022/02/01 09:05:07 Loaded File: main.go
Error: an error occured while trying to parse imports: Found non-letter character '.' in Alias: .
Usage:
  gci [-diff | -write] [-local localPackageURLs] path... [flags]
  gci [command]

Available Commands:
  completion  Generate the autocompletion script for the specified shell
  diff        Prints a git style diff to STDOUT
  help        Help about any command
  print       Outputs the formatted file to STDOUT
  write       Formats the specified files in-place

Flags:
  -d, --diff            display diffs instead of rewriting files
  -h, --help            help for gci
  -l, --local strings   put imports beginning with this string after 3rd-party packages, separate imports by comma
  -v, --version         version for gci
  -w, --write           write result to (source) file instead of stdout

Use "gci [command] --help" for more information about a command.

I'm using the latest version:

$ gci --version
gci version 0.3

Using the previous version 0.2.9 the analysis finish wit successfull:

$ go install github.com/daixiang0/[email protected]
$ gci -w -local . testdata main.go

gci error not clear

the error

pass.Reportf(file.Pos(diffIdx), "Expected %s, Found %s at %s[line %d,col %d]", formattedRune, fileRune, filePath, diffPos.Line, diffPos.Column)

jumped for me when I had

import (
        "fmt"
        "reflect"

        "github.com/go-pg/pg/v10"
        "github.com/go-pg/pg/v10/orm"

        "github.com/spf13/cobra"
)

and the fix was to join the 3 github imports.

could we catch this error up somewhere so the error would be more along the lines "imports are not joined together, please remove newline in line X" ?

the error is

file.go:X:${LAST_CHAR_IN_LINE}: Expected '\t', Found '\n' at file.go[line X col ${LAST_CHAR_IN_LINE}] (gci)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.