Elffuss BraidHub

kikocis/continue public

main · 20.2 KiBRawPermalink
1import * as child_process from "node:child_process";
2import { exec } from "node:child_process";
3
4import { Range } from "core";
5import { EXTENSION_NAME } from "core/control-plane/env";
6import { DEFAULT_IGNORES, defaultIgnoresGlob } from "core/indexing/ignore";
7import * as URI from "uri-js";
8import * as vscode from "vscode";
9
10import {
11 executeGotoProvider,
12 executeSignatureHelpProvider,
13 executeSymbolProvider,
14} from "./autocomplete/lsp";
15import { Repository } from "./otherExtensions/git";
16import { SecretStorage } from "./stubs/SecretStorage";
17import { VsCodeIdeUtils } from "./util/ideUtils";
18import { getExtensionUri, openEditorAndRevealRange } from "./util/vscode";
19import { VsCodeWebviewProtocol } from "./webviewProtocol";
20
21import type {
22 DocumentSymbol,
23 FileStatsMap,
24 FileType,
25 IDE,
26 IdeInfo,
27 IdeSettings,
28 IndexTag,
29 Location,
30 Problem,
31 RangeInFile,
32 SignatureHelp,
33 TerminalOptions,
34 Thread,
35} from "core";
36import { getExtensionVersion, isExtensionPrerelease } from "./util/util";
37
38class VsCodeIde implements IDE {
39 ideUtils: VsCodeIdeUtils;
40 secretStorage: SecretStorage;
41
42 constructor(
43 private readonly vscodeWebviewProtocolPromise: Promise<VsCodeWebviewProtocol>,
44 private readonly context: vscode.ExtensionContext,
45 ) {
46 this.ideUtils = new VsCodeIdeUtils();
47 this.secretStorage = new SecretStorage(context);
48 }
49
50 async readSecrets(keys: string[]): Promise<Record<string, string>> {
51 const secretValuePromises = keys.map((key) => this.secretStorage.get(key));
52 const secretValues = await Promise.all(secretValuePromises);
53
54 return keys.reduce(
55 (acc, key, index) => {
56 if (secretValues[index] === undefined) {
57 return acc;
58 }
59
60 acc[key] = secretValues[index];
61 return acc;
62 },
63 {} as Record<string, string>,
64 );
65 }
66
67 async writeSecrets(secrets: { [key: string]: string }): Promise<void> {
68 for (const [key, value] of Object.entries(secrets)) {
69 await this.secretStorage.store(key, value);
70 }
71 }
72
73 async fileExists(uri: string): Promise<boolean> {
74 try {
75 const stat = await this.ideUtils.stat(vscode.Uri.parse(uri));
76 return stat !== null;
77 } catch (error) {
78 if (error instanceof vscode.FileSystemError) {
79 return false;
80 }
81 throw error;
82 }
83 }
84
85 async gotoDefinition(location: Location): Promise<RangeInFile[]> {
86 const result = await executeGotoProvider({
87 uri: vscode.Uri.parse(location.filepath),
88 line: location.position.line,
89 character: location.position.character,
90 name: "vscode.executeDefinitionProvider",
91 });
92
93 return result;
94 }
95
96 async gotoTypeDefinition(location: Location): Promise<RangeInFile[]> {
97 const result = await executeGotoProvider({
98 uri: vscode.Uri.parse(location.filepath),
99 line: location.position.line,
100 character: location.position.character,
101 name: "vscode.executeTypeDefinitionProvider",
102 });
103
104 return result;
105 }
106
107 async getSignatureHelp(location: Location): Promise<SignatureHelp | null> {
108 const result = await executeSignatureHelpProvider({
109 uri: vscode.Uri.parse(location.filepath),
110 line: location.position.line,
111 character: location.position.character,
112 name: "vscode.executeSignatureHelpProvider",
113 });
114
115 return result;
116 }
117
118 async getReferences(location: Location): Promise<RangeInFile[]> {
119 const result = await executeGotoProvider({
120 uri: vscode.Uri.parse(location.filepath),
121 line: location.position.line,
122 character: location.position.character,
123 name: "vscode.executeReferenceProvider",
124 });
125
126 return result;
127 }
128
129 async getDocumentSymbols(
130 textDocumentIdentifier: string, // uri
131 ): Promise<DocumentSymbol[]> {
132 const result = await executeSymbolProvider({
133 uri: vscode.Uri.parse(textDocumentIdentifier),
134 name: "vscode.executeDocumentSymbolProvider",
135 });
136
137 return result;
138 }
139
140 onDidChangeActiveTextEditor(callback: (uri: string) => void): void {
141 vscode.window.onDidChangeActiveTextEditor((editor) => {
142 if (editor) {
143 callback(editor.document.uri.toString());
144 }
145 });
146 }
147
148 showToast: IDE["showToast"] = async (...params) => {
149 const [type, message, ...otherParams] = params;
150 const { showErrorMessage, showWarningMessage, showInformationMessage } =
151 vscode.window;
152
153 switch (type) {
154 case "error":
155 return showErrorMessage(message, "Show logs").then((selection) => {
156 if (selection === "Show logs") {
157 vscode.commands.executeCommand("workbench.action.toggleDevTools");
158 }
159 });
160 case "info":
161 return showInformationMessage(message, ...otherParams);
162 case "warning":
163 return showWarningMessage(message, ...otherParams);
164 }
165 };
166
167 async getRepoName(dir: string): Promise<string | undefined> {
168 const repo = await this.getRepo(dir);
169 const remotes = repo?.state.remotes;
170 if (!remotes) {
171 return undefined;
172 }
173 const remote =
174 remotes?.find((r: any) => r.name === "origin") ?? remotes?.[0];
175 if (!remote) {
176 return undefined;
177 }
178 const ownerAndRepo = remote.fetchUrl
179 ?.replace(".git", "")
180 .split("/")
181 .slice(-2);
182 return ownerAndRepo?.join("/");
183 }
184
185 async getTags(artifactId: string): Promise<IndexTag[]> {
186 const workspaceDirs = await this.getWorkspaceDirs();
187
188 const branches = await Promise.all(
189 workspaceDirs.map((dir) => this.getBranch(dir)),
190 );
191
192 const tags: IndexTag[] = workspaceDirs.map((directory, i) => ({
193 directory,
194 branch: branches[i],
195 artifactId,
196 }));
197
198 return tags;
199 }
200
201 getIdeInfo(): Promise<IdeInfo> {
202 return Promise.resolve({
203 ideType: "vscode",
204 name: vscode.env.appName,
205 version: vscode.version,
206 remoteName: vscode.env.remoteName || "local",
207 extensionVersion: getExtensionVersion(),
208 isPrerelease: isExtensionPrerelease(),
209 });
210 }
211
212 readRangeInFile(fileUri: string, range: Range): Promise<string> {
213 return this.ideUtils.readRangeInFile(
214 vscode.Uri.parse(fileUri),
215 new vscode.Range(
216 new vscode.Position(range.start.line, range.start.character),
217 new vscode.Position(range.end.line, range.end.character),
218 ),
219 );
220 }
221
222 async getFileStats(files: string[]): Promise<FileStatsMap> {
223 const pathToLastModified: FileStatsMap = {};
224 await Promise.all(
225 files.map(async (file) => {
226 const stat = await this.ideUtils.stat(
227 vscode.Uri.parse(file),
228 false /* No need to catch ENOPRO exceptions */,
229 );
230 pathToLastModified[file] = {
231 lastModified: stat!.mtime,
232 size: stat!.size,
233 };
234 }),
235 );
236
237 return pathToLastModified;
238 }
239
240 async getRepo(dir: string): Promise<Repository | undefined> {
241 return this.ideUtils.getRepo(vscode.Uri.parse(dir));
242 }
243
244 async isTelemetryEnabled(): Promise<boolean> {
245 const globalEnabled = vscode.env.isTelemetryEnabled;
246 const continueEnabled: boolean =
247 (await vscode.workspace
248 .getConfiguration(EXTENSION_NAME)
249 .get("telemetryEnabled")) ?? true;
250 return globalEnabled && continueEnabled;
251 }
252
253 isWorkspaceRemote(): Promise<boolean> {
254 return Promise.resolve(vscode.env.remoteName !== undefined);
255 }
256
257 getUniqueId(): Promise<string> {
258 return Promise.resolve(vscode.env.machineId);
259 }
260
261 async getDiff(includeUnstaged: boolean): Promise<string[]> {
262 return await this.ideUtils.getDiff(includeUnstaged);
263 }
264
265 async getClipboardContent() {
266 return {
267 text: await vscode.env.clipboard.readText(),
268 copiedAt: new Date().toISOString(),
269 };
270 }
271
272 async getTerminalContents(): Promise<string> {
273 return await this.ideUtils.getTerminalContents(1);
274 }
275
276 async getDebugLocals(threadIndex: number): Promise<string> {
277 return await this.ideUtils.getDebugLocals(threadIndex);
278 }
279
280 async getTopLevelCallStackSources(
281 threadIndex: number,
282 stackDepth: number,
283 ): Promise<string[]> {
284 return await this.ideUtils.getTopLevelCallStackSources(
285 threadIndex,
286 stackDepth,
287 );
288 }
289 async getAvailableThreads(): Promise<Thread[]> {
290 return await this.ideUtils.getAvailableThreads();
291 }
292
293 async getWorkspaceDirs(): Promise<string[]> {
294 return this.ideUtils.getWorkspaceDirectories().map((uri) => uri.toString());
295 }
296
297 async writeFile(fileUri: string, contents: string): Promise<void> {
298 await vscode.workspace.fs.writeFile(
299 vscode.Uri.parse(fileUri),
300 Buffer.from(contents),
301 );
302 }
303
304 async showVirtualFile(title: string, contents: string): Promise<void> {
305 this.ideUtils.showVirtualFile(title, contents);
306 }
307
308 async openFile(fileUri: string): Promise<void> {
309 await this.ideUtils.openFile(vscode.Uri.parse(fileUri));
310 }
311
312 async showLines(
313 fileUri: string,
314 startLine: number,
315 endLine: number,
316 ): Promise<void> {
317 const range = new vscode.Range(
318 new vscode.Position(startLine, 0),
319 new vscode.Position(endLine, 0),
320 );
321 openEditorAndRevealRange(vscode.Uri.parse(fileUri), range).then(
322 (editor) => {
323 // Select the lines
324 editor.selection = new vscode.Selection(
325 new vscode.Position(startLine, 0),
326 new vscode.Position(endLine, 0),
327 );
328 },
329 );
330 }
331
332 async runCommand(
333 command: string,
334 options: TerminalOptions = { reuseTerminal: true },
335 ): Promise<void> {
336 let terminal: vscode.Terminal | undefined;
337 if (vscode.window.terminals.length && options.reuseTerminal) {
338 if (options.terminalName) {
339 terminal = vscode.window.terminals.find(
340 (t) => t?.name === options.terminalName,
341 );
342 } else {
343 terminal = vscode.window.activeTerminal ?? vscode.window.terminals[0];
344 }
345 }
346
347 if (!terminal) {
348 terminal = vscode.window.createTerminal(options?.terminalName);
349 }
350 terminal.show();
351 terminal.sendText(command, false);
352 }
353
354 async saveFile(fileUri: string): Promise<void> {
355 await this.ideUtils.saveFile(vscode.Uri.parse(fileUri));
356 }
357
358 private static MAX_BYTES = 100000;
359
360 async readFile(fileUri: string): Promise<string> {
361 try {
362 const uri = vscode.Uri.parse(fileUri);
363
364 // First, check whether it's a notebook document
365 // Need to iterate over the cells to get full contents
366 const notebook =
367 vscode.workspace.notebookDocuments.find((doc) =>
368 URI.equal(doc.uri.toString(), uri.toString()),
369 ) ??
370 (uri.path.endsWith("ipynb")
371 ? await vscode.workspace.openNotebookDocument(uri)
372 : undefined);
373 if (notebook) {
374 return notebook
375 .getCells()
376 .map((cell) => cell.document.getText())
377 .join("\n\n");
378 }
379
380 // Check whether it's an open document
381 const openTextDocument = vscode.workspace.textDocuments.find((doc) =>
382 URI.equal(doc.uri.toString(), uri.toString()),
383 );
384 if (openTextDocument !== undefined) {
385 return openTextDocument.getText();
386 }
387
388 const fileStats = await this.ideUtils.stat(uri);
389 if (fileStats === null || fileStats.size > 10 * VsCodeIde.MAX_BYTES) {
390 return "";
391 }
392
393 const bytes = await this.ideUtils.readFile(uri);
394 if (bytes === null) {
395 return "";
396 }
397
398 // Truncate the buffer to the first MAX_BYTES
399 const truncatedBytes = bytes.slice(0, VsCodeIde.MAX_BYTES);
400 const contents = new TextDecoder().decode(truncatedBytes);
401 return contents;
402 } catch (e) {
403 return "";
404 }
405 }
406
407 async openUrl(url: string): Promise<void> {
408 await vscode.env.openExternal(vscode.Uri.parse(url));
409 }
410
411 async getExternalUri(uri: string): Promise<string> {
412 const vsCodeUri = vscode.Uri.parse(uri);
413 const externalUri = await vscode.env.asExternalUri(vsCodeUri);
414 return externalUri.toString(true);
415 }
416
417 async getOpenFiles(): Promise<string[]> {
418 return this.ideUtils.getOpenFiles().map((uri) => uri.toString());
419 }
420
421 async getCurrentFile() {
422 if (!vscode.window.activeTextEditor) {
423 return undefined;
424 }
425 return {
426 isUntitled: vscode.window.activeTextEditor.document.isUntitled,
427 path: vscode.window.activeTextEditor.document.uri.toString(),
428 contents: vscode.window.activeTextEditor.document.getText(),
429 };
430 }
431
432 async getPinnedFiles(): Promise<string[]> {
433 const tabArray = vscode.window.tabGroups.all[0].tabs;
434
435 return tabArray
436 .filter((t) => t.isPinned)
437 .map((t) => (t.input as vscode.TabInputText).uri.toString());
438 }
439
440 runRipgrepQuery(dirUri: string, args: string[]) {
441 const relativeDir = vscode.Uri.parse(dirUri).fsPath;
442 const ripGrepUri = vscode.Uri.joinPath(
443 getExtensionUri(),
444 "out/node_modules/@vscode/ripgrep/bin/rg",
445 );
446 const p = child_process.spawn(ripGrepUri.fsPath, args, {
447 cwd: relativeDir,
448 });
449 let output = "";
450
451 p.stdout.on("data", (data) => {
452 output += data.toString();
453 });
454
455 return new Promise<string>((resolve, reject) => {
456 p.on("error", reject);
457 p.on("close", (code) => {
458 if (code === 0) {
459 resolve(output);
460 } else if (code === 1) {
461 // No matches
462 resolve(
463 "No matches found. Build, secrets, etc. dirs and files are not included.",
464 );
465 } else {
466 reject(new Error(`Process exited with code ${code}`));
467 }
468 });
469 });
470 }
471
472 async getFileResults(
473 pattern: string,
474 maxResults?: number,
475 ): Promise<string[]> {
476 // Create a single combined ignore pattern for ripgrep (calculated once)
477
478 if (vscode.env.remoteName) {
479 // TODO better tests for this remote search implementation
480 // throw new Error("Ripgrep not supported, this workspace is remote");
481
482 // IMPORTANT: findFiles automatically accounts for .gitignore
483 const ignoreFiles = await vscode.workspace.findFiles(
484 "**/.continueignore",
485 null,
486 );
487
488 const ignoreGlobs: Set<string> = new Set();
489 // Add default ignores from core
490 for (const pattern of DEFAULT_IGNORES) {
491 ignoreGlobs.add(pattern);
492 }
493
494 for (const file of ignoreFiles) {
495 const content = await this.ideUtils.readFile(file);
496 if (content === null) {
497 continue;
498 }
499 const filePath = vscode.workspace.asRelativePath(file);
500 const fileDir = filePath
501 .replace(/\\/g, "/")
502 .replace(/\/$/, "")
503 .split("/")
504 .slice(0, -1)
505 .join("/");
506
507 const patterns = Buffer.from(content)
508 .toString()
509 .split("\n")
510 .map((line) => line.trim())
511 .filter(
512 (line) => line && !line.startsWith("#") && !pattern.startsWith("!"),
513 );
514 // VSCode does not support negations
515
516 patterns
517 // Handle prefix
518 .map((pattern) => {
519 const normalizedPattern = pattern.replace(/\\/g, "/");
520
521 if (normalizedPattern.startsWith("/")) {
522 if (fileDir) {
523 return `{/,}${normalizedPattern}`;
524 } else {
525 return `${fileDir}/${normalizedPattern.substring(1)}`;
526 }
527 } else {
528 if (fileDir) {
529 return `${fileDir}/${normalizedPattern}`;
530 } else {
531 return `**/${normalizedPattern}`;
532 }
533 }
534 })
535 // Handle suffix
536 .map((pattern) => {
537 return pattern.endsWith("/") ? `${pattern}**/*` : pattern;
538 })
539 .forEach((pattern) => {
540 ignoreGlobs.add(pattern);
541 });
542 }
543
544 const ignoreGlobsArray = Array.from(ignoreGlobs);
545
546 const results = await vscode.workspace.findFiles(
547 pattern,
548 ignoreGlobs.size ? `{${ignoreGlobsArray.join(",")}}` : null,
549 maxResults,
550 );
551 return results.map((result) => vscode.workspace.asRelativePath(result));
552 } else {
553 const results: string[] = [];
554 // Create a single combined ignore pattern using glob brace expansion
555 for (const dir of await this.getWorkspaceDirs()) {
556 const dirResults = await this.runRipgrepQuery(dir, [
557 "--files",
558 "--iglob",
559 pattern,
560 "--ignore-file",
561 ".continueignore",
562 "--ignore-file",
563 ".gitignore",
564 "--glob",
565 defaultIgnoresGlob,
566 ...(maxResults ? ["--max-count", String(maxResults)] : []),
567 ]);
568
569 results.push(dirResults);
570 }
571
572 const allResults = results.join("\n").split("\n");
573 if (maxResults) {
574 // In the case of multiple workspaces, maxResults will be applied to each workspace
575 // And then the combined results will also be truncated
576 return allResults.slice(0, maxResults);
577 } else {
578 return allResults;
579 }
580 }
581 }
582
583 async getSearchResults(query: string, maxResults?: number): Promise<string> {
584 if (vscode.env.remoteName) {
585 throw new Error("Ripgrep not supported, this workspace is remote");
586 }
587 const results: string[] = [];
588
589 for (const dir of await this.getWorkspaceDirs()) {
590 const dirResults = await this.runRipgrepQuery(dir, [
591 "-i", // Case-insensitive search
592 "--ignore-file",
593 ".continueignore",
594 "--ignore-file",
595 ".gitignore",
596 "-C",
597 "2", // Show 2 lines of context
598 "--heading", // Only show filepath once per result
599 // Use a single glob with all default ignores
600 "--glob",
601 defaultIgnoresGlob,
602 ...(maxResults ? ["-m", maxResults.toString()] : []),
603 "-e",
604 query, // Pattern to search for
605 ".", // Directory to search in
606 ]);
607
608 results.push(dirResults);
609 }
610
611 const allResults = results.join("\n");
612 if (maxResults) {
613 // In case of multiple workspaces, do max results per workspace and then truncate to maxResults
614 // Will prioritize first workspace results, fine for now
615 // Results are separated by either ./ or --
616 const matches = Array.from(allResults.matchAll(/(\n--|\n\.\/)/g));
617 if (matches.length > maxResults) {
618 return allResults.substring(0, matches[maxResults].index);
619 } else {
620 return allResults;
621 }
622 } else {
623 return allResults;
624 }
625 }
626
627 async getProblems(fileUri?: string | undefined): Promise<Problem[]> {
628 const uri = fileUri
629 ? vscode.Uri.parse(fileUri)
630 : vscode.window.activeTextEditor?.document.uri;
631 if (!uri) {
632 return [];
633 }
634 return vscode.languages.getDiagnostics(uri).map((d) => {
635 return {
636 filepath: uri.toString(),
637 range: {
638 start: {
639 line: d.range.start.line,
640 character: d.range.start.character,
641 },
642 end: { line: d.range.end.line, character: d.range.end.character },
643 },
644 message: d.message,
645 };
646 });
647 }
648
649 async subprocess(command: string, cwd?: string): Promise<[string, string]> {
650 return new Promise((resolve, reject) => {
651 exec(command, { cwd }, (error, stdout, stderr) => {
652 if (error) {
653 console.warn(error);
654 reject(stderr);
655 }
656 resolve([stdout, stderr]);
657 });
658 });
659 }
660
661 async getBranch(dir: string): Promise<string> {
662 return this.ideUtils.getBranch(vscode.Uri.parse(dir));
663 }
664
665 async getGitRootPath(dir: string): Promise<string | undefined> {
666 const root = await this.ideUtils.getGitRoot(vscode.Uri.parse(dir));
667 return root?.toString();
668 }
669
670 async listDir(dir: string): Promise<[string, FileType][]> {
671 const entries = await this.ideUtils.readDirectory(vscode.Uri.parse(dir));
672 return entries === null ? [] : (entries as any);
673 }
674
675 private getIdeSettingsSync(): IdeSettings {
676 const settings = vscode.workspace.getConfiguration(EXTENSION_NAME);
677 const remoteConfigServerUrl = settings.get<string | undefined>(
678 "remoteConfigServerUrl",
679 undefined,
680 );
681 const ideSettings: IdeSettings = {
682 remoteConfigServerUrl,
683 remoteConfigSyncPeriod: settings.get<number>(
684 "remoteConfigSyncPeriod",
685 60,
686 ),
687 userToken: settings.get<string>("userToken", ""),
688 continueTestEnvironment: "production",
689 pauseCodebaseIndexOnStart: settings.get<boolean>(
690 "pauseCodebaseIndexOnStart",
691 false,
692 ),
693 };
694 return ideSettings;
695 }
696
697 async getIdeSettings(): Promise<IdeSettings> {
698 const ideSettings = this.getIdeSettingsSync();
699 return ideSettings;
700 }
701}
702
703export { VsCodeIde };