Elffuss BraidHub

kikocis/continue public

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