Elffuss BraidHub

kikocis/continue public

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