From d00c049af023e89060e497ccf48e646d31fe6ed0 Mon Sep 17 00:00:00 2001 From: Martin Kuntz Jacobsen Date: Wed, 28 Oct 2026 14:07:29 +0100 Subject: [PATCH] gazelle/javascript,typescript: resolve test config setup files as deps Literal setupFiles, setupFilesAfterEnv, globalSetup, globalTeardown, and snapshotSerializers entries in jest, vitest, and vite configs now add the named modules to the config's rule. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011u9TXHDZrfmzFQ2WT8QAKK --- gazelle/common/BUILD.bazel | 2 + gazelle/common/jsscan.go | 18 ++- gazelle/common/jstestconfig.go | 152 ++++++++++++++++++ gazelle/common/jstestconfig_test.go | 67 ++++++++ gazelle/javascript/BUILD.bazel | 1 + gazelle/javascript/lang.go | 2 +- .../javascript/testdata/test_config/README.md | 4 + .../javascript/testdata/test_config/WORKSPACE | 0 .../testdata/test_config/pkg/demo/BUILD.in | 0 .../testdata/test_config/pkg/demo/BUILD.out | 20 +++ .../test_config/pkg/demo/jest.config.js | 4 + .../testdata/test_config/pkg/demo/setup.js | 1 + .../testdata/test_config/pkg/demo/teardown.js | 1 + gazelle/typescript/BUILD.bazel | 1 + gazelle/typescript/lang.go | 2 +- .../typescript/testdata/test_config/README.md | 4 + .../typescript/testdata/test_config/WORKSPACE | 0 .../testdata/test_config/pkg/demo/BUILD.in | 1 + .../testdata/test_config/pkg/demo/BUILD.out | 22 +++ .../test_config/pkg/demo/global_setup.ts | 1 + .../testdata/test_config/pkg/demo/setup.ts | 1 + .../test_config/pkg/demo/vitest.config.ts | 8 + 22 files changed, 309 insertions(+), 3 deletions(-) create mode 100644 gazelle/common/jstestconfig.go create mode 100644 gazelle/common/jstestconfig_test.go create mode 100644 gazelle/javascript/testdata/test_config/README.md create mode 100644 gazelle/javascript/testdata/test_config/WORKSPACE create mode 100644 gazelle/javascript/testdata/test_config/pkg/demo/BUILD.in create mode 100644 gazelle/javascript/testdata/test_config/pkg/demo/BUILD.out create mode 100644 gazelle/javascript/testdata/test_config/pkg/demo/jest.config.js create mode 100644 gazelle/javascript/testdata/test_config/pkg/demo/setup.js create mode 100644 gazelle/javascript/testdata/test_config/pkg/demo/teardown.js create mode 100644 gazelle/typescript/testdata/test_config/README.md create mode 100644 gazelle/typescript/testdata/test_config/WORKSPACE create mode 100644 gazelle/typescript/testdata/test_config/pkg/demo/BUILD.in create mode 100644 gazelle/typescript/testdata/test_config/pkg/demo/BUILD.out create mode 100644 gazelle/typescript/testdata/test_config/pkg/demo/global_setup.ts create mode 100644 gazelle/typescript/testdata/test_config/pkg/demo/setup.ts create mode 100644 gazelle/typescript/testdata/test_config/pkg/demo/vitest.config.ts diff --git a/gazelle/common/BUILD.bazel b/gazelle/common/BUILD.bazel index 2d5e4899d3..447a627d8d 100644 --- a/gazelle/common/BUILD.bazel +++ b/gazelle/common/BUILD.bazel @@ -38,6 +38,7 @@ go_library( "ignore.go", "jsresolve.go", "jsscan.go", + "jstestconfig.go", "jvmmask.go", "jvmplatform.go", "langcore.go", @@ -109,6 +110,7 @@ go_test( "errors_test.go", "external_test.go", "ignore_test.go", + "jstestconfig_test.go", "manifest_test.go", "naming_test.go", "remedy_test.go", diff --git a/gazelle/common/jsscan.go b/gazelle/common/jsscan.go index b2c9c709ca..3ea463a3bc 100644 --- a/gazelle/common/jsscan.go +++ b/gazelle/common/jsscan.go @@ -108,8 +108,24 @@ func isRelativeSpec(spec string) bool { } func ParseImportRefs(src []byte, dir string) []ImportRef { + return parseRefs(src, dir, Scan) +} + +// ParseSourceImportRefs is ParseImportRefs plus the setup modules a Jest, +// Vitest, or Vite config named name declares. +func ParseSourceImportRefs(name string, src []byte, dir string) []ImportRef { + if !IsJSTestConfig(name) { + return ParseImportRefs(src, dir) + } + return parseRefs(src, dir, func(src []byte, add func(string)) { + Scan(src, add) + ScanJSTestConfig(src, add) + }) +} + +func parseRefs(src []byte, dir string, scan func([]byte, func(string))) []ImportRef { refs := make(map[string]ImportRef) - Scan(src, func(spec string) { + scan(src, func(spec string) { spec = strings.TrimSpace(spec) if spec == "" { return diff --git a/gazelle/common/jstestconfig.go b/gazelle/common/jstestconfig.go new file mode 100644 index 0000000000..bf6741ff81 --- /dev/null +++ b/gazelle/common/jstestconfig.go @@ -0,0 +1,152 @@ +package common + +import ( + "path" + "strings" +) + +var jsTestConfigKeys = map[string]bool{ + "setupFiles": true, + "setupFilesAfterEnv": true, + "globalSetup": true, + "globalTeardown": true, + "snapshotSerializers": true, +} + +// IsJSTestConfig reports whether name is a Jest, Vitest, or Vite config file. +func IsJSTestConfig(name string) bool { + base := path.Base(name) + stem := strings.TrimSuffix(base, path.Ext(base)) + if !strings.HasSuffix(stem, ".config") || !HasExt(base, JSModuleExts) { + return false + } + switch strings.TrimSuffix(stem, ".config") { + case "jest", "vitest", "vite": + return true + } + return false +} + +// ScanJSTestConfig reports the literal module specs of setupFiles, +// setupFilesAfterEnv, globalSetup, globalTeardown, and snapshotSerializers. +// A leading / is read as the config's own directory. +func ScanJSTestConfig(src []byte, add func(string)) { + n := len(src) + addSpec := func(spec string) { + if rest, ok := strings.CutPrefix(spec, "/"); ok { + spec = "./" + rest + } + if spec != "" && !strings.Contains(spec, "<") { + add(spec) + } + } + i := 0 + for i < n { + c := src[i] + if np, ok := skipComment(src, i); ok { + i = np + continue + } + var key string + next := i + 1 + switch { + case c == '\'' || c == '"': + s, np, ok := parseQuoted(src, i) + if !ok { + i = np + continue + } + key, next = s, np + case c == '`': + i = skipTemplate(src, i) + continue + case c == '/' && isRegexStart(src, i): + i = skipRegex(src, i) + continue + case isIdentStart(c): + j := i + 1 + for j < n && isIdentChar(src[j]) { + j++ + } + if isPrecededByDot(src, i) { + i = j + continue + } + key, next = string(src[i:j]), j + } + i = next + if !jsTestConfigKeys[key] { + continue + } + p := skipTrivia(src, next) + if p >= n || src[p] != ':' { + continue + } + p = skipTrivia(src, p+1) + if p >= n { + return + } + switch src[p] { + case '\'', '"': + if s, np, ok := parseQuoted(src, p); ok { + addSpec(s) + i = np + } + case '[': + i = scanStringArray(src, p+1, addSpec) + } + } +} + +// scanStringArray reports the string literal elements of an array starting +// after its '[' and skips any other element. +func scanStringArray(src []byte, p int, add func(string)) int { + n := len(src) + depth := 0 + sep := true + for p < n { + p = skipTrivia(src, p) + if p >= n { + return p + } + c := src[p] + if c == ',' && depth == 0 { + sep = true + p++ + continue + } + wasSep := sep + sep = false + switch c { + case '\'', '"': + s, np, ok := parseQuoted(src, p) + if !ok { + return np + } + if depth == 0 && wasSep { + q := skipTrivia(src, np) + if q < n && (src[q] == ',' || src[q] == ']') { + add(s) + } + } + p = np + case '`': + p = skipTemplate(src, p) + case '[', '(', '{': + depth++ + p++ + case ')', '}': + depth-- + p++ + case ']': + if depth == 0 { + return p + 1 + } + depth-- + p++ + default: + p++ + } + } + return p +} diff --git a/gazelle/common/jstestconfig_test.go b/gazelle/common/jstestconfig_test.go new file mode 100644 index 0000000000..95124a1fef --- /dev/null +++ b/gazelle/common/jstestconfig_test.go @@ -0,0 +1,67 @@ +package common + +import ( + "reflect" + "testing" +) + +func TestIsJSTestConfig(t *testing.T) { + for _, name := range []string{"jest.config.js", "jest.config.ts", "jest.config.cjs", "vitest.config.mts", "vite.config.ts", "pkg/jest.config.mjs"} { + if !IsJSTestConfig(name) { + t.Errorf("IsJSTestConfig(%q) = false, want true", name) + } + } + for _, name := range []string{"jest.config.json", "jest.setup.js", "config.js", "webpack.config.js", "my.jest.config.js", "jest.js"} { + if IsJSTestConfig(name) { + t.Errorf("IsJSTestConfig(%q) = true, want false", name) + } + } +} + +func TestScanJSTestConfig(t *testing.T) { + cases := []struct { + name string + source string + want []string + }{ + {"empty", "", nil}, + {"jestArray", "module.exports = { setupFiles: ['./a.js', \"./b\"] };\n", []string{"./a.js", "./b"}}, + {"afterEnv", "export default { setupFilesAfterEnv: ['@testing-library/jest-dom'] };\n", []string{"@testing-library/jest-dom"}}, + {"globalString", "export default { globalSetup: './gs.ts', globalTeardown: \"./gt.ts\" };\n", []string{"./gs.ts", "./gt.ts"}}, + {"quotedKey", "{ \"setupFiles\": [\"./a\"] }\n", []string{"./a"}}, + {"rootDir", "{ setupFiles: ['/setup/a.js'] }\n", []string{"./setup/a.js"}}, + {"otherToken", "{ setupFiles: ['/../.js'] }\n", nil}, + {"vitestNested", "export default defineConfig({ test: { setupFiles: ['./vs.ts'], globalSetup: ['./g.ts'] } });\n", []string{"./vs.ts", "./g.ts"}}, + {"trailingComma", "{ setupFiles: [\n './a', // first\n './b',\n] }\n", []string{"./a", "./b"}}, + {"mixed", "{ setupFiles: ['./a', path.join(dir, './x'), x + './y', './y' + x, `./t`, ...rest, './b'] }\n", []string{"./a", "./b"}}, + {"dynamic", "{ setupFiles: files, globalSetup: resolve('./g') }\n", nil}, + {"memberKey", "config.setupFiles = ['./a'];\n", nil}, + {"memberLookup", "x = { a: cfg.setupFiles };\n", nil}, + {"serializers", "{ snapshotSerializers: ['enzyme-to-json/serializer'] }\n", []string{"enzyme-to-json/serializer"}}, + {"otherKeys", "{ testMatch: ['./a'], reporters: ['./r'] }\n", nil}, + {"inString", "const s = 'setupFiles: [\"./a\"]';\n", nil}, + {"inComment", "// setupFiles: ['./a']\n/* globalSetup: './g' */\n", nil}, + {"empty string", "{ globalSetup: '' }\n", nil}, + } + for _, tc := range cases { + var got []string + ScanJSTestConfig([]byte(tc.source), func(s string) { got = append(got, s) }) + if !reflect.DeepEqual(got, tc.want) { + t.Errorf("%s: ScanJSTestConfig = %q, want %q", tc.name, got, tc.want) + } + } +} + +func TestParseSourceImportRefs(t *testing.T) { + src := []byte("import { defineConfig } from 'vitest/config';\nexport default defineConfig({ test: { setupFiles: ['./setup.ts'] } });\n") + want := []ImportRef{ + {Spec: "./setup.ts", Root: "pkg/setup", ModuleExt: ".ts", Relative: true}, + {Spec: "vitest/config", Root: "vitest/config"}, + } + if got := ParseSourceImportRefs("vitest.config.ts", src, "pkg"); !reflect.DeepEqual(got, want) { + t.Errorf("ParseSourceImportRefs = %+v, want %+v", got, want) + } + if got := ParseSourceImportRefs("app.ts", src, "pkg"); !reflect.DeepEqual(got, want[1:]) { + t.Errorf("ParseSourceImportRefs(app.ts) = %+v, want %+v", got, want[1:]) + } +} diff --git a/gazelle/javascript/BUILD.bazel b/gazelle/javascript/BUILD.bazel index b74e74f1e3..fee2e5c880 100644 --- a/gazelle/javascript/BUILD.bazel +++ b/gazelle/javascript/BUILD.bazel @@ -52,6 +52,7 @@ real_source_target( markdown_srcs = [ "testdata/entries/README.md", "testdata/source_only/README.md", + "testdata/test_config/README.md", ], tags = ["corpus"], ) diff --git a/gazelle/javascript/lang.go b/gazelle/javascript/lang.go index eaee7af388..843f81d2a1 100644 --- a/gazelle/javascript/lang.go +++ b/gazelle/javascript/lang.go @@ -138,7 +138,7 @@ func generateRules(args language.GenerateArgs, _ map[string]rule.KindInfo, rep c } p := plan{name: name, src: src, test: IsTestFile(src)} p.entry = !p.test && IsEntryFile(src) - p.refs = common.JSImportRefs(common.ParseImportRefs(content, path.Join(args.Rel, path.Dir(src)))) + p.refs = common.JSImportRefs(common.ParseSourceImportRefs(src, content, path.Join(args.Rel, path.Dir(src)))) plans = append(plans, p) } if rep.Failed() { diff --git a/gazelle/javascript/testdata/test_config/README.md b/gazelle/javascript/testdata/test_config/README.md new file mode 100644 index 0000000000..0b0e9a39a4 --- /dev/null +++ b/gazelle/javascript/testdata/test_config/README.md @@ -0,0 +1,4 @@ +# Test config setup files + +Verifies that literal `setupFilesAfterEnv` entries in a Jest config, including +`` paths, become deps of the config's library. diff --git a/gazelle/javascript/testdata/test_config/WORKSPACE b/gazelle/javascript/testdata/test_config/WORKSPACE new file mode 100644 index 0000000000..e69de29bb2 diff --git a/gazelle/javascript/testdata/test_config/pkg/demo/BUILD.in b/gazelle/javascript/testdata/test_config/pkg/demo/BUILD.in new file mode 100644 index 0000000000..e69de29bb2 diff --git a/gazelle/javascript/testdata/test_config/pkg/demo/BUILD.out b/gazelle/javascript/testdata/test_config/pkg/demo/BUILD.out new file mode 100644 index 0000000000..76c3dc49de --- /dev/null +++ b/gazelle/javascript/testdata/test_config/pkg/demo/BUILD.out @@ -0,0 +1,20 @@ +load("@rules_dx//javascript/rules:defs.bzl", "javascript_library") + +javascript_library( + name = "jest_config", + srcs = ["jest.config.js"], + deps = [ + ":setup", + ":teardown", + ], +) + +javascript_library( + name = "setup", + srcs = ["setup.js"], +) + +javascript_library( + name = "teardown", + srcs = ["teardown.js"], +) diff --git a/gazelle/javascript/testdata/test_config/pkg/demo/jest.config.js b/gazelle/javascript/testdata/test_config/pkg/demo/jest.config.js new file mode 100644 index 0000000000..4acc92f074 --- /dev/null +++ b/gazelle/javascript/testdata/test_config/pkg/demo/jest.config.js @@ -0,0 +1,4 @@ +module.exports = { + setupFilesAfterEnv: ["/setup.js"], + globalTeardown: "./teardown.js", +}; diff --git a/gazelle/javascript/testdata/test_config/pkg/demo/setup.js b/gazelle/javascript/testdata/test_config/pkg/demo/setup.js new file mode 100644 index 0000000000..f1a3e39fff --- /dev/null +++ b/gazelle/javascript/testdata/test_config/pkg/demo/setup.js @@ -0,0 +1 @@ +globalThis.ready = true; diff --git a/gazelle/javascript/testdata/test_config/pkg/demo/teardown.js b/gazelle/javascript/testdata/test_config/pkg/demo/teardown.js new file mode 100644 index 0000000000..81aff321c0 --- /dev/null +++ b/gazelle/javascript/testdata/test_config/pkg/demo/teardown.js @@ -0,0 +1 @@ +module.exports = async () => {}; diff --git a/gazelle/typescript/BUILD.bazel b/gazelle/typescript/BUILD.bazel index 5c2cf38101..5a76313189 100644 --- a/gazelle/typescript/BUILD.bazel +++ b/gazelle/typescript/BUILD.bazel @@ -52,6 +52,7 @@ real_source_target( markdown_srcs = [ "testdata/entries/README.md", "testdata/source_only/README.md", + "testdata/test_config/README.md", "testdata/tsconfig_paths/README.md", ], tags = ["corpus"], diff --git a/gazelle/typescript/lang.go b/gazelle/typescript/lang.go index 7ebce490ba..4481eef16b 100644 --- a/gazelle/typescript/lang.go +++ b/gazelle/typescript/lang.go @@ -249,7 +249,7 @@ func generateRules(args language.GenerateArgs, _ map[string]rule.KindInfo, rep c p := plan{name: name, src: src, test: IsTestFile(src)} p.decl = IsDeclaration(src) p.entry = !p.test && !p.decl && IsEntryFile(src) - p.refs = common.JSImportRefs(common.ParseImportRefs(content, path.Join(args.Rel, path.Dir(src)))) + p.refs = common.JSImportRefs(common.ParseSourceImportRefs(src, content, path.Join(args.Rel, path.Dir(src)))) plans = append(plans, p) } if rep.Failed() { diff --git a/gazelle/typescript/testdata/test_config/README.md b/gazelle/typescript/testdata/test_config/README.md new file mode 100644 index 0000000000..89789b720b --- /dev/null +++ b/gazelle/typescript/testdata/test_config/README.md @@ -0,0 +1,4 @@ +# Test config setup files + +Verifies that literal `setupFiles` and `globalSetup` entries in a Vitest +config become deps of the config's project. Dynamic entries add no deps. diff --git a/gazelle/typescript/testdata/test_config/WORKSPACE b/gazelle/typescript/testdata/test_config/WORKSPACE new file mode 100644 index 0000000000..e69de29bb2 diff --git a/gazelle/typescript/testdata/test_config/pkg/demo/BUILD.in b/gazelle/typescript/testdata/test_config/pkg/demo/BUILD.in new file mode 100644 index 0000000000..86318bc893 --- /dev/null +++ b/gazelle/typescript/testdata/test_config/pkg/demo/BUILD.in @@ -0,0 +1 @@ +# gazelle:dx_ignore_import typescript @testing-library/jest-dom diff --git a/gazelle/typescript/testdata/test_config/pkg/demo/BUILD.out b/gazelle/typescript/testdata/test_config/pkg/demo/BUILD.out new file mode 100644 index 0000000000..61319a3e9a --- /dev/null +++ b/gazelle/typescript/testdata/test_config/pkg/demo/BUILD.out @@ -0,0 +1,22 @@ +load("@rules_dx//typescript/rules:defs.bzl", "typescript_project") + +# gazelle:dx_ignore_import typescript @testing-library/jest-dom + +typescript_project( + name = "global_setup", + srcs = ["global_setup.ts"], +) + +typescript_project( + name = "setup", + srcs = ["setup.ts"], +) + +typescript_project( + name = "vitest_config", + srcs = ["vitest.config.ts"], + deps = [ + ":global_setup", + ":setup", + ], +) diff --git a/gazelle/typescript/testdata/test_config/pkg/demo/global_setup.ts b/gazelle/typescript/testdata/test_config/pkg/demo/global_setup.ts new file mode 100644 index 0000000000..dcf2fe126e --- /dev/null +++ b/gazelle/typescript/testdata/test_config/pkg/demo/global_setup.ts @@ -0,0 +1 @@ +export default function setup(): void {} diff --git a/gazelle/typescript/testdata/test_config/pkg/demo/setup.ts b/gazelle/typescript/testdata/test_config/pkg/demo/setup.ts new file mode 100644 index 0000000000..fa3dfc9b26 --- /dev/null +++ b/gazelle/typescript/testdata/test_config/pkg/demo/setup.ts @@ -0,0 +1 @@ +export const ready = true; diff --git a/gazelle/typescript/testdata/test_config/pkg/demo/vitest.config.ts b/gazelle/typescript/testdata/test_config/pkg/demo/vitest.config.ts new file mode 100644 index 0000000000..e8d4417ae7 --- /dev/null +++ b/gazelle/typescript/testdata/test_config/pkg/demo/vitest.config.ts @@ -0,0 +1,8 @@ +const extra: string[] = []; + +export default { + test: { + setupFiles: ["./setup.ts", "@testing-library/jest-dom", ...extra], + globalSetup: "./global_setup.ts", + }, +};