package promptkit_test import ( "go/ast" "go/parser" "go/token" "io/fs" "os" "path/filepath" "strconv" "strings" "testing" ) const formerModulePath = "gitea.maximumdirect.net/eric/" + "scrip" + "torium" func TestRepositoryDoesNotImportFormerModule(t *testing.T) { violations, err := findFormerModuleImports(".") if err != nil { t.Fatalf("inspect repository imports: %v", err) } if len(violations) > 0 { t.Fatalf("repository imports the former module:\n%s", strings.Join(violations, "\n")) } } func TestFormerModuleGuardFindsNestedImport(t *testing.T) { root := t.TempDir() nested := filepath.Join(root, "nested", "package") if err := os.MkdirAll(nested, 0o755); err != nil { t.Fatalf("create nested package: %v", err) } sourcePath := filepath.Join(nested, "violation.go") source := "package nested\n\nimport _ " + strconv.Quote(formerModulePath+"/internal/domain") + "\n" if err := os.WriteFile(sourcePath, []byte(source), 0o600); err != nil { t.Fatalf("write nested source: %v", err) } violations, err := findFormerModuleImports(root) if err != nil { t.Fatalf("inspect nested imports: %v", err) } if len(violations) != 1 { t.Fatalf("violations = %v, want one nested import", violations) } if !strings.Contains(violations[0], "violation.go") || !strings.Contains(violations[0], formerModulePath+"/internal/domain") { t.Fatalf("violation = %q, want file and import path", violations[0]) } } func findFormerModuleImports(root string) ([]string, error) { var violations []string err := filepath.WalkDir(root, func(path string, entry fs.DirEntry, walkErr error) error { if walkErr != nil { return walkErr } if entry.IsDir() { switch entry.Name() { case ".git", "generated", "vendor": return filepath.SkipDir } return nil } if filepath.Ext(path) != ".go" { return nil } file, err := parser.ParseFile(token.NewFileSet(), path, nil, parser.ImportsOnly|parser.ParseComments) if err != nil { return err } if ast.IsGenerated(file) { return nil } for _, spec := range file.Imports { importPath, err := strconv.Unquote(spec.Path.Value) if err != nil { return err } if importPath == formerModulePath || strings.HasPrefix(importPath, formerModulePath+"/") { violations = append(violations, path+": "+importPath) } } return nil }) return violations, err }