Skip to content
Open
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
38 changes: 18 additions & 20 deletions packages/foundry/src/findNearest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,26 @@ export function findNearest(
filename: string,
start: string | undefined
): string {
let pathSegments: string[] = [];
let dir: string;
const mainPath = require.main?.path;
if (typeof start === "string") {
if (start[start.length - 1] !== path.sep) {
start += path.sep;
}
start = path.normalize(start);
pathSegments = start.split(path.sep);
} else if (require.main?.path) {
pathSegments = require.main?.path.split(path.sep);
}
if (!pathSegments.length) {
throw new Error(filename + " not found in path");
dir = path.normalize(start);
} else if (mainPath) {
dir = path.normalize(mainPath);
} else {
dir = process.cwd();
}
// remove trailing '' element
pathSegments.pop();
let dir = pathSegments.join(path.sep);
let fullPath = path.join(dir, filename);
if (fs.existsSync(fullPath)) {
return path.normalize(fullPath);
} else {
// pop current dir, recurse one dir closer to root
pathSegments.pop();
return findNearest(filename, pathSegments.join(path.sep));
while (true) {
if (fs.existsSync(fullPath)) {
return path.normalize(fullPath);
}
const parent = path.dirname(dir);
if (parent === dir) {
break;
}
dir = parent;
fullPath = path.join(dir, filename);
}
throw new Error(filename + " not found in path");
}