Skip to content

Commit 3a139cd

Browse files
committed
fix: handle edge cases where linked file is not found
1 parent 8a4ea3e commit 3a139cd

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

src/index/generateTrees/toFractalTree.ts

+28-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ import { hasCycle } from "./toFractalTree/hasCycle";
77
import { RootOption } from "../shared/RootOption";
88
import { isLinkedFile, linkedFileToOriginal } from "./shared/isLinkedFile";
99
import chalk from "chalk";
10+
import { fileWithoutExtension } from "../shared/fileWithoutExtension";
11+
import { isTestFile } from "./shared/isTestFile";
1012

1113
export function toFractalTree(graph: Graph, entryPoints: string[]) {
1214
const tree: RootOption["tree"] = {};
@@ -130,6 +132,8 @@ export function toFractalTree(graph: Graph, entryPoints: string[]) {
130132
});
131133
}
132134

135+
const treeKeys = Object.keys(tree);
136+
133137
if (linkedFiles.size > 0) {
134138
// const globalTests = [];
135139

@@ -141,7 +145,30 @@ export function toFractalTree(graph: Graph, entryPoints: string[]) {
141145
path.basename(sourceFile)
142146
);
143147
// source file will either be in the current dir or one up
144-
const sourceFilePath = tree[sourceFile] || tree[oneDirUp];
148+
let sourceFilePath = tree[sourceFile] || tree[oneDirUp];
149+
150+
// sometimes the test is add.test.jsx and the source is add.test.js
151+
// so we have to do a linear search to find source key
152+
// we could probably optimize this if needed by doing some work in the fn above
153+
if (!sourceFilePath) {
154+
const sourceFileWithoutFileExtension = fileWithoutExtension(sourceFile);
155+
for (const key of treeKeys) {
156+
if (path.basename(key).startsWith(sourceFileWithoutFileExtension)) {
157+
sourceFilePath = tree[key];
158+
break;
159+
}
160+
}
161+
}
162+
163+
if (!sourceFilePath && isTestFile(linkedFile)) {
164+
// could not link by filename
165+
// so the backup is linking by first relative import
166+
const [firstRelativeImport] = graph[linkedFile];
167+
if (firstRelativeImport) {
168+
sourceFilePath = tree[firstRelativeImport];
169+
}
170+
}
171+
145172
if (!sourceFilePath) {
146173
logger.warn(
147174
`could not find source file that is linked to ${chalk.blueBright(
+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
import path from "path";
2+
3+
export const fileWithoutExtension = (f: string) =>
4+
path.basename(f, path.extname(f));

0 commit comments

Comments
 (0)