Elffuss BraidHub

kikocis/continue public

db0553d9db9f · 17.8 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(pattern: string): Promise<string[]> {
437 const MAX_FILE_RESULTS = 200;
438 if (vscode.env.remoteName) {
439 // TODO better tests for this remote search implementation
440 // throw new Error("Ripgrep not supported, this workspace is remote");
441
442 // IMPORTANT: findFiles automatically accounts for .gitignore
443 const ignoreFiles = await vscode.workspace.findFiles(
444 "**/.continueignore",
445 null,
446 );
447
448 const ignoreGlobs: Set<string> = new Set();
449 for (const file of ignoreFiles) {
450 const content = await this.ideUtils.readFile(file);
451 if (content === null) {
452 continue;
453 }
454 const filePath = vscode.workspace.asRelativePath(file);
455 const fileDir = filePath
456 .replace(/\\/g, "/")
457 .replace(/\/$/, "")
458 .split("/")
459 .slice(0, -1)
460 .join("/");
461
462 const patterns = Buffer.from(content)
463 .toString()
464 .split("\n")
465 .map((line) => line.trim())
466 .filter(
467 (line) => line && !line.startsWith("#") && !pattern.startsWith("!"),
468 );
469 // VSCode does not support negations
470
471 patterns
472 // Handle prefix
473 .map((pattern) => {
474 const normalizedPattern = pattern.replace(/\\/g, "/");
475
476 if (normalizedPattern.startsWith("/")) {
477 if (fileDir) {
478 return `{/,}${normalizedPattern}`;
479 } else {
480 return `${fileDir}/${normalizedPattern.substring(1)}`;
481 }
482 } else {
483 if (fileDir) {
484 return `${fileDir}/${normalizedPattern}`;
485 } else {
486 return `**/${normalizedPattern}`;
487 }
488 }
489 })
490 // Handle suffix
491 .map((pattern) => {
492 return pattern.endsWith("/") ? `${pattern}**/*` : pattern;
493 })
494 .forEach((pattern) => {
495 ignoreGlobs.add(pattern);
496 });
497 }
498
499 const ignoreGlobsArray = Array.from(ignoreGlobs);
500
501 const results = await vscode.workspace.findFiles(
502 pattern,
503 ignoreGlobs.size ? `{${ignoreGlobsArray.join(",")}}` : null,
504 MAX_FILE_RESULTS,
505 );
506 return results.map((result) => vscode.workspace.asRelativePath(result));
507 } else {
508 const results: string[] = [];
509 for (const dir of await this.getWorkspaceDirs()) {
510 const dirResults = await this.runRipgrepQuery(dir, [
511 "--files",
512 "--iglob",
513 pattern,
514 "--ignore-file",
515 ".continueignore",
516 "--ignore-file",
517 ".gitignore",
518 ]);
519
520 results.push(dirResults);
521 }
522
523 return results.join("\n").split("\n").slice(0, MAX_FILE_RESULTS);
524 }
525 }
526
527 async getSearchResults(query: string): Promise<string> {
528 if (vscode.env.remoteName) {
529 throw new Error("Ripgrep not supported, this workspace is remote");
530 }
531 const results: string[] = [];
532 for (const dir of await this.getWorkspaceDirs()) {
533 const dirResults = await this.runRipgrepQuery(dir, [
534 "-i", // Case-insensitive search
535 "--ignore-file",
536 ".continueignore",
537 "--ignore-file",
538 ".gitignore",
539 "-C",
540 "2", // Show 2 lines of context
541 "--heading", // Only show filepath once per result
542 "-e",
543 query, // Pattern to search for
544 ".", // Directory to search in
545 ]);
546
547 results.push(dirResults);
548 }
549
550 return results.join("\n");
551 }
552
553 async getProblems(fileUri?: string | undefined): Promise<Problem[]> {
554 const uri = fileUri
555 ? vscode.Uri.parse(fileUri)
556 : vscode.window.activeTextEditor?.document.uri;
557 if (!uri) {
558 return [];
559 }
560 return vscode.languages.getDiagnostics(uri).map((d) => {
561 return {
562 filepath: uri.toString(),
563 range: {
564 start: {
565 line: d.range.start.line,
566 character: d.range.start.character,
567 },
568 end: { line: d.range.end.line, character: d.range.end.character },
569 },
570 message: d.message,
571 };
572 });
573 }
574
575 async subprocess(command: string, cwd?: string): Promise<[string, string]> {
576 return new Promise((resolve, reject) => {
577 exec(command, { cwd }, (error, stdout, stderr) => {
578 if (error) {
579 console.warn(error);
580 reject(stderr);
581 }
582 resolve([stdout, stderr]);
583 });
584 });
585 }
586
587 async getBranch(dir: string): Promise<string> {
588 return this.ideUtils.getBranch(vscode.Uri.parse(dir));
589 }
590
591 async getGitRootPath(dir: string): Promise<string | undefined> {
592 const root = await this.ideUtils.getGitRoot(vscode.Uri.parse(dir));
593 return root?.toString();
594 }
595
596 async listDir(dir: string): Promise<[string, FileType][]> {
597 const entries = await this.ideUtils.readDirectory(vscode.Uri.parse(dir));
598 return entries === null ? [] : (entries as any);
599 }
600
601 private getIdeSettingsSync(): IdeSettings {
602 const settings = vscode.workspace.getConfiguration(EXTENSION_NAME);
603 const remoteConfigServerUrl = settings.get<string | undefined>(
604 "remoteConfigServerUrl",
605 undefined,
606 );
607 const ideSettings: IdeSettings = {
608 remoteConfigServerUrl,
609 remoteConfigSyncPeriod: settings.get<number>(
610 "remoteConfigSyncPeriod",
611 60,
612 ),
613 userToken: settings.get<string>("userToken", ""),
614 continueTestEnvironment: "production",
615 pauseCodebaseIndexOnStart: settings.get<boolean>(
616 "pauseCodebaseIndexOnStart",
617 false,
618 ),
619 };
620 return ideSettings;
621 }
622
623 async getIdeSettings(): Promise<IdeSettings> {
624 const ideSettings = this.getIdeSettingsSync();
625 return ideSettings;
626 }
627}
628
629export { VsCodeIde };