forked from huggingface/llm-vscode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfindImports.ts
43 lines (37 loc) · 1.34 KB
/
findImports.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { CodeAction } from "vscode";
const importStatement = /Import ([\S]*) from module [\S]*/;
const existingImportStatement = /Add ([\S]*) to existing import declaration from [\S]*/;
const importDefaultStatement = /Import default ([\S]*) from module [\S]*/;
const existingDefaultImportStatement = /Add default import ([\S]*) to existing import declaration from [\S]*/;
const importStatements = [
importStatement,
existingImportStatement,
importDefaultStatement,
existingDefaultImportStatement,
];
/*
filter imports with same name from different modules
for example if there are multiple modules with same exported name:
Import {foo} from './a' and Import {foo} from './b'
in this case we will ignore and not auto import it
*/
export default function findImports(
codeActionCommands: CodeAction[] = []
): CodeAction[] {
const importCommands = codeActionCommands.filter(({ title }) =>
importStatements.some((statement) => statement.test(title))
);
const importNames = importCommands.map(getImportName);
return importCommands.filter(
(command) =>
importNames.filter((name) => name === getImportName(command)).length <= 1
);
}
function getImportName({
title,
}: {
title: string;
}): string | undefined | null {
const statement = importStatements.map((s) => s.exec(title)).find(Boolean);
return statement && statement[1];
}