Elffuss BraidHub

kikocis/continue public

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