diff --git a/reviser/file.go b/reviser/file.go index 1c7ff1c..0a993cc 100644 --- a/reviser/file.go +++ b/reviser/file.go @@ -378,19 +378,18 @@ func removeEmptyImportNode(f *ast.File) { func rebuildImports(tok token.Token, commentsMetadata map[string]*commentsMetadata, imports [][]string) []ast.Spec { var specs []ast.Spec - amountOfGroups := len(imports) for i, group := range imports { + if i != 0 && len(group) != 0 && len(specs) != 0 { + spec := &ast.ImportSpec{Path: &ast.BasicLit{Value: "", Kind: token.STRING}} + + specs = append(specs, spec) + } for _, imprt := range group { spec := &ast.ImportSpec{ Path: &ast.BasicLit{Value: importWithComment(imprt, commentsMetadata), Kind: tok}, } specs = append(specs, spec) } - if len(group) != 0 && i != amountOfGroups-1 { - spec := &ast.ImportSpec{Path: &ast.BasicLit{Value: "", Kind: token.STRING}} - - specs = append(specs, spec) - } } return specs diff --git a/reviser/file_test.go b/reviser/file_test.go index 2f250f2..aba10ee 100644 --- a/reviser/file_test.go +++ b/reviser/file_test.go @@ -270,7 +270,27 @@ import ( wantChange: true, wantErr: false, }, + { + name: "success with single std deps only", + args: args{ + projectName: "github.com/incu6us/goimports-reviser", + filePath: "./testdata/example.go", + fileContent: `package testdata + +import "log" + +// nolint:gomnd +`, + }, + want: `package testdata + +import "log" +// nolint:gomnd +`, + wantChange: false, + wantErr: false, + }, { name: "success with third-party deps only", args: args{ @@ -297,6 +317,27 @@ import ( wantChange: true, wantErr: false, }, + { + name: "success with single third-party deps", + args: args{ + projectName: "github.com/incu6us/goimports-reviser", + filePath: "./testdata/example.go", + fileContent: `package testdata + +import "golang.org/x/exp/slices" + +// nolint:gomnd +`, + }, + want: `package testdata + +import "golang.org/x/exp/slices" + +// nolint:gomnd +`, + wantChange: false, + wantErr: false, + }, { name: "success with project deps only", @@ -510,6 +551,33 @@ import ( "errors" "fmt" ) +`, + wantChange: false, + wantErr: false, + }, + { + name: "preserves cgo import with single std deps", + args: args{ + projectName: "github.com/incu6us/goimports-reviser", + filePath: "./testdata/cgo_example.go", + fileContent: `package testdata + +/* +#include +*/ +import "C" + +import "errors" +`, + }, + want: `package testdata + +/* +#include +*/ +import "C" + +import "errors" `, wantChange: false, wantErr: false,