Find nearest node_modules between project path and aqua file (#19)

This commit is contained in:
Dima 2022-08-10 15:06:57 +03:00 committed by GitHub
parent 7a71f0fbbe
commit ae72f62dbe
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -6,6 +6,40 @@ import type { WorkspaceFolder } from 'vscode-languageserver-protocol';
import * as fs from 'fs';
import * as Path from 'path';
function findNearestNodeModules(fileLocation: string, projectLocation: string): string | undefined {
const relative = Path.relative(projectLocation, fileLocation);
const projectPath = Path.resolve(projectLocation.replace('file://', ''));
// project location is a part of file location
if (relative && !relative.startsWith('..') && !Path.isAbsolute(relative)) {
let currentPath = Path.join(fileLocation.replace('file:/', ''), '..');
let result: string | undefined = undefined;
while (true) {
const possibleNodeModulesPath = Path.join(currentPath, '/node_modules');
if (fs.existsSync(possibleNodeModulesPath)) {
result = Path.resolve(possibleNodeModulesPath);
break;
}
if (Path.resolve(currentPath) === projectPath) {
break;
} else {
currentPath = Path.join(currentPath, '..');
}
}
return result;
} else {
return undefined;
}
}
function notEmpty<TValue>(value: TValue | null | undefined): value is TValue {
return value !== null && value !== undefined;
}
export async function compileAqua(
settings: Settings,
textDocument: TextDocument,
@ -16,6 +50,9 @@ export async function compileAqua(
let imports: string[] = [];
let nodeModulesPaths = folders.map((f) => findNearestNodeModules(textDocument.uri, f.uri)).filter(notEmpty);
imports = imports.concat(nodeModulesPaths);
// add all workspace folders to imports
imports = imports.concat(folders.map((f) => f.uri.replace('file://', '')));
imports = imports.concat(folders.map((f) => f.uri.replace('file://', '')) + '/node_modules');