From 0bdb3335bdaaf0939a3d17813a49780c91dcf0d1 Mon Sep 17 00:00:00 2001 From: Vyacheslav Pryimak Date: Fri, 5 Feb 2021 19:58:53 +0200 Subject: [PATCH] #35 Remove empty import node if present --- reviser/reviser.go | 35 +++++++++++++++++++++++++++++++++-- reviser/reviser_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 2 deletions(-) diff --git a/reviser/reviser.go b/reviser/reviser.go index 674d79a..32c25b6 100644 --- a/reviser/reviser.go +++ b/reviser/reviser.go @@ -172,10 +172,10 @@ func skipPackageAlias(pkg string) string { return strings.Trim(pkg, `"`) } -func generateFile(fset *token.FileSet, file *ast.File) ([]byte, error) { +func generateFile(fset *token.FileSet, f *ast.File) ([]byte, error) { var output []byte buffer := bytes.NewBuffer(output) - if err := printer.Fprint(buffer, fset, file); err != nil { + if err := printer.Fprint(buffer, fset, f); err != nil { return nil, err } @@ -210,6 +210,37 @@ func fixImports( } clearImportDocs(f, importsPositions) + removeEmptyImportNode(f) +} + +func removeEmptyImportNode(f *ast.File) { + var ( + decls []ast.Decl + hasImports bool + ) + + for _, decl := range f.Decls { + dd, ok := decl.(*ast.GenDecl) + if !ok { + decls = append(decls, decl) + + continue + } + + if dd.Tok == token.IMPORT && len(dd.Specs) > 0 { + hasImports = true + + break + } + + if dd.Tok != token.IMPORT { + decls = append(decls, decl) + } + } + + if !hasImports { + f.Decls = decls + } } func rebuildImports( diff --git a/reviser/reviser_test.go b/reviser/reviser_test.go index 249f0ed..1bd7039 100644 --- a/reviser/reviser_test.go +++ b/reviser/reviser_test.go @@ -552,6 +552,33 @@ const webDirectory = "web" wantChange: false, wantErr: false, }, + { + name: "cleanup empty import block", + args: args{ + projectName: "github.com/incu6us/goimports-reviser", + filePath: "./testdata/example.go", + fileContent: `// Some comments are here +package testdata + +import ( + "fmt" +) + +// nolint:gomnd +func main(){ +} +`, + }, + want: `// Some comments are here +package testdata + +// nolint:gomnd +func main() { +} +`, + wantChange: true, + wantErr: false, + }, } for _, tt := range tests {