Repository: daixiang0/gci (go)

Issue:
Duplicate imports are reordered back and forth (`gci write` not idempotent)
I am using gci to format [this Go file](https://github.com/juju/juju/blob/41a6baeb0c4c6c76891847aa72deb08f44aacd4e/cmd/juju/romulus/sla/sla_test.go). Note that it has duplicate imports:
```go
import (
        ...
	"github.com/juju/testing"
	jujutesting "github.com/juju/testing"
        ...
)
```
When I run
```
gci write -s standard -s default -s "Prefix(github.com/juju/juju)" --skip-generated \
  cmd/juju/romulus/sla/sla_test.go
```
it will continue to reorder these imports. i.e. after one run they will be in the reverse order
```go
import (
        ...
	jujutesting "github.com/juju/testing"
	"github.com/juju/testing"
        ...
)
```
If I run it again, they will return to the original order. If I run it again, they will reverse again, and so forth.

This is observed on gci v0.6.2. Obviously I would expect `gci write` to be idempotent. I am struggling to isolate a MWE - I've tried a few simpler Go files and haven't observed this behaviour.

Pull request description:
fix issue when duplicate imports
Fix #98

Signed-off-by: Loong <loong.dai@intel.com>

Patch:
diff --git a/pkg/parse/parse.go b/pkg/parse/parse.go
index df0af3d..d84ed13 100644
--- a/pkg/parse/parse.go
+++ b/pkg/parse/parse.go
@@ -20,6 +20,10 @@ func (l ImportList) Len() int {
 }
 
 func (l ImportList) Less(i, j int) bool {
+	if strings.Compare(l[i].Path, l[j].Path) == 0 {
+		return strings.Compare(l[i].Name, l[j].Name) < 0
+	}
+
 	return strings.Compare(l[i].Path, l[j].Path) < 0
 }
 


Test patch:
diff --git a/pkg/gci/internal/testdata/duplicate-imports.cfg.yaml b/pkg/gci/internal/testdata/duplicate-imports.cfg.yaml
new file mode 100644
index 0000000..e666ab9
--- /dev/null
+++ b/pkg/gci/internal/testdata/duplicate-imports.cfg.yaml
@@ -0,0 +1,4 @@
+sections:
+  - Standard
+  - Default
+  - Prefix(github.com/daixiang0)
diff --git a/pkg/gci/internal/testdata/duplicate-imports.in.go b/pkg/gci/internal/testdata/duplicate-imports.in.go
new file mode 100644
index 0000000..a443a33
--- /dev/null
+++ b/pkg/gci/internal/testdata/duplicate-imports.in.go
@@ -0,0 +1,9 @@
+package main
+import (
+	"fmt"
+
+	g "github.com/golang"
+
+	a "github.com/daixiang0/gci"
+	"github.com/daixiang0/gci"
+)
diff --git a/pkg/gci/internal/testdata/duplicate-imports.out.go b/pkg/gci/internal/testdata/duplicate-imports.out.go
new file mode 100644
index 0000000..fbdf2a1
--- /dev/null
+++ b/pkg/gci/internal/testdata/duplicate-imports.out.go
@@ -0,0 +1,9 @@
+package main
+import (
+	"fmt"
+
+	g "github.com/golang"
+
+	"github.com/daixiang0/gci"
+	a "github.com/daixiang0/gci"
+)