Elffuss BraidHub

kikocis/continue public

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