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