From 6c22dddce6065e9adc9c5520adf6915a130d0dc3 Mon Sep 17 00:00:00 2001 From: Syasusu Date: Mon, 11 Dec 2023 20:51:36 +0100 Subject: [PATCH] [#144] If it is single import, do not convert into an import list --- reviser/file.go | 9 ++++++ reviser/file_test.go | 68 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+) diff --git a/reviser/file.go b/reviser/file.go index 9686895..425b1f1 100644 --- a/reviser/file.go +++ b/reviser/file.go @@ -379,6 +379,15 @@ func rebuildImports(tok token.Token, commentsMetadata map[string]*commentsMetada var specs []ast.Spec amountOfGroups := len(imports) + var importSlice []string + for _, group := range imports { + importSlice = append(importSlice, group...) + } + if len(importSlice) == 1 { + return []ast.Spec{&ast.ImportSpec{ + Path: &ast.BasicLit{Value: importWithComment(importSlice[0], commentsMetadata), Kind: tok}, + }} + } for i, group := range imports { for _, imprt := range group { spec := &ast.ImportSpec{ diff --git a/reviser/file_test.go b/reviser/file_test.go index a621f07..7927e18 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,