Elffuss BraidHub

kikocis/continue public

86b69ad8aae4 · 2.7 KiBRawPermalink
1import { IDE } from "../..";
2import {
3 AutocompleteCodeSnippet,
4 AutocompleteSnippetType,
5} from "../snippets/types";
6import { HelperVars } from "../util/HelperVars";
7
8import { ImportDefinitionsService } from "./ImportDefinitionsService";
9import { getSymbolsForSnippet } from "./ranking";
10import { RootPathContextService } from "./root-path-context/RootPathContextService";
11
12export class ContextRetrievalService {
13 private importDefinitionsService: ImportDefinitionsService;
14 private rootPathContextService: RootPathContextService;
15
16 constructor(private readonly ide: IDE) {
17 this.importDefinitionsService = new ImportDefinitionsService(this.ide);
18 this.rootPathContextService = new RootPathContextService(
19 this.importDefinitionsService,
20 this.ide,
21 );
22 }
23
24 public async getSnippetsFromImportDefinitions(
25 helper: HelperVars,
26 ): Promise<AutocompleteCodeSnippet[]> {
27 if (helper.options.useImports === false) {
28 return [];
29 }
30
31 const importSnippets: AutocompleteCodeSnippet[] = [];
32 const fileInfo = this.importDefinitionsService.get(helper.filepath);
33 if (fileInfo) {
34 const { imports } = fileInfo;
35 // Look for imports of any symbols around the current range
36 const textAroundCursor =
37 helper.fullPrefix.split("\n").slice(-5).join("\n") +
38 helper.fullSuffix.split("\n").slice(0, 3).join("\n");
39 const symbols = Array.from(getSymbolsForSnippet(textAroundCursor)).filter(
40 (symbol) => !helper.lang.topLevelKeywords.includes(symbol),
41 );
42 for (const symbol of symbols) {
43 const rifs = imports[symbol];
44 if (Array.isArray(rifs)) {
45 const snippets: AutocompleteCodeSnippet[] = rifs.map((rif) => {
46 return {
47 filepath: rif.filepath,
48 content: rif.contents,
49 type: AutocompleteSnippetType.Code,
50 };
51 });
52
53 importSnippets.push(...snippets);
54 }
55 }
56 }
57
58 return importSnippets;
59 }
60
61 public async getRootPathSnippets(
62 helper: HelperVars,
63 ): Promise<AutocompleteCodeSnippet[]> {
64 if (!helper.treePath) {
65 return [];
66 }
67
68 return this.rootPathContextService.getContextForPath(
69 helper.filepath,
70 helper.treePath,
71 );
72 }
73
74 /**
75 * Initialize the import definitions cache for a file.
76 * This is normally done automatically when the active text editor changes,
77 * but needs to be called manually when using context fetching outside the normal flow.
78 */
79 public async initializeForFile(filepath: string): Promise<void> {
80 try {
81 await (this.importDefinitionsService as any).cache.initKey(filepath);
82 } catch (e) {
83 console.warn(
84 `Failed to initialize import definitions cache for ${filepath}:`,
85 e,
86 );
87 }
88 }
89}