Skip to content

Commit

Permalink
fix: improve resolve search logic (#697)
Browse files Browse the repository at this point in the history
* fix: improve resolve search logic

* Only progress towards the root if file is not relative.
  • Loading branch information
Jason3S committed Nov 30, 2020
1 parent 0d95869 commit 75be89b
Showing 1 changed file with 27 additions and 1 deletion.
28 changes: 27 additions & 1 deletion packages/cspell-lib/src/util/resolveFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ const testNodeModules = /^node_modules\//;
export function resolveFile(filename: string, relativeTo: string): ResolveFileResult {
filename = filename.replace(/^~/, os.homedir());
const steps: { filename: string; fn: (f: string, r: string) => ResolveFileResult }[] = [
{ filename: filename, fn: tryNodeResolveDefaultPaths },
{ filename: filename, fn: tryNodeResolve },
{ filename: path.resolve(relativeTo, filename), fn: tryResolveExists },
{ filename: path.resolve(filename), fn: tryResolveExists },
Expand All @@ -36,9 +37,34 @@ export function resolveFile(filename: string, relativeTo: string): ResolveFileRe
return { filename: path.resolve(relativeTo, filename), relativeTo, found: false };
}

function tryNodeResolveDefaultPaths(filename: string): ResolveFileResult {
try {
const r = require.resolve(filename);
return { filename: r, relativeTo: undefined, found: true };
} catch (_) {
return { filename, relativeTo: undefined, found: false };
}
}

function tryNodeResolve(filename: string, relativeTo: string): ResolveFileResult {
const home = os.homedir();
function calcPaths(p: string) {
const paths = [p];
// Do not progress towards the root if it is a relative filename.
if (
filename.startsWith('.') &&
(filename.startsWith('./') || filename.startsWith('.' + path.sep) || filename.startsWith('..'))
) {
return paths;
}
for (; p && path.dirname(p) !== p && p !== home; p = path.dirname(p)) {
paths.push(p);
}
return paths;
}
const paths = calcPaths(path.resolve(relativeTo));
try {
const r = require.resolve(filename, { paths: [path.resolve(relativeTo)] });
const r = require.resolve(filename, { paths });
return { filename: r, relativeTo, found: true };
} catch (_) {
return { filename, relativeTo, found: false };
Expand Down

0 comments on commit 75be89b

Please sign in to comment.