Elffuss BraidHub

kikocis/continue public

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