move Spring Cli commands implementation to language server

This commit is contained in:
vudayani
2024-09-28 17:11:58 +05:30
committed by Martin Lippert
parent 3d18619e98
commit f9949d6480
42 changed files with 2099 additions and 144 deletions

View File

@@ -24,7 +24,6 @@ import { startTestJarSupport } from "./test-jar-launch";
import { startPropertiesConversionSupport } from "./convert-props-yaml";
import { activateCopilotFeatures } from "./copilot";
import * as springBootAgent from './copilot/springBootAgent';
import { SpringCli } from './copilot/springCli';
import { applyLspEdit } from "./copilot/guideApply";
import { isLlmApiReady } from "./copilot/util";
import CopilotRequest, { logger } from "./copilot/copilotRequest";
@@ -38,7 +37,6 @@ const JPA_QUERY_PROPERTIES_LANGUAGE_ID = "jpa-query-properties";
const STOP_ASKING = "Stop Asking";
export const SPRINGCLI = new SpringCli();
/** Called when extension is activated */
export function activate(context: ExtensionContext): Thenable<ExtensionAPI> {

View File

@@ -1,8 +1,8 @@
import { Uri, workspace, window } from "vscode";
import { SPRINGCLI } from "../Main";
import { getTargetGuideMardown } from "./util";
import { Uri, workspace, window, commands } from "vscode";
import { getTargetGuideMardown, readResponseFromFile } from "./util";
import { createConverter } from "vscode-languageclient/lib/common/protocolConverter";
import fs from "fs";
import path from "path";
const CONVERTER = createConverter(undefined, true, true);
@@ -13,11 +13,13 @@ export async function applyLspEdit(uri: Uri) {
if (!uri) {
uri = await getTargetGuideMardown();
}
const lspEdit = await SPRINGCLI.guideLspEdit(uri);
const fileContent = (await readResponseFromFile(uri)).toString();
const lspEdit = await commands.executeCommand("sts/copilot/agent/lspEdits", uri.toString(), path.dirname(uri.fsPath), fileContent);
const workspaceEdit = await CONVERTER.asWorkspaceEdit(lspEdit);
console.log(lspEdit);
await Promise.all(workspaceEdit.entries().map(async ([uri, edits]) => {
console.log(edits);
if (fs.existsSync(uri.fsPath)) {
const doc = await workspace.openTextDocument(uri.fsPath);
await window.showTextDocument(doc);

View File

@@ -3,7 +3,6 @@ import { CancellationToken, chat, ChatContext, ChatRequest, ChatResponseStream,
import { systemBoot2Prompt, systemBoot3Prompt, systemPrompt } from "./system-ai-prompt";
import { userPrompt } from "./user-ai-prompt";
import { getWorkspaceRoot, writeResponseToFile } from "./util";
import { SPRINGCLI } from "../Main";
const PARTICIPANT_ID = 'springboot.agent';
const SYSTEM_PROMPT = systemPrompt;
@@ -77,7 +76,7 @@ export default class SpringBootChatAgent {
} else {
// modify the response from copilot LLM i.e. make response Boot 3 compliant if necessary
if (bootProjInfo.springBootVersion.startsWith('3')) {
const enhancedResponse = await SPRINGCLI.enhanceResponse(targetMarkdownUri, selectedProject.fsPath);
const enhancedResponse = await commands.executeCommand("sts/copilot/agent/enhanceResponse", response) as string;
await writeResponseToFile(enhancedResponse, bootProjInfo.name, selectedProject.fsPath);
}
documentContent = await workspace.fs.readFile(targetMarkdownUri);

View File

@@ -1,121 +1,121 @@
import { ProgressLocation, Uri, window, workspace } from "vscode";
import cp from "child_process";
import * as vscode from 'vscode';
import { homedir } from "os";
import { getWorkspaceRoot, getWorkspaceRootPath } from "./util";
import path from "path";
import { WorkspaceEdit } from "vscode-languageclient";
// import { ProgressLocation, Uri, window, workspace } from "vscode";
// import cp from "child_process";
// import * as vscode from 'vscode';
// import { homedir } from "os";
// import { getWorkspaceRoot, getWorkspaceRootPath } from "./util";
// import path from "path";
// import { WorkspaceEdit } from "vscode-languageclient";
export const CANCELLED = "Cancelled";
// export const CANCELLED = "Cancelled";
export class SpringCli {
// export class SpringCli {
get executable(): string {
return workspace.getConfiguration("spring-cli").get("executable") || "spring";
}
// get executable(): string {
// return workspace.getConfiguration("spring-cli").get("executable") || "spring";
// }
guideLspEdit(uri: Uri, cwd?: string): Promise<WorkspaceEdit> {
const args = [
"guide",
"apply",
"--lsp-edit",
"--file",
uri.fsPath
];
return this.fetchJson("Applying guide", uri.fsPath, args, cwd || path.dirname(uri.fsPath), true);
}
// guideLspEdit(uri: Uri, cwd?: string): Promise<WorkspaceEdit> {
// const args = [
// "guide",
// "apply",
// "--lsp-edit",
// "--file",
// uri.fsPath
// ];
// return this.fetchJson("Applying guide", uri.fsPath, args, cwd || path.dirname(uri.fsPath), true);
// }
enhanceResponse(uri: Uri, cwd: string): Thenable<string> {
const args = [
"ai",
"enhance-response",
"--file",
uri.fsPath
];
return this.exec("Spring cli ai", "Enhance response", args, cwd);
}
// enhanceResponse(uri: Uri, cwd: string): Thenable<string> {
// const args = [
// "ai",
// "enhance-response",
// "--file",
// uri.fsPath
// ];
// return this.exec("Spring cli ai", "Enhance response", args, cwd);
// }
private async executeCommand(args: string[], cwd?: string): Promise<string> {
const processOpts = { cwd: cwd || (await getWorkspaceRoot())?.fsPath || homedir() };
const process = this.executable.endsWith(".jar") ? await cp.exec(`java -jar ${this.executable} ${args.join(" ")}`, processOpts) : await cp.exec(`${this.executable} ${args.join(" ")}`, processOpts);
const dataChunks: string[] = [];
process.stdout.on("data", s => dataChunks.push(s));
return new Promise<string>((resolve, reject) => {
process.on("exit", (code) => {
if (code) {
reject(`Failed to execute command: ${dataChunks.join()}`);
} else {
resolve(dataChunks.join());
}
});
});
}
// private async executeCommand(args: string[], cwd?: string): Promise<string> {
// const processOpts = { cwd: cwd || (await getWorkspaceRoot())?.fsPath || homedir() };
// const process = this.executable.endsWith(".jar") ? await cp.exec(`java -jar ${this.executable} ${args.join(" ")}`, processOpts) : await cp.exec(`${this.executable} ${args.join(" ")}`, processOpts);
// const dataChunks: string[] = [];
// process.stdout.on("data", s => dataChunks.push(s));
// return new Promise<string>((resolve, reject) => {
// process.on("exit", (code) => {
// if (code) {
// reject(`Failed to execute command: ${dataChunks.join()}`);
// } else {
// resolve(dataChunks.join());
// }
// });
// });
// }
private async exec<T>(title: string, message: string, args: string[], cwd?: string): Promise<T> {
return vscode.window.withProgress({
location: vscode.ProgressLocation.Window,
cancellable: true,
title,
}, async (progress, cancellation) => {
// private async exec<T>(title: string, message: string, args: string[], cwd?: string): Promise<T> {
// return vscode.window.withProgress({
// location: vscode.ProgressLocation.Window,
// cancellable: true,
// title,
// }, async (progress, cancellation) => {
if (message) {
progress.report({ message });
}
// if (message) {
// progress.report({ message });
// }
return new Promise<T>(async (resolve, reject) => {
if (cancellation.isCancellationRequested) {
reject("Cancelled");
}
try {
const output: string = await this.executeCommand(args, cwd);
resolve(output as T);
} catch (error) {
console.error(`Error: ${error}`);
reject(error);
}
});
});
}
// return new Promise<T>(async (resolve, reject) => {
// if (cancellation.isCancellationRequested) {
// reject("Cancelled");
// }
// try {
// const output: string = await this.executeCommand(args, cwd);
// resolve(output as T);
// } catch (error) {
// console.error(`Error: ${error}`);
// reject(error);
// }
// });
// });
// }
private async fetchJson<T>(title: string, message: string, args: string[], cwd?: string, omitJsonParam?: boolean): Promise<T> {
// private async fetchJson<T>(title: string, message: string, args: string[], cwd?: string, omitJsonParam?: boolean): Promise<T> {
return window.withProgress({
location: ProgressLocation.Window,
cancellable: true,
title
}, (progress, cancellation) => {
// return window.withProgress({
// location: ProgressLocation.Window,
// cancellable: true,
// title
// }, (progress, cancellation) => {
if (message) {
progress.report({ message });
}
// if (message) {
// progress.report({ message });
// }
return new Promise<T>(async (resolve, reject) => {
if (cancellation.isCancellationRequested) {
reject(CANCELLED);
}
const processOpts = { cwd: cwd || getWorkspaceRootPath()?.fsPath || homedir() };
const process = this.executable.endsWith(".jar") ? await cp.exec(`java -jar ${this.executable} ${args.join(" ")}`, processOpts) : await cp.exec(`${this.executable} ${args.join(" ")} ${omitJsonParam ? "" : "--json"}`, processOpts);
cancellation.onCancellationRequested(() => process.kill());
const dataChunks: string[] = [];
process.stdout.on("data", s => dataChunks.push(s));
process.on("exit", (code) => {
if (code) {
if (cancellation.isCancellationRequested) {
reject(CANCELLED);
} else {
reject(`Failed to fetch data: ${dataChunks.join()}`);
}
} else {
try {
resolve(JSON.parse(dataChunks.join()) as T);
} catch (error) {
reject(error);
}
}
});
});
});
}
// return new Promise<T>(async (resolve, reject) => {
// if (cancellation.isCancellationRequested) {
// reject(CANCELLED);
// }
// const processOpts = { cwd: cwd || getWorkspaceRootPath()?.fsPath || homedir() };
// const process = this.executable.endsWith(".jar") ? await cp.exec(`java -jar ${this.executable} ${args.join(" ")}`, processOpts) : await cp.exec(`${this.executable} ${args.join(" ")} ${omitJsonParam ? "" : "--json"}`, processOpts);
// cancellation.onCancellationRequested(() => process.kill());
// const dataChunks: string[] = [];
// process.stdout.on("data", s => dataChunks.push(s));
// process.on("exit", (code) => {
// if (code) {
// if (cancellation.isCancellationRequested) {
// reject(CANCELLED);
// } else {
// reject(`Failed to fetch data: ${dataChunks.join()}`);
// }
// } else {
// try {
// resolve(JSON.parse(dataChunks.join()) as T);
// } catch (error) {
// reject(error);
// }
// }
// });
// });
// });
// }
}
// }

View File

@@ -3,10 +3,6 @@ import { Uri, WorkspaceFolder, version, window, workspace } from "vscode";
import fs from "fs";
import { SemVer } from "semver";
export function getExecutable(): string {
return workspace.getConfiguration("spring-cli").get("executable") || "spring";
}
export async function getWorkspaceRoot(): Promise<Uri | undefined> {
if (workspace.workspaceFolders && workspace.workspaceFolders.length) {
if (workspace.workspaceFolders.length === 1) {
@@ -86,6 +82,10 @@ export async function writeResponseToFile(response: string, appName: string, sel
}
}
export async function readResponseFromFile(uri: Uri) {
return workspace.fs.readFile(uri);
}
export function isLlmApiReady(): boolean {
return version.includes('insider') && new SemVer(version).compare(new SemVer("1.90.0-insider")) >= 0;
}