Elffuss BraidHub

kikocis/continue public

main · 19.3 KiBRawPermalink
1import { EXTENSION_NAME } from "core/control-plane/env";
2import { findUriInDirs } from "core/util/uri";
3import _ from "lodash";
4import * as URI from "uri-js";
5import * as vscode from "vscode";
6
7import { threadStopped } from "../debug/debug";
8import { VsCodeExtension } from "../extension/VsCodeExtension";
9import { GitExtension, Repository } from "../otherExtensions/git";
10import {
11 SuggestionRanges,
12 acceptSuggestionCommand,
13 rejectSuggestionCommand,
14 showSuggestion as showSuggestionInEditor,
15} from "../suggestions";
16
17import { getUniqueId, openEditorAndRevealRange } from "./vscode";
18
19import type { Range, Thread } from "core";
20
21const util = require("node:util");
22const asyncExec = util.promisify(require("node:child_process").exec);
23
24const NO_FS_PROVIDER_ERROR = "ENOPRO";
25const UNSUPPORTED_SCHEMES: Set<string> = new Set();
26
27export class VsCodeIdeUtils {
28 visibleMessages: Set<string> = new Set();
29
30 async gotoDefinition(
31 uri: vscode.Uri,
32 position: vscode.Position,
33 ): Promise<vscode.Location[]> {
34 const locations: vscode.Location[] = await vscode.commands.executeCommand(
35 "vscode.executeDefinitionProvider",
36 uri,
37 position,
38 );
39 return locations;
40 }
41
42 async documentSymbol(uri: vscode.Uri): Promise<vscode.DocumentSymbol[]> {
43 return await vscode.commands.executeCommand(
44 "vscode.executeDocumentSymbolProvider",
45 uri,
46 );
47 }
48
49 async references(
50 uri: vscode.Uri,
51 position: vscode.Position,
52 ): Promise<vscode.Location[]> {
53 return await vscode.commands.executeCommand(
54 "vscode.executeReferenceProvider",
55 uri,
56 position,
57 );
58 }
59
60 async foldingRanges(uri: vscode.Uri): Promise<vscode.FoldingRange[]> {
61 return await vscode.commands.executeCommand(
62 "vscode.executeFoldingRangeProvider",
63 uri,
64 );
65 }
66
67 private _workspaceDirectories: vscode.Uri[] | undefined = undefined;
68 getWorkspaceDirectories(): vscode.Uri[] {
69 if (this._workspaceDirectories === undefined) {
70 this._workspaceDirectories =
71 vscode.workspace.workspaceFolders?.map((folder) => folder.uri) || [];
72 }
73
74 return this._workspaceDirectories;
75 }
76
77 getUniqueId() {
78 return getUniqueId();
79 }
80
81 showSuggestion(uri: vscode.Uri, range: Range, suggestion: string) {
82 showSuggestionInEditor(
83 uri,
84 new vscode.Range(
85 range.start.line,
86 range.start.character,
87 range.end.line,
88 range.end.character,
89 ),
90 suggestion,
91 );
92 }
93
94 async openFile(uri: vscode.Uri, range?: vscode.Range) {
95 // vscode has a builtin open/get open files
96 return await openEditorAndRevealRange(
97 uri,
98 range,
99 vscode.ViewColumn.One,
100 false,
101 );
102 }
103
104 async fileExists(uri: vscode.Uri): Promise<boolean> {
105 try {
106 return (await this.stat(uri)) !== null;
107 } catch {
108 return false;
109 }
110 }
111
112 /**
113 * Read the entire contents of a file from the given URI.
114 * If there are unsaved changes in an open editor, returns those instead of the file on disk.
115 *
116 * @param uri - The URI of the file to read.
117 * @param ignoreMissingProviders - Optional flag to ignore missing file system providers for unsupported schemes.
118 * Defaults to `true`.
119 * @returns A promise that resolves to the file content as a `Uint8Array`, or `null` if the scheme is unsupported
120 * or the provider is missing and `ignoreMissingProviders` is `true`.
121 * If `ignoreMissingProviders` is `false`, it will throw an error for unsupported schemes or missing providers.
122 * @throws Will rethrow any error that is not related to missing providers or unsupported schemes.
123 */
124 async readFile(
125 uri: vscode.Uri,
126 ignoreMissingProviders: boolean = true,
127 ): Promise<Uint8Array | null> {
128 // First check if there's an open document with this URI that might have unsaved changes.
129 const openDocuments = vscode.workspace.textDocuments;
130 for (const document of openDocuments) {
131 if (document.uri.toString() === uri.toString()) {
132 // Found an open document with this URI.
133 // Return its current content (including any unsaved changes) as Uint8Array.
134 const docText = document.getText();
135 return Buffer.from(docText, "utf8");
136 }
137 }
138
139 // If no open document found or if it's not dirty, fall back to reading from disk.
140 return await this.fsOperation(
141 uri,
142 async (u) => {
143 return await vscode.workspace.fs.readFile(u);
144 },
145 ignoreMissingProviders,
146 );
147 }
148
149 /**
150 * Retrieve metadata about a file from the given URI.
151 *
152 * @param uri - The URI of the file or directory to retrieve metadata about.
153 * @param ignoreMissingProviders - Optional. If `true`, missing file system providers will be ignored. Defaults to `true`.
154 * @returns A promise that resolves to a `vscode.FileStat` object containing the file metadata,
155 * or `null` if the scheme is unsupported or the provider is missing and `ignoreMissingProviders` is `true`.
156 */
157 async stat(
158 uri: vscode.Uri,
159 ignoreMissingProviders: boolean = true,
160 ): Promise<vscode.FileStat | null> {
161 return await this.fsOperation(
162 uri,
163 async (u) => {
164 return await vscode.workspace.fs.stat(uri);
165 },
166 ignoreMissingProviders,
167 );
168 }
169
170 /**
171 * Retrieve all entries of a directory from the given URI.
172 *
173 * @param uri - The URI of the directory to read.
174 * @param ignoreMissingProviders - Optional. If `true`, missing file system providers will be ignored. Defaults to `true`.
175 * @returns A promise that resolves to an array of tuples, where each tuple contains the name of a directory entry
176 * and its type (`vscode.FileType`), or `null` if the scheme is unsupported or the provider is missing and `ignoreMissingProviders` is `true`.
177 */
178 async readDirectory(
179 uri: vscode.Uri,
180 ignoreMissingProviders: boolean = true,
181 ): Promise<[string, vscode.FileType][] | null> {
182 return await this.fsOperation(
183 uri,
184 async (u) => {
185 return await vscode.workspace.fs.readDirectory(uri);
186 },
187 ignoreMissingProviders,
188 );
189 }
190
191 /**
192 * Performs a file system operation on the given URI using the provided delegate function.
193 *
194 * @template T The type of the result returned by the delegate function.
195 * @param uri The URI on which the file system operation is to be performed.
196 * @param delegate A function that performs the desired operation on the given URI.
197 * @param ignoreMissingProviders Whether to ignore errors caused by missing file system providers. Defaults to `true`.
198 * @returns A promise that resolves to the result of the delegate function, or `null` if the operation is skipped due to unsupported schemes or missing providers.
199 * @throws Re-throws any error encountered during the operation, except for missing provider errors when `ignoreMissingProviders` is `true`.
200 */
201 private async fsOperation<T>(
202 uri: vscode.Uri,
203 delegate: (uri: vscode.Uri) => T,
204 ignoreMissingProviders: boolean = true,
205 ): Promise<T | null> {
206 const scheme = uri.scheme;
207 if (ignoreMissingProviders && UNSUPPORTED_SCHEMES.has(scheme)) {
208 return null;
209 }
210 try {
211 return await delegate(uri);
212 } catch (err: any) {
213 if (
214 ignoreMissingProviders &&
215 //see https://github.com/microsoft/vscode/blob/c9c54f9e775e5f57d97bef796797b5bc670c8150/src/vs/workbench/api/common/extHostFileSystemConsumer.ts#L230
216 (err.name === NO_FS_PROVIDER_ERROR ||
217 err.message?.includes(NO_FS_PROVIDER_ERROR))
218 ) {
219 UNSUPPORTED_SCHEMES.add(scheme);
220 console.log(`Ignoring missing provider error:`, err.message);
221 return null;
222 }
223 throw err;
224 }
225 }
226
227 showVirtualFile(name: string, contents: string) {
228 vscode.workspace
229 .openTextDocument(
230 vscode.Uri.parse(
231 `${
232 VsCodeExtension.continueVirtualDocumentScheme
233 }:${encodeURIComponent(name)}?${encodeURIComponent(contents)}`,
234 ),
235 )
236 .then((doc) => {
237 vscode.window.showTextDocument(doc, { preview: false });
238 });
239 }
240
241 async getUserSecret(key: string) {
242 // Check if secret already exists in VS Code settings (global)
243 let secret = vscode.workspace.getConfiguration(EXTENSION_NAME).get(key);
244 if (typeof secret !== "undefined" && secret !== null) {
245 return secret;
246 }
247
248 // If not, ask user for secret
249 secret = await vscode.window.showInputBox({
250 prompt: `Either enter secret for ${key} or press enter to try Continue for free.`,
251 password: true,
252 });
253
254 // Add secret to VS Code settings
255 vscode.workspace
256 .getConfiguration(EXTENSION_NAME)
257 .update(key, secret, vscode.ConfigurationTarget.Global);
258
259 return secret;
260 }
261
262 // ------------------------------------ //
263 // Initiate Request
264
265 acceptRejectSuggestion(accept: boolean, key: SuggestionRanges) {
266 if (accept) {
267 acceptSuggestionCommand(key);
268 } else {
269 rejectSuggestionCommand(key);
270 }
271 }
272
273 // ------------------------------------ //
274 // Respond to request
275
276 // Checks to see if the editor is a code editor.
277 // In some cases vscode.window.visibleTextEditors can return non-code editors
278 // e.g. terminal editors in side-by-side mode
279 private documentIsCode(uri: vscode.Uri) {
280 return uri.scheme === "file" || uri.scheme === "vscode-remote";
281 }
282
283 getOpenFiles(): vscode.Uri[] {
284 return vscode.window.tabGroups.all
285 .flatMap((group) => group.tabs)
286 .filter(
287 (tab) =>
288 tab.input instanceof vscode.TabInputText &&
289 this.documentIsCode((tab.input as vscode.TabInputText).uri),
290 )
291 .map((tab) => (tab.input as vscode.TabInputText).uri);
292 }
293
294 saveFile(uri: vscode.Uri) {
295 vscode.window.visibleTextEditors
296 .filter((editor) => this.documentIsCode(editor.document.uri))
297 .forEach((editor) => {
298 if (URI.equal(editor.document.uri.toString(), uri.toString())) {
299 editor.document.save();
300 }
301 });
302 }
303
304 async readRangeInFile(uri: vscode.Uri, range: vscode.Range): Promise<string> {
305 const buffer = await this.readFile(uri);
306 if (buffer === null) {
307 return "";
308 }
309 const contents = new TextDecoder().decode(buffer);
310 const lines = contents.split("\n");
311 return `${lines
312 .slice(range.start.line, range.end.line)
313 .join("\n")}\n${lines[
314 range.end.line < lines.length - 1 ? range.end.line : lines.length - 1
315 ].slice(0, range.end.character)}`;
316 }
317
318 async getTerminalContents(commands = -1): Promise<string> {
319 const tempCopyBuffer = await vscode.env.clipboard.readText();
320 if (commands < 0) {
321 await vscode.commands.executeCommand(
322 "workbench.action.terminal.selectAll",
323 );
324 } else {
325 for (let i = 0; i < commands; i++) {
326 await vscode.commands.executeCommand(
327 "workbench.action.terminal.selectToPreviousCommand",
328 );
329 }
330 }
331 await vscode.commands.executeCommand(
332 "workbench.action.terminal.copySelection",
333 );
334 await vscode.commands.executeCommand(
335 "workbench.action.terminal.clearSelection",
336 );
337 let terminalContents = (await vscode.env.clipboard.readText()).trim();
338 await vscode.env.clipboard.writeText(tempCopyBuffer);
339
340 if (tempCopyBuffer === terminalContents) {
341 // This means there is no terminal open to select text from
342 return "";
343 }
344
345 // Sometimes the above won't successfully separate by command, so we attempt manually
346 const lines = terminalContents.split("\n");
347 const lastLine = lines.pop()?.trim();
348 if (lastLine) {
349 let i = lines.length - 1;
350 while (i >= 0 && !lines[i].trim().startsWith(lastLine)) {
351 i--;
352 }
353 terminalContents = lines.slice(Math.max(i, 0)).join("\n");
354 }
355
356 return terminalContents;
357 }
358
359 private async _getThreads(session: vscode.DebugSession) {
360 const threadsResponse = await session.customRequest("threads");
361 const threads = threadsResponse.threads.filter((thread: any) =>
362 threadStopped.get(thread.id),
363 );
364 threads.sort((a: any, b: any) => a.id - b.id);
365 threadsResponse.threads = threads;
366
367 return threadsResponse;
368 }
369
370 async getAvailableThreads(): Promise<Thread[]> {
371 const session = vscode.debug.activeDebugSession;
372 if (!session) {
373 return [];
374 }
375
376 const threadsResponse = await this._getThreads(session);
377 return threadsResponse.threads;
378 }
379
380 async getDebugLocals(threadIndex = 0): Promise<string> {
381 const session = vscode.debug.activeDebugSession;
382
383 if (!session) {
384 vscode.window.showWarningMessage(
385 "No active debug session found, therefore no debug context will be provided for the llm.",
386 );
387 return "";
388 }
389
390 const variablesResponse = await session
391 .customRequest("stackTrace", {
392 threadId: threadIndex,
393 startFrame: 0,
394 })
395 .then((traceResponse) =>
396 session.customRequest("scopes", {
397 frameId: traceResponse.stackFrames[0].id,
398 }),
399 )
400 .then((scopesResponse) =>
401 session.customRequest("variables", {
402 variablesReference: scopesResponse.scopes[0].variablesReference,
403 }),
404 );
405
406 const variableContext = variablesResponse.variables
407 .filter((variable: any) => variable.type !== "global")
408 .reduce(
409 (acc: any, variable: any) =>
410 `${acc}\nname: ${variable.name}, type: ${variable.type}, ` +
411 `value: ${variable.value}`,
412 "",
413 );
414
415 return variableContext;
416 }
417
418 async getTopLevelCallStackSources(
419 threadIndex: number,
420 stackDepth = 3,
421 ): Promise<string[]> {
422 const session = vscode.debug.activeDebugSession;
423 if (!session) {
424 return [];
425 }
426
427 const sourcesPromises = await session
428 .customRequest("stackTrace", {
429 threadId: threadIndex,
430 startFrame: 0,
431 })
432 .then((traceResponse) =>
433 traceResponse.stackFrames
434 .slice(0, stackDepth)
435 .map(async (stackFrame: any) => {
436 const scopeResponse = await session.customRequest("scopes", {
437 frameId: stackFrame.id,
438 });
439
440 const scope = scopeResponse.scopes[0];
441
442 return await this.retrieveSource(
443 scope.source && !_.isEmpty(scope.source) ? scope : stackFrame,
444 );
445 }),
446 );
447
448 return Promise.all(sourcesPromises);
449 }
450
451 private async retrieveSource(sourceContainer: any): Promise<string> {
452 if (!sourceContainer.source) {
453 return "";
454 }
455
456 const sourceRef = sourceContainer.source.sourceReference;
457 if (sourceRef && sourceRef > 0) {
458 // according to the spec, source might be ony available in a debug session
459 // not yet able to test this branch
460 const sourceResponse =
461 await vscode.debug.activeDebugSession?.customRequest("source", {
462 source: sourceContainer.source,
463 sourceReference: sourceRef,
464 });
465 return sourceResponse.content;
466 } else if (sourceContainer.line && sourceContainer.endLine) {
467 return await this.readRangeInFile(
468 sourceContainer.source.path,
469 new vscode.Range(
470 sourceContainer.line - 1, // The line number from scope response starts from 1
471 sourceContainer.column,
472 sourceContainer.endLine - 1,
473 sourceContainer.endColumn,
474 ),
475 );
476 } else if (sourceContainer.line) {
477 // fall back to 5 line of context
478 return await this.readRangeInFile(
479 sourceContainer.source.path,
480 new vscode.Range(
481 Math.max(0, sourceContainer.line - 3),
482 0,
483 sourceContainer.line + 2,
484 0,
485 ),
486 );
487 } else {
488 return "unavailable";
489 }
490 }
491
492 private async _getRepo(
493 forDirectory: vscode.Uri,
494 ): Promise<Repository | undefined> {
495 // Use the native git extension to get the branch name
496 const extension =
497 vscode.extensions.getExtension<GitExtension>("vscode.git");
498 if (
499 typeof extension === "undefined" ||
500 !extension.isActive ||
501 typeof vscode.workspace.workspaceFolders === "undefined"
502 ) {
503 return undefined;
504 }
505
506 try {
507 const git = extension.exports.getAPI(1);
508 return git.getRepository(forDirectory) ?? undefined;
509 } catch (e) {
510 this._repoWasNone = true;
511 console.warn("Git not found: ", e);
512 return undefined;
513 }
514 }
515
516 private _getRepositories(): Repository[] | undefined {
517 const extension =
518 vscode.extensions.getExtension<GitExtension>("vscode.git");
519 if (
520 typeof extension === "undefined" ||
521 !extension.isActive ||
522 typeof vscode.workspace.workspaceFolders === "undefined"
523 ) {
524 return undefined;
525 }
526
527 try {
528 const git = extension.exports.getAPI(1);
529 return git.repositories;
530 } catch (e) {
531 this._repoWasNone = true;
532 console.warn("Git not found: ", e);
533 return undefined;
534 }
535 }
536
537 private _repoWasNone: boolean = false;
538 private repoCache: Map<string, Repository> = new Map();
539 private static secondsToWaitForGitToLoad =
540 process.env.NODE_ENV === "test" ? 1 : 20;
541 async getRepo(forDirectory: vscode.Uri): Promise<Repository | undefined> {
542 const workspaceDirs = this.getWorkspaceDirectories().map((dir) =>
543 dir.toString(),
544 );
545 const { foundInDir } = findUriInDirs(
546 forDirectory.toString(),
547 workspaceDirs,
548 );
549 if (foundInDir) {
550 // Check if the repository is already cached
551 const cachedRepo = this.repoCache.get(foundInDir);
552 if (cachedRepo) {
553 return cachedRepo;
554 }
555 }
556
557 let repo = await this._getRepo(forDirectory);
558
559 let i = 0;
560 while (!repo?.state?.HEAD?.name) {
561 if (this._repoWasNone) {
562 return undefined;
563 }
564
565 await new Promise((resolve) => setTimeout(resolve, 1000));
566 i++;
567 if (i >= VsCodeIdeUtils.secondsToWaitForGitToLoad) {
568 this._repoWasNone = true;
569 return undefined;
570 }
571 repo = await this._getRepo(forDirectory);
572 }
573
574 if (foundInDir) {
575 // Cache the repository for the parent directory
576 this.repoCache.set(foundInDir, repo);
577 }
578
579 return repo;
580 }
581
582 async getGitRoot(forDirectory: vscode.Uri): Promise<vscode.Uri | undefined> {
583 const repo = await this.getRepo(forDirectory);
584 return repo?.rootUri;
585 }
586
587 async getBranch(forDirectory: vscode.Uri) {
588 const repo = await this.getRepo(forDirectory);
589 if (repo?.state?.HEAD?.name === undefined) {
590 try {
591 const { stdout } = await asyncExec("git rev-parse --abbrev-ref HEAD", {
592 cwd: forDirectory.fsPath,
593 });
594 return stdout?.trim() || "NONE";
595 } catch (e) {
596 return "NONE";
597 }
598 }
599
600 return repo?.state?.HEAD?.name || "NONE";
601 }
602
603 private splitDiff(diffString: string): string[] {
604 const fileDiffHeaderRegex = /(?=diff --git a\/.* b\/.*)/;
605
606 const diffs = diffString.split(fileDiffHeaderRegex);
607
608 if (diffs[0].trim() === "") {
609 diffs.shift();
610 }
611
612 return diffs;
613 }
614
615 async getDiff(includeUnstaged: boolean): Promise<string[]> {
616 const diffs: string[] = [];
617
618 const repos = this._getRepositories();
619
620 try {
621 if (repos) {
622 for (const repo of repos) {
623 const staged = await repo.diff(true);
624
625 diffs.push(staged);
626 if (includeUnstaged) {
627 const unstaged = await repo.diff(false);
628 diffs.push(unstaged);
629 }
630 }
631 }
632
633 return diffs.flatMap((diff) => this.splitDiff(diff));
634 } catch (e) {
635 console.error(e);
636 return [];
637 }
638 }
639}