Serge Bazanski | 8bd2ab1 | 2021-12-17 17:32:16 +0100 | [diff] [blame] | 1 | package importsort |
| 2 | |
| 3 | import ( |
| 4 | "strings" |
| 5 | |
| 6 | alib "source.monogon.dev/build/analysis/lib" |
| 7 | ) |
| 8 | |
| 9 | // groupClass is the 'class' of a given import path or import group. |
| 10 | type groupClass string |
| 11 | |
| 12 | const ( |
| 13 | // groupClassMixed are import group that contain multiple different classes of |
| 14 | // import paths. |
| 15 | groupClassMixed = "mixed" |
| 16 | // groupClassStdlib is an import path or group that contains only Go standard |
| 17 | // library imports. |
| 18 | groupClassStdlib = "stdlib" |
| 19 | // groupClassGlobal is an import path or group that contains only third-party |
| 20 | // packages, ie. all packages that aren't part of stdlib and aren't local to the |
| 21 | // Monogon codebase. |
| 22 | groupClassGlobal = "global" |
| 23 | // groupClassLocal is an import path or group that contains only package that |
| 24 | // are local to the Monogon codebase. |
| 25 | groupClassLocal = "local" |
| 26 | ) |
| 27 | |
| 28 | // classifyImport returns a groupClass for a given import path. |
| 29 | func classifyImport(path string) groupClass { |
| 30 | if alib.StdlibPackages[path] { |
| 31 | return groupClassStdlib |
| 32 | } |
| 33 | if strings.HasPrefix(path, "source.monogon.dev/") { |
| 34 | return groupClassLocal |
| 35 | } |
| 36 | return groupClassGlobal |
| 37 | } |
| 38 | |
| 39 | // classifyImportGroup returns a groupClass for a list of import paths that are |
| 40 | // part of a single import group. |
| 41 | func classifyImportGroup(paths []string) groupClass { |
| 42 | res := groupClass("") |
| 43 | for _, p := range paths { |
| 44 | if res == "" { |
| 45 | res = classifyImport(p) |
| 46 | continue |
| 47 | } |
| 48 | class := classifyImport(p) |
| 49 | if res != class { |
| 50 | return groupClassMixed |
| 51 | } |
| 52 | } |
| 53 | return res |
| 54 | } |