Elffuss BraidHub

kikocis/continue public

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