Elffuss BraidHub

kikocis/continue public

9d5865e0e05b · 19.4 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 * as URI from "uri-js";
7import * as vscode from "vscode";
8
9import {
10 executeGotoProvider,
11 executeSignatureHelpProvider,
12 executeSymbolProvider,
13} from "./autocomplete/lsp";
14import { Repository } from "./otherExtensions/git";
15import { SecretStorage } from "./stubs/SecretStorage";
16import { VsCodeIdeUtils } from "./util/ideUtils";
17import { getExtensionUri, openEditorAndRevealRange } from "./util/vscode";
18import { VsCodeWebviewProtocol } from "./webviewProtocol";
19
20import type {
21 DocumentSymbol,
22 FileStatsMap,
23 FileType,
24 IDE,
25 IdeInfo,
26 IdeSettings,
27 IndexTag,
28 Location,
29 Problem,
30 RangeInFile,
31 SignatureHelp,
32 TerminalOptions,
33 Thread,
34} from "core";
35import { getExtensionVersion, isExtensionPrerelease } from "./util/util";
36
37class VsCodeIde implements IDE {
38 ideUtils: VsCodeIdeUtils;
39 secretStorage: SecretStorage;
40
41 constructor(
42 private readonly vscodeWebviewProtocolPromise: Promise<VsCodeWebviewProtocol>,
43 private readonly context: vscode.ExtensionContext,
44 ) {
45 this.ideUtils = new VsCodeIdeUtils();
46 this.secretStorage = new SecretStorage(context);
47 }
48
49 async readSecrets(keys: string[]): Promise<Record<string, string>> {
50 const secretValuePromises = keys.map((key) => this.secretStorage.get(key));
51 const secretValues = await Promise.all(secretValuePromises);
52
53 return keys.reduce(
54 (acc, key, index) => {
55 if (secretValues[index] === undefined) {
56 return acc;
57 }
58
59 acc[key] = secretValues[index];
60 return acc;
61 },
62 {} as Record<string, string>,
63 );
64 }
65
66 async writeSecrets(secrets: { [key: string]: string }): Promise<void> {
67 for (const [key, value] of Object.entries(secrets)) {
68 await this.secretStorage.store(key, value);
69 }
70 }
71
72 async fileExists(uri: string): Promise<boolean> {
73 try {
74 const stat = await this.ideUtils.stat(vscode.Uri.parse(uri));
75 return stat !== null;
76 } catch (error) {
77 if (error instanceof vscode.FileSystemError) {
78 return false;
79 }
80 throw error;
81 }
82 }
83
84 async gotoDefinition(location: Location): Promise<RangeInFile[]> {
85 const result = await executeGotoProvider({
86 uri: vscode.Uri.parse(location.filepath),
87 line: location.position.line,
88 character: location.position.character,
89 name: "vscode.executeDefinitionProvider",
90 });
91
92 return result;
93 }
94
95 async gotoTypeDefinition(location: Location): Promise<RangeInFile[]> {
96 const result = await executeGotoProvider({
97 uri: vscode.Uri.parse(location.filepath),
98 line: location.position.line,
99 character: location.position.character,
100 name: "vscode.executeTypeDefinitionProvider",
101 });
102
103 return result;
104 }
105
106 async getSignatureHelp(location: Location): Promise<SignatureHelp | null> {
107 const result = await executeSignatureHelpProvider({
108 uri: vscode.Uri.parse(location.filepath),
109 line: location.position.line,
110 character: location.position.character,
111 name: "vscode.executeSignatureHelpProvider",
112 });
113
114 return result;
115 }
116
117 async getReferences(location: Location): Promise<RangeInFile[]> {
118 const result = await executeGotoProvider({
119 uri: vscode.Uri.parse(location.filepath),
120 line: location.position.line,
121 character: location.position.character,
122 name: "vscode.executeReferenceProvider",
123 });
124
125 return result;
126 }
127
128 async getDocumentSymbols(
129 textDocumentIdentifier: string, // uri
130 ): Promise<DocumentSymbol[]> {
131 const result = await executeSymbolProvider({
132 uri: vscode.Uri.parse(textDocumentIdentifier),
133 name: "vscode.executeDocumentSymbolProvider",
134 });
135
136 return result;
137 }
138
139 onDidChangeActiveTextEditor(callback: (uri: string) => void): void {
140 vscode.window.onDidChangeActiveTextEditor((editor) => {
141 if (editor) {
142 callback(editor.document.uri.toString());
143 }
144 });
145 }
146
147 showToast: IDE["showToast"] = async (...params) => {
148 const [type, message, ...otherParams] = params;
149 const { showErrorMessage, showWarningMessage, showInformationMessage } =
150 vscode.window;
151
152 switch (type) {
153 case "error":
154 return showErrorMessage(message, "Show logs").then((selection) => {
155 if (selection === "Show logs") {
156 vscode.commands.executeCommand("workbench.action.toggleDevTools");
157 }
158 });
159 case "info":
160 return showInformationMessage(message, ...otherParams);
161 case "warning":
162 return showWarningMessage(message, ...otherParams);
163 }
164 };
165
166 async getRepoName(dir: string): Promise<string | undefined> {
167 const repo = await this.getRepo(dir);
168 const remotes = repo?.state.remotes;
169 if (!remotes) {
170 return undefined;
171 }
172 const remote =
173 remotes?.find((r: any) => r.name === "origin") ?? remotes?.[0];
174 if (!remote) {
175 return undefined;
176 }
177 const ownerAndRepo = remote.fetchUrl
178 ?.replace(".git", "")
179 .split("/")
180 .slice(-2);
181 return ownerAndRepo?.join("/");
182 }
183
184 async getTags(artifactId: string): Promise<IndexTag[]> {
185 const workspaceDirs = await this.getWorkspaceDirs();
186
187 const branches = await Promise.all(
188 workspaceDirs.map((dir) => this.getBranch(dir)),
189 );
190
191 const tags: IndexTag[] = workspaceDirs.map((directory, i) => ({
192 directory,
193 branch: branches[i],
194 artifactId,
195 }));
196
197 return tags;
198 }
199
200 getIdeInfo(): Promise<IdeInfo> {
201 return Promise.resolve({
202 ideType: "vscode",
203 name: vscode.env.appName,
204 version: vscode.version,
205 remoteName: vscode.env.remoteName || "local",
206 extensionVersion: getExtensionVersion(),
207 isPrerelease: isExtensionPrerelease(),
208 });
209 }
210
211 readRangeInFile(fileUri: string, range: Range): Promise<string> {
212 return this.ideUtils.readRangeInFile(
213 vscode.Uri.parse(fileUri),
214 new vscode.Range(
215 new vscode.Position(range.start.line, range.start.character),
216 new vscode.Position(range.end.line, range.end.character),
217 ),
218 );
219 }
220
221 async getFileStats(files: string[]): Promise<FileStatsMap> {
222 const pathToLastModified: FileStatsMap = {};
223 await Promise.all(
224 files.map(async (file) => {
225 const stat = await this.ideUtils.stat(
226 vscode.Uri.parse(file),
227 false /* No need to catch ENOPRO exceptions */,
228 );
229 pathToLastModified[file] = {
230 lastModified: stat!.mtime,
231 size: stat!.size,
232 };
233 }),
234 );
235
236 return pathToLastModified;
237 }
238
239 async getRepo(dir: string): Promise<Repository | undefined> {
240 return this.ideUtils.getRepo(vscode.Uri.parse(dir));
241 }
242
243 async isTelemetryEnabled(): Promise<boolean> {
244 const globalEnabled = vscode.env.isTelemetryEnabled;
245 const continueEnabled: boolean =
246 (await vscode.workspace
247 .getConfiguration(EXTENSION_NAME)
248 .get("telemetryEnabled")) ?? true;
249 return globalEnabled && continueEnabled;
250 }
251
252 isWorkspaceRemote(): Promise<boolean> {
253 return Promise.resolve(vscode.env.remoteName !== undefined);
254 }
255
256 getUniqueId(): Promise<string> {
257 return Promise.resolve(vscode.env.machineId);
258 }
259
260 async getDiff(includeUnstaged: boolean): Promise<string[]> {
261 return await this.ideUtils.getDiff(includeUnstaged);
262 }
263
264 async getClipboardContent() {
265 return {
266 text: await vscode.env.clipboard.readText(),
267 copiedAt: new Date().toISOString(),
268 };
269 }
270
271 async getTerminalContents(): Promise<string> {
272 return await this.ideUtils.getTerminalContents(1);
273 }
274
275 async getDebugLocals(threadIndex: number): Promise<string> {
276 return await this.ideUtils.getDebugLocals(threadIndex);
277 }
278
279 async getTopLevelCallStackSources(
280 threadIndex: number,
281 stackDepth: number,
282 ): Promise<string[]> {
283 return await this.ideUtils.getTopLevelCallStackSources(
284 threadIndex,
285 stackDepth,
286 );
287 }
288 async getAvailableThreads(): Promise<Thread[]> {
289 return await this.ideUtils.getAvailableThreads();
290 }
291
292 async getWorkspaceDirs(): Promise<string[]> {
293 return this.ideUtils.getWorkspaceDirectories().map((uri) => uri.toString());
294 }
295
296 async writeFile(fileUri: string, contents: string): Promise<void> {
297 await vscode.workspace.fs.writeFile(
298 vscode.Uri.parse(fileUri),
299 Buffer.from(contents),
300 );
301 }
302
303 async showVirtualFile(title: string, contents: string): Promise<void> {
304 this.ideUtils.showVirtualFile(title, contents);
305 }
306
307 async openFile(fileUri: string): Promise<void> {
308 await this.ideUtils.openFile(vscode.Uri.parse(fileUri));
309 }
310
311 async showLines(
312 fileUri: string,
313 startLine: number,
314 endLine: number,
315 ): Promise<void> {
316 const range = new vscode.Range(
317 new vscode.Position(startLine, 0),
318 new vscode.Position(endLine, 0),
319 );
320 openEditorAndRevealRange(vscode.Uri.parse(fileUri), range).then(
321 (editor) => {
322 // Select the lines
323 editor.selection = new vscode.Selection(
324 new vscode.Position(startLine, 0),
325 new vscode.Position(endLine, 0),
326 );
327 },
328 );
329 }
330
331 async runCommand(
332 command: string,
333 options: TerminalOptions = { reuseTerminal: true },
334 ): Promise<void> {
335 let terminal: vscode.Terminal | undefined;
336 if (vscode.window.terminals.length && options.reuseTerminal) {
337 if (options.terminalName) {
338 terminal = vscode.window.terminals.find(
339 (t) => t?.name === options.terminalName,
340 );
341 } else {
342 terminal = vscode.window.activeTerminal ?? vscode.window.terminals[0];
343 }
344 }
345
346 if (!terminal) {
347 terminal = vscode.window.createTerminal(options?.terminalName);
348 }
349 terminal.show();
350 terminal.sendText(command, false);
351 }
352
353 async saveFile(fileUri: string): Promise<void> {
354 await this.ideUtils.saveFile(vscode.Uri.parse(fileUri));
355 }
356
357 private static MAX_BYTES = 100000;
358
359 async readFile(fileUri: string): Promise<string> {
360 try {
361 const uri = vscode.Uri.parse(fileUri);
362
363 // First, check whether it's a notebook document
364 // Need to iterate over the cells to get full contents
365 const notebook =
366 vscode.workspace.notebookDocuments.find((doc) =>
367 URI.equal(doc.uri.toString(), uri.toString()),
368 ) ??
369 (uri.path.endsWith("ipynb")
370 ? await vscode.workspace.openNotebookDocument(uri)
371 : undefined);
372 if (notebook) {
373 return notebook
374 .getCells()
375 .map((cell) => cell.document.getText())
376 .join("\n\n");
377 }
378
379 // Check whether it's an open document
380 const openTextDocument = vscode.workspace.textDocuments.find((doc) =>
381 URI.equal(doc.uri.toString(), uri.toString()),
382 );
383 if (openTextDocument !== undefined) {
384 return openTextDocument.getText();
385 }
386
387 const fileStats = await this.ideUtils.stat(uri);
388 if (fileStats === null || fileStats.size > 10 * VsCodeIde.MAX_BYTES) {
389 return "";
390 }
391
392 const bytes = await this.ideUtils.readFile(uri);
393 if (bytes === null) {
394 return "";
395 }
396
397 // Truncate the buffer to the first MAX_BYTES
398 const truncatedBytes = bytes.slice(0, VsCodeIde.MAX_BYTES);
399 const contents = new TextDecoder().decode(truncatedBytes);
400 return contents;
401 } catch (e) {
402 return "";
403 }
404 }
405
406 async openUrl(url: string): Promise<void> {
407 await vscode.env.openExternal(vscode.Uri.parse(url));
408 }
409
410 async getOpenFiles(): Promise<string[]> {
411 return this.ideUtils.getOpenFiles().map((uri) => uri.toString());
412 }
413
414 async getCurrentFile() {
415 if (!vscode.window.activeTextEditor) {
416 return undefined;
417 }
418 return {
419 isUntitled: vscode.window.activeTextEditor.document.isUntitled,
420 path: vscode.window.activeTextEditor.document.uri.toString(),
421 contents: vscode.window.activeTextEditor.document.getText(),
422 };
423 }
424
425 async getPinnedFiles(): Promise<string[]> {
426 const tabArray = vscode.window.tabGroups.all[0].tabs;
427
428 return tabArray
429 .filter((t) => t.isPinned)
430 .map((t) => (t.input as vscode.TabInputText).uri.toString());
431 }
432
433 runRipgrepQuery(dirUri: string, args: string[]) {
434 const relativeDir = vscode.Uri.parse(dirUri).fsPath;
435 const ripGrepUri = vscode.Uri.joinPath(
436 getExtensionUri(),
437 "out/node_modules/@vscode/ripgrep/bin/rg",
438 );
439 const p = child_process.spawn(ripGrepUri.fsPath, args, {
440 cwd: relativeDir,
441 });
442 let output = "";
443
444 p.stdout.on("data", (data) => {
445 output += data.toString();
446 });
447
448 return new Promise<string>((resolve, reject) => {
449 p.on("error", reject);
450 p.on("close", (code) => {
451 if (code === 0) {
452 resolve(output);
453 } else if (code === 1) {
454 // No matches
455 resolve("No matches found");
456 } else {
457 reject(new Error(`Process exited with code ${code}`));
458 }
459 });
460 });
461 }
462
463 async getFileResults(
464 pattern: string,
465 maxResults?: number,
466 ): Promise<string[]> {
467 if (vscode.env.remoteName) {
468 // TODO better tests for this remote search implementation
469 // throw new Error("Ripgrep not supported, this workspace is remote");
470
471 // IMPORTANT: findFiles automatically accounts for .gitignore
472 const ignoreFiles = await vscode.workspace.findFiles(
473 "**/.continueignore",
474 null,
475 );
476
477 const ignoreGlobs: Set<string> = new Set();
478 for (const file of ignoreFiles) {
479 const content = await this.ideUtils.readFile(file);
480 if (content === null) {
481 continue;
482 }
483 const filePath = vscode.workspace.asRelativePath(file);
484 const fileDir = filePath
485 .replace(/\\/g, "/")
486 .replace(/\/$/, "")
487 .split("/")
488 .slice(0, -1)
489 .join("/");
490
491 const patterns = Buffer.from(content)
492 .toString()
493 .split("\n")
494 .map((line) => line.trim())
495 .filter(
496 (line) => line && !line.startsWith("#") && !pattern.startsWith("!"),
497 );
498 // VSCode does not support negations
499
500 patterns
501 // Handle prefix
502 .map((pattern) => {
503 const normalizedPattern = pattern.replace(/\\/g, "/");
504
505 if (normalizedPattern.startsWith("/")) {
506 if (fileDir) {
507 return `{/,}${normalizedPattern}`;
508 } else {
509 return `${fileDir}/${normalizedPattern.substring(1)}`;
510 }
511 } else {
512 if (fileDir) {
513 return `${fileDir}/${normalizedPattern}`;
514 } else {
515 return `**/${normalizedPattern}`;
516 }
517 }
518 })
519 // Handle suffix
520 .map((pattern) => {
521 return pattern.endsWith("/") ? `${pattern}**/*` : pattern;
522 })
523 .forEach((pattern) => {
524 ignoreGlobs.add(pattern);
525 });
526 }
527
528 const ignoreGlobsArray = Array.from(ignoreGlobs);
529
530 const results = await vscode.workspace.findFiles(
531 pattern,
532 ignoreGlobs.size ? `{${ignoreGlobsArray.join(",")}}` : null,
533 maxResults,
534 );
535 return results.map((result) => vscode.workspace.asRelativePath(result));
536 } else {
537 const results: string[] = [];
538 for (const dir of await this.getWorkspaceDirs()) {
539 const dirResults = await this.runRipgrepQuery(dir, [
540 "--files",
541 "--iglob",
542 pattern,
543 "--ignore-file",
544 ".continueignore",
545 "--ignore-file",
546 ".gitignore",
547 ...(maxResults ? ["--max-count", String(maxResults)] : []),
548 ]);
549
550 results.push(dirResults);
551 }
552
553 const allResults = results.join("\n").split("\n");
554 if (maxResults) {
555 // In the case of multiple workspaces, maxResults will be applied to each workspace
556 // And then the combined results will also be truncated
557 return allResults.slice(0, maxResults);
558 } else {
559 return allResults;
560 }
561 }
562 }
563
564 async getSearchResults(query: string, maxResults?: number): Promise<string> {
565 if (vscode.env.remoteName) {
566 throw new Error("Ripgrep not supported, this workspace is remote");
567 }
568 const results: string[] = [];
569 for (const dir of await this.getWorkspaceDirs()) {
570 const dirResults = await this.runRipgrepQuery(dir, [
571 "-i", // Case-insensitive search
572 "--ignore-file",
573 ".continueignore",
574 "--ignore-file",
575 ".gitignore",
576 "-C",
577 "2", // Show 2 lines of context
578 "--heading", // Only show filepath once per result
579 ...(maxResults ? ["-m", maxResults.toString()] : []),
580 "-e",
581 query, // Pattern to search for
582 ".", // Directory to search in
583 ]);
584
585 results.push(dirResults);
586 }
587
588 const allResults = results.join("\n");
589 if (maxResults) {
590 // In case of multiple workspaces, do max results per workspace and then truncate to maxResults
591 // Will prioritize first workspace results, fine for now
592 // Results are separated by either ./ or --
593 const matches = Array.from(allResults.matchAll(/(\n--|\n\.\/)/g));
594 if (matches.length > maxResults) {
595 return allResults.substring(0, matches[maxResults].index);
596 } else {
597 return allResults;
598 }
599 } else {
600 return allResults;
601 }
602 }
603
604 async getProblems(fileUri?: string | undefined): Promise<Problem[]> {
605 const uri = fileUri
606 ? vscode.Uri.parse(fileUri)
607 : vscode.window.activeTextEditor?.document.uri;
608 if (!uri) {
609 return [];
610 }
611 return vscode.languages.getDiagnostics(uri).map((d) => {
612 return {
613 filepath: uri.toString(),
614 range: {
615 start: {
616 line: d.range.start.line,
617 character: d.range.start.character,
618 },
619 end: { line: d.range.end.line, character: d.range.end.character },
620 },
621 message: d.message,
622 };
623 });
624 }
625
626 async subprocess(command: string, cwd?: string): Promise<[string, string]> {
627 return new Promise((resolve, reject) => {
628 exec(command, { cwd }, (error, stdout, stderr) => {
629 if (error) {
630 console.warn(error);
631 reject(stderr);
632 }
633 resolve([stdout, stderr]);
634 });
635 });
636 }
637
638 async getBranch(dir: string): Promise<string> {
639 return this.ideUtils.getBranch(vscode.Uri.parse(dir));
640 }
641
642 async getGitRootPath(dir: string): Promise<string | undefined> {
643 const root = await this.ideUtils.getGitRoot(vscode.Uri.parse(dir));
644 return root?.toString();
645 }
646
647 async listDir(dir: string): Promise<[string, FileType][]> {
648 const entries = await this.ideUtils.readDirectory(vscode.Uri.parse(dir));
649 return entries === null ? [] : (entries as any);
650 }
651
652 private getIdeSettingsSync(): IdeSettings {
653 const settings = vscode.workspace.getConfiguration(EXTENSION_NAME);
654 const remoteConfigServerUrl = settings.get<string | undefined>(
655 "remoteConfigServerUrl",
656 undefined,
657 );
658 const ideSettings: IdeSettings = {
659 remoteConfigServerUrl,
660 remoteConfigSyncPeriod: settings.get<number>(
661 "remoteConfigSyncPeriod",
662 60,
663 ),
664 userToken: settings.get<string>("userToken", ""),
665 continueTestEnvironment: "production",
666 pauseCodebaseIndexOnStart: settings.get<boolean>(
667 "pauseCodebaseIndexOnStart",
668 false,
669 ),
670 };
671 return ideSettings;
672 }
673
674 async getIdeSettings(): Promise<IdeSettings> {
675 const ideSettings = this.getIdeSettingsSync();
676 return ideSettings;
677 }
678}
679
680export { VsCodeIde };