Elffuss BraidHub

kikocis/continue public

b06f5503dce8 · 20.0 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 getOpenFiles(): Promise<string[]> {
412 return this.ideUtils.getOpenFiles().map((uri) => uri.toString());
413 }
414
415 async getCurrentFile() {
416 if (!vscode.window.activeTextEditor) {
417 return undefined;
418 }
419 return {
420 isUntitled: vscode.window.activeTextEditor.document.isUntitled,
421 path: vscode.window.activeTextEditor.document.uri.toString(),
422 contents: vscode.window.activeTextEditor.document.getText(),
423 };
424 }
425
426 async getPinnedFiles(): Promise<string[]> {
427 const tabArray = vscode.window.tabGroups.all[0].tabs;
428
429 return tabArray
430 .filter((t) => t.isPinned)
431 .map((t) => (t.input as vscode.TabInputText).uri.toString());
432 }
433
434 runRipgrepQuery(dirUri: string, args: string[]) {
435 const relativeDir = vscode.Uri.parse(dirUri).fsPath;
436 const ripGrepUri = vscode.Uri.joinPath(
437 getExtensionUri(),
438 "out/node_modules/@vscode/ripgrep/bin/rg",
439 );
440 const p = child_process.spawn(ripGrepUri.fsPath, args, {
441 cwd: relativeDir,
442 });
443 let output = "";
444
445 p.stdout.on("data", (data) => {
446 output += data.toString();
447 });
448
449 return new Promise<string>((resolve, reject) => {
450 p.on("error", reject);
451 p.on("close", (code) => {
452 if (code === 0) {
453 resolve(output);
454 } else if (code === 1) {
455 // No matches
456 resolve(
457 "No matches found. Build, secrets, etc. dirs and files are not included.",
458 );
459 } else {
460 reject(new Error(`Process exited with code ${code}`));
461 }
462 });
463 });
464 }
465
466 async getFileResults(
467 pattern: string,
468 maxResults?: number,
469 ): Promise<string[]> {
470 // Create a single combined ignore pattern for ripgrep (calculated once)
471
472 if (vscode.env.remoteName) {
473 // TODO better tests for this remote search implementation
474 // throw new Error("Ripgrep not supported, this workspace is remote");
475
476 // IMPORTANT: findFiles automatically accounts for .gitignore
477 const ignoreFiles = await vscode.workspace.findFiles(
478 "**/.continueignore",
479 null,
480 );
481
482 const ignoreGlobs: Set<string> = new Set();
483 // Add default ignores from core
484 for (const pattern of DEFAULT_IGNORES) {
485 ignoreGlobs.add(pattern);
486 }
487
488 for (const file of ignoreFiles) {
489 const content = await this.ideUtils.readFile(file);
490 if (content === null) {
491 continue;
492 }
493 const filePath = vscode.workspace.asRelativePath(file);
494 const fileDir = filePath
495 .replace(/\\/g, "/")
496 .replace(/\/$/, "")
497 .split("/")
498 .slice(0, -1)
499 .join("/");
500
501 const patterns = Buffer.from(content)
502 .toString()
503 .split("\n")
504 .map((line) => line.trim())
505 .filter(
506 (line) => line && !line.startsWith("#") && !pattern.startsWith("!"),
507 );
508 // VSCode does not support negations
509
510 patterns
511 // Handle prefix
512 .map((pattern) => {
513 const normalizedPattern = pattern.replace(/\\/g, "/");
514
515 if (normalizedPattern.startsWith("/")) {
516 if (fileDir) {
517 return `{/,}${normalizedPattern}`;
518 } else {
519 return `${fileDir}/${normalizedPattern.substring(1)}`;
520 }
521 } else {
522 if (fileDir) {
523 return `${fileDir}/${normalizedPattern}`;
524 } else {
525 return `**/${normalizedPattern}`;
526 }
527 }
528 })
529 // Handle suffix
530 .map((pattern) => {
531 return pattern.endsWith("/") ? `${pattern}**/*` : pattern;
532 })
533 .forEach((pattern) => {
534 ignoreGlobs.add(pattern);
535 });
536 }
537
538 const ignoreGlobsArray = Array.from(ignoreGlobs);
539
540 const results = await vscode.workspace.findFiles(
541 pattern,
542 ignoreGlobs.size ? `{${ignoreGlobsArray.join(",")}}` : null,
543 maxResults,
544 );
545 return results.map((result) => vscode.workspace.asRelativePath(result));
546 } else {
547 const results: string[] = [];
548 // Create a single combined ignore pattern using glob brace expansion
549 for (const dir of await this.getWorkspaceDirs()) {
550 const dirResults = await this.runRipgrepQuery(dir, [
551 "--files",
552 "--iglob",
553 pattern,
554 "--ignore-file",
555 ".continueignore",
556 "--ignore-file",
557 ".gitignore",
558 "--glob",
559 defaultIgnoresGlob,
560 ...(maxResults ? ["--max-count", String(maxResults)] : []),
561 ]);
562
563 results.push(dirResults);
564 }
565
566 const allResults = results.join("\n").split("\n");
567 if (maxResults) {
568 // In the case of multiple workspaces, maxResults will be applied to each workspace
569 // And then the combined results will also be truncated
570 return allResults.slice(0, maxResults);
571 } else {
572 return allResults;
573 }
574 }
575 }
576
577 async getSearchResults(query: string, maxResults?: number): Promise<string> {
578 if (vscode.env.remoteName) {
579 throw new Error("Ripgrep not supported, this workspace is remote");
580 }
581 const results: string[] = [];
582
583 for (const dir of await this.getWorkspaceDirs()) {
584 const dirResults = await this.runRipgrepQuery(dir, [
585 "-i", // Case-insensitive search
586 "--ignore-file",
587 ".continueignore",
588 "--ignore-file",
589 ".gitignore",
590 "-C",
591 "2", // Show 2 lines of context
592 "--heading", // Only show filepath once per result
593 // Use a single glob with all default ignores
594 "--glob",
595 defaultIgnoresGlob,
596 ...(maxResults ? ["-m", maxResults.toString()] : []),
597 "-e",
598 query, // Pattern to search for
599 ".", // Directory to search in
600 ]);
601
602 results.push(dirResults);
603 }
604
605 const allResults = results.join("\n");
606 if (maxResults) {
607 // In case of multiple workspaces, do max results per workspace and then truncate to maxResults
608 // Will prioritize first workspace results, fine for now
609 // Results are separated by either ./ or --
610 const matches = Array.from(allResults.matchAll(/(\n--|\n\.\/)/g));
611 if (matches.length > maxResults) {
612 return allResults.substring(0, matches[maxResults].index);
613 } else {
614 return allResults;
615 }
616 } else {
617 return allResults;
618 }
619 }
620
621 async getProblems(fileUri?: string | undefined): Promise<Problem[]> {
622 const uri = fileUri
623 ? vscode.Uri.parse(fileUri)
624 : vscode.window.activeTextEditor?.document.uri;
625 if (!uri) {
626 return [];
627 }
628 return vscode.languages.getDiagnostics(uri).map((d) => {
629 return {
630 filepath: uri.toString(),
631 range: {
632 start: {
633 line: d.range.start.line,
634 character: d.range.start.character,
635 },
636 end: { line: d.range.end.line, character: d.range.end.character },
637 },
638 message: d.message,
639 };
640 });
641 }
642
643 async subprocess(command: string, cwd?: string): Promise<[string, string]> {
644 return new Promise((resolve, reject) => {
645 exec(command, { cwd }, (error, stdout, stderr) => {
646 if (error) {
647 console.warn(error);
648 reject(stderr);
649 }
650 resolve([stdout, stderr]);
651 });
652 });
653 }
654
655 async getBranch(dir: string): Promise<string> {
656 return this.ideUtils.getBranch(vscode.Uri.parse(dir));
657 }
658
659 async getGitRootPath(dir: string): Promise<string | undefined> {
660 const root = await this.ideUtils.getGitRoot(vscode.Uri.parse(dir));
661 return root?.toString();
662 }
663
664 async listDir(dir: string): Promise<[string, FileType][]> {
665 const entries = await this.ideUtils.readDirectory(vscode.Uri.parse(dir));
666 return entries === null ? [] : (entries as any);
667 }
668
669 private getIdeSettingsSync(): IdeSettings {
670 const settings = vscode.workspace.getConfiguration(EXTENSION_NAME);
671 const remoteConfigServerUrl = settings.get<string | undefined>(
672 "remoteConfigServerUrl",
673 undefined,
674 );
675 const ideSettings: IdeSettings = {
676 remoteConfigServerUrl,
677 remoteConfigSyncPeriod: settings.get<number>(
678 "remoteConfigSyncPeriod",
679 60,
680 ),
681 userToken: settings.get<string>("userToken", ""),
682 continueTestEnvironment: "production",
683 pauseCodebaseIndexOnStart: settings.get<boolean>(
684 "pauseCodebaseIndexOnStart",
685 false,
686 ),
687 };
688 return ideSettings;
689 }
690
691 async getIdeSettings(): Promise<IdeSettings> {
692 const ideSettings = this.getIdeSettingsSync();
693 return ideSettings;
694 }
695}
696
697export { VsCodeIde };