Skip to content

Commit 3a3ed6e

Browse files
added import chack test to tui
1 parent bbef260 commit 3a3ed6e

1 file changed

Lines changed: 79 additions & 0 deletions

File tree

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
// Copyright (c) 2026 Keymaster Team
2+
// Keymaster - SSH key management system
3+
// This source code is licensed under the MIT license found in the LICENSE file.
4+
package tui_test
5+
6+
import (
7+
"bytes"
8+
"encoding/json"
9+
"os/exec"
10+
"regexp"
11+
"testing"
12+
)
13+
14+
type Package struct {
15+
ImportPath string `json:"ImportPath"`
16+
Imports []string `json:"Imports"`
17+
}
18+
19+
func TestPreventUnwantedImports(t *testing.T) {
20+
blackList := map[string]string{
21+
regexp.QuoteMeta("github.com/toeirei/keymaster/") + ".+": "no keymaster imports except for the whitelisted allowed",
22+
}
23+
24+
whiteList := []string{
25+
regexp.QuoteMeta("github.com/toeirei/keymaster/ui/tui") + ".*",
26+
regexp.QuoteMeta("github.com/toeirei/keymaster/util") + ".*",
27+
regexp.QuoteMeta("github.com/toeirei/keymaster/tags") + ".*",
28+
regexp.QuoteMeta("github.com/toeirei/keymaster/client") + ".*",
29+
regexp.QuoteMeta("github.com/toeirei/keymaster/i18n"),
30+
regexp.QuoteMeta("github.com/toeirei/keymaster/buildvars"),
31+
}
32+
33+
cmd := exec.Command("go", "list", "-json", "./...")
34+
var stdout bytes.Buffer
35+
cmd.Stdout = &stdout
36+
37+
if err := cmd.Run(); err != nil {
38+
t.Fatalf("failed to execute 'go list': %v", err)
39+
}
40+
41+
decoder := json.NewDecoder(&stdout)
42+
for decoder.More() {
43+
var pkg Package
44+
if err := decoder.Decode(&pkg); err != nil {
45+
t.Fatalf("failed to decode 'go list' output: %v", err)
46+
}
47+
48+
t.Run(pkg.ImportPath, func(t *testing.T) {
49+
for _, pkgImport := range pkg.Imports {
50+
var blacklisted bool
51+
var reason string
52+
53+
for regexpStr, _reason := range blackList {
54+
blacklisted = regexp.MustCompile(regexpStr).MatchString(pkgImport)
55+
if blacklisted {
56+
reason = _reason
57+
break
58+
}
59+
}
60+
61+
if blacklisted {
62+
var whitelisted bool
63+
64+
for _, regexpStr := range whiteList {
65+
whitelisted = regexp.MustCompile(regexpStr).MatchString(pkgImport)
66+
if whitelisted {
67+
break
68+
}
69+
}
70+
71+
if !whitelisted {
72+
t.Errorf("FAIL: Package %q imports banned package %q. Reason: %s", pkg.ImportPath, pkgImport, reason)
73+
return
74+
}
75+
}
76+
}
77+
})
78+
}
79+
}

0 commit comments

Comments
 (0)