From 3b54e499c60cdf19e81e4aed8a1176665f3e4803 Mon Sep 17 00:00:00 2001 From: Shintaro Ikeda Date: Wed, 10 Feb 2021 16:09:08 +0900 Subject: [PATCH] Fix bugs for go files that doesnt have import decl --- strictgoimports.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/strictgoimports.go b/strictgoimports.go index f587411..832aa57 100644 --- a/strictgoimports.go +++ b/strictgoimports.go @@ -24,6 +24,18 @@ func (e *Err) Error() string { return fmt.Sprintf("Message: %s. Position: %s", e.Message, e.FileSet.Position(e.Pos).String()) } +func checkTheresImportDecl(f *ast.File) bool { + for _, d := range f.Decls { + switch v := d.(type) { + case *ast.GenDecl: + if v.Tok == token.IMPORT { + return true + } + } + } + return false +} + func Run(filePath, localPaths string) (fileSet *token.FileSet, pos []token.Pos, correctImport string, fixed []byte) { fileSet = token.NewFileSet() f, err := parser.ParseFile(fileSet, filePath, nil, parser.ImportsOnly) @@ -31,6 +43,10 @@ func Run(filePath, localPaths string) (fileSet *token.FileSet, pos []token.Pos, return nil, nil, "", nil } + if !checkTheresImportDecl(f) { + return fileSet, nil, "", nil + } + realLines := buildImportLines(filePath, f, fileSet) idealLines, idealSrc := buildIdeal(filePath, localPaths, fileSet)