Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions gazelle/common/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ go_library(
"ignore.go",
"jsresolve.go",
"jsscan.go",
"jstestconfig.go",
"jvmmask.go",
"jvmplatform.go",
"langcore.go",
Expand Down Expand Up @@ -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",
Expand Down
18 changes: 17 additions & 1 deletion gazelle/common/jsscan.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
152 changes: 152 additions & 0 deletions gazelle/common/jstestconfig.go
Original file line number Diff line number Diff line change
@@ -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 <rootDir>/ 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, "<rootDir>/"); 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
}
67 changes: 67 additions & 0 deletions gazelle/common/jstestconfig_test.go
Original file line number Diff line number Diff line change
@@ -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: ['<rootDir>/setup/a.js'] }\n", []string{"./setup/a.js"}},
{"otherToken", "{ setupFiles: ['<rootDir>/../<x>.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:])
}
}
1 change: 1 addition & 0 deletions gazelle/javascript/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
)
Expand Down
2 changes: 1 addition & 1 deletion gazelle/javascript/lang.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
4 changes: 4 additions & 0 deletions gazelle/javascript/testdata/test_config/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Test config setup files

Verifies that literal `setupFilesAfterEnv` entries in a Jest config, including
`<rootDir>` paths, become deps of the config's library.
Empty file.
Empty file.
20 changes: 20 additions & 0 deletions gazelle/javascript/testdata/test_config/pkg/demo/BUILD.out
Original file line number Diff line number Diff line change
@@ -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"],
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = {
setupFilesAfterEnv: ["<rootDir>/setup.js"],
globalTeardown: "./teardown.js",
};
1 change: 1 addition & 0 deletions gazelle/javascript/testdata/test_config/pkg/demo/setup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
globalThis.ready = true;
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = async () => {};
1 change: 1 addition & 0 deletions gazelle/typescript/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
Expand Down
2 changes: 1 addition & 1 deletion gazelle/typescript/lang.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
4 changes: 4 additions & 0 deletions gazelle/typescript/testdata/test_config/README.md
Original file line number Diff line number Diff line change
@@ -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.
Empty file.
1 change: 1 addition & 0 deletions gazelle/typescript/testdata/test_config/pkg/demo/BUILD.in
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# gazelle:dx_ignore_import typescript @testing-library/jest-dom
22 changes: 22 additions & 0 deletions gazelle/typescript/testdata/test_config/pkg/demo/BUILD.out
Original file line number Diff line number Diff line change
@@ -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",
],
)
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default function setup(): void {}
1 change: 1 addition & 0 deletions gazelle/typescript/testdata/test_config/pkg/demo/setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const ready = true;
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const extra: string[] = [];

export default {
test: {
setupFiles: ["./setup.ts", "@testing-library/jest-dom", ...extra],
globalSetup: "./global_setup.ts",
},
};
Loading