Created
November 23, 2019 21:37
-
-
Save steevehook/be75b595e7980811c765fd9f48cb9fa6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"fmt" | |
"os" | |
"path/filepath" | |
"strings" | |
) | |
func main() { | |
dir, err := os.Getwd() | |
if err != nil { | |
panic(err) | |
} | |
project := strings.Split(dir, "/src/")[1] | |
project = strings.Join(strings.SplitN(project, "/", 3)[:3], "/") | |
var invalidImports []string | |
err = filepath.Walk(".", func(path string, info os.FileInfo, err error) error { | |
if strings.Contains(path, "vendor/") { | |
return filepath.SkipDir | |
} | |
if info.IsDir() { | |
return nil | |
} | |
if !strings.HasSuffix(info.Name(), ".go") { | |
return nil | |
} | |
f, err := os.Open(path) | |
if err != nil { | |
return err | |
} | |
defer f.Close() | |
var prevGroup string | |
var importGroups string | |
started := false | |
reader := bufio.NewReader(f) | |
for err == nil { | |
var line string | |
line, err = reader.ReadString('\n') | |
if !started { | |
started = strings.HasPrefix(line, "import (") | |
continue | |
} | |
if strings.HasSuffix(line, ")\n") { | |
break | |
} | |
iType := identifyImportType(project, line) | |
if prevGroup != iType { | |
importGroups += iType | |
} | |
prevGroup = iType | |
} | |
if !isValidImportGroups(importGroups) { | |
invalidImports = append(invalidImports, path) | |
} | |
return nil | |
}) | |
if err != nil { | |
panic(err) | |
} | |
if len(invalidImports) == 0 { | |
fmt.Println("good boy") | |
return | |
} | |
fmt.Println("fix your imports, you son of a bitch") | |
for _, i := range invalidImports { | |
fmt.Println(i) | |
} | |
} | |
func identifyImportType(project, imp string) string { | |
imp = strings.TrimSpace(imp) | |
aliasAndImport := strings.Split(imp, " ") | |
imp = aliasAndImport[len(aliasAndImport)-1] | |
switch { | |
case imp == "": | |
return " " | |
case !strings.Contains(imp, "."): | |
return "STD" | |
case strings.HasPrefix(imp, "\""+project): | |
return "LOC" | |
default: | |
return "EXT" | |
} | |
} | |
func isValidImportGroups(importGroups string) bool { | |
if strings.HasSuffix(importGroups, " ") || strings.HasSuffix(importGroups, " ") { | |
return false | |
} | |
return strings.Contains("STD EXT LOC||STD LOC", importGroups) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment