Skip to content

Commit

Permalink
Merge pull request #41 from incu6us/ISSUE-35
Browse files Browse the repository at this point in the history
#35 Remove empty import node if present
  • Loading branch information
incu6us authored Feb 5, 2021
2 parents a8bb3a7 + 0bdb333 commit ebe652c
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 2 deletions.
35 changes: 33 additions & 2 deletions reviser/reviser.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down Expand Up @@ -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(
Expand Down
27 changes: 27 additions & 0 deletions reviser/reviser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit ebe652c

Please sign in to comment.