Elffuss BraidHub

kikocis/continue public

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