Elffuss BraidHub

kikocis/continue public

deff15df45d1 · 18.6 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 getOpenFiles(): vscode.Uri[] {
271 return vscode.window.tabGroups.all
272 .map((group) => {
273 return group.tabs.map((tab) => {
274 return (tab.input as any)?.uri;
275 });
276 })
277 .flat()
278 .filter(Boolean) // filter out undefined values
279 .filter((uri) => this.documentIsCode(uri)); // Filter out undesired documents
280 }
281
282 saveFile(uri: vscode.Uri) {
283 vscode.window.visibleTextEditors
284 .filter((editor) => this.documentIsCode(editor.document.uri))
285 .forEach((editor) => {
286 if (URI.equal(editor.document.uri.toString(), uri.toString())) {
287 editor.document.save();
288 }
289 });
290 }
291
292 async readRangeInFile(uri: vscode.Uri, range: vscode.Range): Promise<string> {
293 const buffer = await this.readFile(uri);
294 if (buffer === null) {
295 return '';
296 }
297 const contents = new TextDecoder().decode(buffer);
298 const lines = contents.split("\n");
299 return `${lines
300 .slice(range.start.line, range.end.line)
301 .join("\n")}\n${lines[
302 range.end.line < lines.length - 1 ? range.end.line : lines.length - 1
303 ].slice(0, range.end.character)}`;
304 }
305
306 async getTerminalContents(commands = -1): Promise<string> {
307 const tempCopyBuffer = await vscode.env.clipboard.readText();
308 if (commands < 0) {
309 await vscode.commands.executeCommand(
310 "workbench.action.terminal.selectAll",
311 );
312 } else {
313 for (let i = 0; i < commands; i++) {
314 await vscode.commands.executeCommand(
315 "workbench.action.terminal.selectToPreviousCommand",
316 );
317 }
318 }
319 await vscode.commands.executeCommand(
320 "workbench.action.terminal.copySelection",
321 );
322 await vscode.commands.executeCommand(
323 "workbench.action.terminal.clearSelection",
324 );
325 let terminalContents = (await vscode.env.clipboard.readText()).trim();
326 await vscode.env.clipboard.writeText(tempCopyBuffer);
327
328 if (tempCopyBuffer === terminalContents) {
329 // This means there is no terminal open to select text from
330 return "";
331 }
332
333 // Sometimes the above won't successfully separate by command, so we attempt manually
334 const lines = terminalContents.split("\n");
335 const lastLine = lines.pop()?.trim();
336 if (lastLine) {
337 let i = lines.length - 1;
338 while (i >= 0 && !lines[i].trim().startsWith(lastLine)) {
339 i--;
340 }
341 terminalContents = lines.slice(Math.max(i, 0)).join("\n");
342 }
343
344 return terminalContents;
345 }
346
347 private async _getThreads(session: vscode.DebugSession) {
348 const threadsResponse = await session.customRequest("threads");
349 const threads = threadsResponse.threads.filter((thread: any) =>
350 threadStopped.get(thread.id),
351 );
352 threads.sort((a: any, b: any) => a.id - b.id);
353 threadsResponse.threads = threads;
354
355 return threadsResponse;
356 }
357
358 async getAvailableThreads(): Promise<Thread[]> {
359 const session = vscode.debug.activeDebugSession;
360 if (!session) {
361 return [];
362 }
363
364 const threadsResponse = await this._getThreads(session);
365 return threadsResponse.threads;
366 }
367
368 async getDebugLocals(threadIndex = 0): Promise<string> {
369 const session = vscode.debug.activeDebugSession;
370
371 if (!session) {
372 vscode.window.showWarningMessage(
373 "No active debug session found, therefore no debug context will be provided for the llm.",
374 );
375 return "";
376 }
377
378 const variablesResponse = await session
379 .customRequest("stackTrace", {
380 threadId: threadIndex,
381 startFrame: 0,
382 })
383 .then((traceResponse) =>
384 session.customRequest("scopes", {
385 frameId: traceResponse.stackFrames[0].id,
386 }),
387 )
388 .then((scopesResponse) =>
389 session.customRequest("variables", {
390 variablesReference: scopesResponse.scopes[0].variablesReference,
391 }),
392 );
393
394 const variableContext = variablesResponse.variables
395 .filter((variable: any) => variable.type !== "global")
396 .reduce(
397 (acc: any, variable: any) =>
398 `${acc}\nname: ${variable.name}, type: ${variable.type}, ` +
399 `value: ${variable.value}`,
400 "",
401 );
402
403 return variableContext;
404 }
405
406 async getTopLevelCallStackSources(
407 threadIndex: number,
408 stackDepth = 3,
409 ): Promise<string[]> {
410 const session = vscode.debug.activeDebugSession;
411 if (!session) {
412 return [];
413 }
414
415 const sourcesPromises = await session
416 .customRequest("stackTrace", {
417 threadId: threadIndex,
418 startFrame: 0,
419 })
420 .then((traceResponse) =>
421 traceResponse.stackFrames
422 .slice(0, stackDepth)
423 .map(async (stackFrame: any) => {
424 const scopeResponse = await session.customRequest("scopes", {
425 frameId: stackFrame.id,
426 });
427
428 const scope = scopeResponse.scopes[0];
429
430 return await this.retrieveSource(
431 scope.source && !_.isEmpty(scope.source) ? scope : stackFrame,
432 );
433 }),
434 );
435
436 return Promise.all(sourcesPromises);
437 }
438
439 private async retrieveSource(sourceContainer: any): Promise<string> {
440 if (!sourceContainer.source) {
441 return "";
442 }
443
444 const sourceRef = sourceContainer.source.sourceReference;
445 if (sourceRef && sourceRef > 0) {
446 // according to the spec, source might be ony available in a debug session
447 // not yet able to test this branch
448 const sourceResponse =
449 await vscode.debug.activeDebugSession?.customRequest("source", {
450 source: sourceContainer.source,
451 sourceReference: sourceRef,
452 });
453 return sourceResponse.content;
454 } else if (sourceContainer.line && sourceContainer.endLine) {
455 return await this.readRangeInFile(
456 sourceContainer.source.path,
457 new vscode.Range(
458 sourceContainer.line - 1, // The line number from scope response starts from 1
459 sourceContainer.column,
460 sourceContainer.endLine - 1,
461 sourceContainer.endColumn,
462 ),
463 );
464 } else if (sourceContainer.line) {
465 // fall back to 5 line of context
466 return await this.readRangeInFile(
467 sourceContainer.source.path,
468 new vscode.Range(
469 Math.max(0, sourceContainer.line - 3),
470 0,
471 sourceContainer.line + 2,
472 0,
473 ),
474 );
475 } else {
476 return "unavailable";
477 }
478 }
479
480 private async _getRepo(
481 forDirectory: vscode.Uri,
482 ): Promise<Repository | undefined> {
483 // Use the native git extension to get the branch name
484 const extension =
485 vscode.extensions.getExtension<GitExtension>("vscode.git");
486 if (
487 typeof extension === "undefined" ||
488 !extension.isActive ||
489 typeof vscode.workspace.workspaceFolders === "undefined"
490 ) {
491 return undefined;
492 }
493
494 try {
495 const git = extension.exports.getAPI(1);
496 return git.getRepository(forDirectory) ?? undefined;
497 } catch (e) {
498 this._repoWasNone = true;
499 console.warn("Git not found: ", e);
500 return undefined;
501 }
502 }
503
504 private _getRepositories(): Repository[] | undefined {
505 const extension =
506 vscode.extensions.getExtension<GitExtension>("vscode.git");
507 if (
508 typeof extension === "undefined" ||
509 !extension.isActive ||
510 typeof vscode.workspace.workspaceFolders === "undefined"
511 ) {
512 return undefined;
513 }
514
515 try {
516 const git = extension.exports.getAPI(1);
517 return git.repositories;
518 } catch (e) {
519 this._repoWasNone = true;
520 console.warn("Git not found: ", e);
521 return undefined;
522 }
523 }
524
525 private _repoWasNone: boolean = false;
526 private repoCache: Map<string, Repository> = new Map();
527 private static secondsToWaitForGitToLoad =
528 process.env.NODE_ENV === "test" ? 1 : 20;
529 async getRepo(forDirectory: vscode.Uri): Promise<Repository | undefined> {
530 const workspaceDirs = this.getWorkspaceDirectories().map((dir) =>
531 dir.toString(),
532 );
533 const { foundInDir } = findUriInDirs(
534 forDirectory.toString(),
535 workspaceDirs,
536 );
537 if (foundInDir) {
538 // Check if the repository is already cached
539 const cachedRepo = this.repoCache.get(foundInDir);
540 if (cachedRepo) {
541 return cachedRepo;
542 }
543 }
544
545 let repo = await this._getRepo(forDirectory);
546
547 let i = 0;
548 while (!repo?.state?.HEAD?.name) {
549 if (this._repoWasNone) {
550 return undefined;
551 }
552
553 await new Promise((resolve) => setTimeout(resolve, 1000));
554 i++;
555 if (i >= VsCodeIdeUtils.secondsToWaitForGitToLoad) {
556 this._repoWasNone = true;
557 return undefined;
558 }
559 repo = await this._getRepo(forDirectory);
560 }
561
562 if (foundInDir) {
563 // Cache the repository for the parent directory
564 this.repoCache.set(foundInDir, repo);
565 }
566
567 return repo;
568 }
569
570 async getGitRoot(forDirectory: vscode.Uri): Promise<vscode.Uri | undefined> {
571 const repo = await this.getRepo(forDirectory);
572 return repo?.rootUri;
573 }
574
575 async getBranch(forDirectory: vscode.Uri) {
576 const repo = await this.getRepo(forDirectory);
577 if (repo?.state?.HEAD?.name === undefined) {
578 try {
579 const { stdout } = await asyncExec("git rev-parse --abbrev-ref HEAD", {
580 cwd: forDirectory.fsPath,
581 });
582 return stdout?.trim() || "NONE";
583 } catch (e) {
584 return "NONE";
585 }
586 }
587
588 return repo?.state?.HEAD?.name || "NONE";
589 }
590
591 private splitDiff(diffString: string): string[] {
592 const fileDiffHeaderRegex = /(?=diff --git a\/.* b\/.*)/;
593
594 const diffs = diffString.split(fileDiffHeaderRegex);
595
596 if (diffs[0].trim() === "") {
597 diffs.shift();
598 }
599
600 return diffs;
601 }
602
603 async getDiff(includeUnstaged: boolean): Promise<string[]> {
604 const diffs: string[] = [];
605
606 const repos = this._getRepositories();
607
608 try {
609 if (repos) {
610 for (const repo of repos) {
611
612 const staged = await repo.diff(true);
613
614 diffs.push(staged);
615 if (includeUnstaged) {
616 const unstaged = await repo.diff(false);
617 diffs.push(unstaged);
618 }
619 }
620 }
621
622 return diffs.flatMap((diff) => this.splitDiff(diff));
623
624 } catch (e) {
625 console.error(e);
626 return [];
627 }
628
629 }
630}