Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
| 彩色输出 | 每条 Maven 命令都带 `-Dstyle.color=always`,即使输出不是终端也保留 Maven 的颜色;Lithe 的构建、运行和测试控制台按颜色显示 `[INFO]`、`[WARNING]`、`[ERROR]` 和 `BUILD SUCCESS`,匹配诊断前会先去掉颜色转义 |
| 依赖 | 显示整个反应堆或单个模块的依赖树(含作用域和传递依赖),反应堆内未安装的兄弟模块也能解析 |
| 同步 | `pom.xml`、`.mvn/maven.config`、`.mvn/extensions.xml` 变化后重新读取项目 |
| 运行配置 | Spring Boot 应用和写明主类的 Java 应用自动出现在标题栏的运行配置里,可以运行和编辑参数,见下面的「运行应用」 |
| 运行配置 | Spring Boot 应用和写明主类的 Java 应用自动出现在标题栏的运行配置里;其他带 main 方法的类选“当前文件”即可运行并保存为配置。都可以运行和编辑参数,见下面的「运行应用」 |

## 设置和构建选项

Expand Down Expand Up @@ -101,6 +101,11 @@ brew install maven
| --- | --- | --- |
| `spring-boot` | 源码根里带 `@SpringBootApplication` 的类(每个一条);没有这样的类但用了 `spring-boot-maven-plugin` 的模块(一条,主类取插件的 `mainClass` 或 `start-class`) | 服务 |
| `application` | `exec-maven-plugin` 的 `mainClass` 或 jar 清单 `archive/manifest/mainClass` 写明主类的模块 | 应用 |
| `main` | 入口运行(`entrypoints: true`):标题栏选“当前文件”点运行时,提供者回答当前文件里带 `static void main(String[])` 的类,Lithe 把它存成以类名命名的运行配置后运行;POM 里不用写主类 | 应用 |

“当前文件”的入口(`lithe/build/runEntrypoints`)只读这一个文件:模块是文件上方最近一个有 `pom.xml` 的目录,类名是包名加文件名,
测试源码(`src/test/`)不算,因为运行用的运行时类路径里没有测试类。这项需要支持 `buildProviders` 1 的 Lithe 桌面端
([1lck/Lithe-IDEA#2104](https://github.com/1lck/Lithe-IDEA/issues/2104))。

列 target 只读源码开头和 POM,不编译。运行时 Lithe 启动随包的构建提供者 `lib/lithe-maven-provider.jar`
(源码在 `provider/`),由它准备运行:
Expand Down
5 changes: 3 additions & 2 deletions io.github.lithe-idea.maven-build/plugin.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"displayName": "Maven",
"version": "1.0.0",
"pluginAPIVersion": 0,
"requires": {"buildSystems": 0, "buildProviders": 0, "projectGenerators": 0, "settings": 0, "backend": 0, "sourceSettings": 0},
"requires": {"buildSystems": 0, "buildProviders": 1, "projectGenerators": 0, "settings": 0, "backend": 0, "sourceSettings": 0},
"vendor": {"id": "io.github.lithe-idea", "displayName": "Lithe Community", "signatureRequirement": "none"},
"permissions": ["process.build", "project.generate", "backend.launch", "languageServer.launch", "workspace.metadata"],
"activationEvents": ["onBuildSystem:maven"],
Expand Down Expand Up @@ -331,7 +331,8 @@
},
"run": [
{"id": "spring-boot", "source": "provider", "fromTargets": {"tags": ["spring-boot"]}, "execution": "service", "debug": {"configurationType": "java"}},
{"id": "application", "source": "provider", "fromTargets": {"tags": ["java-application"]}, "execution": "application"}
{"id": "application", "source": "provider", "fromTargets": {"tags": ["java-application"]}, "execution": "application"},
{"id": "main", "source": "provider", "entrypoints": true}
]
}
],
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
package io.github.litheidea.maven.provider;

import io.github.litheidea.plugin.sdk.PluginError;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* Answers {@code lithe/build/runEntrypoints} (buildProviders 1): the Java
* class with a {@code main} method in one source file, which Run on Current
* File starts through the {@code main} run with the class as
* {@code launchOptions.entrypoint}.
*
* <p>Nothing is compiled: the file's text decides. The class is the file's
* top-level class, named after the file, in the file's package, and it has a
* {@code static void main(String[])} or {@code static void main(String...)}
* method. The project is the nearest directory above the file that has a
* {@code pom.xml}, inside the build root. Test sources are left out, since a
* run starts on the runtime classpath, which holds no test classes.
*/
final class RunEntrypoints {
static final String RUN = "main";
private static final long MAX_SOURCE_BYTES = 4L * 1024 * 1024;
private static final Pattern PACKAGE = Pattern.compile("^\\s*package\\s+([\\w.]+)\\s*;", Pattern.MULTILINE);
private static final Pattern MAIN = Pattern.compile(
"\\bstatic\\s+(?:final\\s+)?void\\s+main\\s*\\(\\s*(?:final\\s+)?String\\s*(?:\\[\\s*]\\s*\\w+|\\.\\.\\.\\s*\\w+|\\w+\\s*\\[\\s*])\\s*\\)");
private static final Pattern ARTIFACT = Pattern.compile("<artifactId>\\s*([^<\\s]+)\\s*</artifactId>");
private static final Pattern PARENT = Pattern.compile("<parent>.*?</parent>", Pattern.DOTALL);

private final Path workspace;

RunEntrypoints(Path workspace) {
this.workspace = workspace;
}

Map<String, Object> find(Map<String, Object> params) throws IOException {
Object rootParam = params.get("root");
Object fileParam = params.get("file");
if (!(fileParam instanceof String)) {
throw new PluginError("maven.entrypoints.noFile", "Lithe sent no source file.");
}
Path root = workspace.resolve(rootParam instanceof String ? (String) rootParam : ".").normalize();
Path file = workspace.resolve((String) fileParam).normalize();
List<Object> entrypoints = new ArrayList<>();
Map<String, Object> answer = new LinkedHashMap<>();
answer.put("entrypoints", entrypoints);
String fileName = file.getFileName() == null ? "" : file.getFileName().toString();
if (!file.startsWith(root) || !fileName.endsWith(".java") || !Files.isRegularFile(file) || Files.size(file) > MAX_SOURCE_BYTES) {
return answer;
}
Path module = module(root, file);
if (module == null || isTestSource(module.relativize(file))) {
return answer;
}
String text = stripComments(new String(Files.readAllBytes(file), StandardCharsets.UTF_8));
String simple = fileName.substring(0, fileName.length() - ".java".length());
if (!MAIN.matcher(text).find() || !Pattern.compile("\\b(?:class|record|enum|interface)\\s+" + Pattern.quote(simple) + "\\b").matcher(text).find()) {
return answer;
}
Matcher pkg = PACKAGE.matcher(text);
String className = pkg.find() ? pkg.group(1) + "." + simple : simple;
String projectPath = root.relativize(module).toString().replace('\\', '/');
if (projectPath.isEmpty()) {
projectPath = ".";
}
Map<String, Object> project = new LinkedHashMap<>();
project.put("name", artifactId(module));
project.put("path", projectPath);
Map<String, Object> entry = new LinkedHashMap<>();
entry.put("run", RUN);
entry.put("name", simple);
entry.put("entrypoint", className);
entry.put("project", project);
entrypoints.add(entry);
return answer;
}

/** The nearest directory from the file up to the root that has a pom.xml, or null. */
static Path module(Path root, Path file) {
for (Path directory = file.getParent(); directory != null && directory.startsWith(root); directory = directory.getParent()) {
if (Files.isRegularFile(directory.resolve("pom.xml"))) {
return directory;
}
}
return null;
}

/** Whether a module-relative path is under Maven's test source tree. */
static boolean isTestSource(Path relative) {
return relative.getNameCount() > 1 && "src".equals(relative.getName(0).toString()) && "test".equals(relative.getName(1).toString());
}

/** The module's own artifactId, or its directory name when the POM names none. */
static String artifactId(Path module) {
try {
String pom = stripXmlComments(new String(Files.readAllBytes(module.resolve("pom.xml")), StandardCharsets.UTF_8));
Matcher matcher = ARTIFACT.matcher(PARENT.matcher(pom).replaceAll(""));
if (matcher.find()) {
return matcher.group(1);
}
} catch (IOException ignored) {
// The directory name still names the project.
}
Path name = module.getFileName();
return name == null ? "project" : name.toString();
}

/**
* The source without comments and with string and character literals
* emptied, so a {@code main} in a comment or a string does not count.
*/
static String stripComments(String source) {
StringBuilder out = new StringBuilder(source.length());
int length = source.length();
for (int index = 0; index < length; index++) {
char current = source.charAt(index);
char next = index + 1 < length ? source.charAt(index + 1) : '\0';
if (current == '/' && next == '/') {
while (index < length && source.charAt(index) != '\n') {
index++;
}
out.append('\n');
} else if (current == '/' && next == '*') {
index += 2;
while (index < length && !(source.charAt(index) == '*' && index + 1 < length && source.charAt(index + 1) == '/')) {
index++;
}
index++;
out.append(' ');
} else if (current == '"' || current == '\'') {
boolean block = current == '"' && source.startsWith("\"\"\"", index);
String close = block ? "\"\"\"" : String.valueOf(current);
index += close.length();
while (index < length && !source.startsWith(close, index)) {
if (source.charAt(index) == '\\') {
index++;
}
index++;
}
index += close.length() - 1;
out.append(current).append(current);
} else {
out.append(current);
}
}
return out.toString();
}

private static String stripXmlComments(String xml) {
return xml.replaceAll("(?s)<!--.*?-->", "");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,10 @@ static Request of(Map<String, Object> params) {
}
}
}
// An entrypoint run names no target; progress and errors name the class instead.
if (request.targetName.isEmpty() && request.entrypoint != null) {
request.targetName = request.entrypoint.substring(request.entrypoint.lastIndexOf('.') + 1);
}
return request;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@

/**
* The Maven build provider process: Lithe starts it on the first run of a
* Maven application and talks to it over stdio. It answers only
* {@code lithe/build/prepareRun}; the model, dependencies, tasks and tests
* stay commands Lithe runs itself.
* Maven application and talks to it over stdio. It answers
* {@code lithe/build/prepareRun} and, for Run on Current File,
* {@code lithe/build/runEntrypoints}; the model, dependencies, tasks and
* tests stay commands Lithe runs itself.
*/
public final class RunProvider {
private RunProvider() {}
Expand All @@ -21,16 +22,23 @@ public static void main(String[] args) throws Exception {
Path extension = lib.resolve("lithe-maven-extension.jar");
Backend backend = Backend.create("lithe-maven-provider", RunProvider.class.getPackage().getImplementationVersion());
backend.onPrepareRun((params, context) -> preparation(backend, extension).prepare(params, context));
backend.onRunEntrypoints((params, context) -> new RunEntrypoints(workspace(backend)).find(params));
backend.listen();
}

private static RunPreparation preparation(Backend backend, Path extension) {
Path workspace = workspace(backend);
Object locale = backend.initializeParams().get("locale");
return new RunPreparation(workspace, extension, new Messages(locale instanceof String ? (String) locale : null));
}

/** The workspace folder Lithe sent in {@code initialize}. */
private static Path workspace(Backend backend) {
Map<String, Object> initialize = backend.initializeParams();
Object root = initialize == null ? null : initialize.get("rootUri");
if (!(root instanceof String)) {
throw new PluginError("maven.run.noWorkspace", "Lithe sent no workspace folder.");
}
Object locale = initialize.get("locale");
return new RunPreparation(Paths.get(URI.create((String) root)), extension, new Messages(locale instanceof String ? (String) locale : null));
return Paths.get(URI.create((String) root));
}
}
4 changes: 2 additions & 2 deletions scripts/compiler/backend-client.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Talks to lib/lithe-maven-settings.jar the way Lithe does: LSP base-protocol
// frames over the process's stdio, `initialize` offering litheBuild 1, then
// frames over the process's stdio, `initialize` offering litheBuild 0 and 1, then
// lithe/build/* requests. Every wait is bounded, and the backend runs in its
// own process group so a test can always end whatever it left behind.
import { execFileSync, spawn } from "node:child_process";
Expand Down Expand Up @@ -80,7 +80,7 @@ export class BackendClient {
processId: process.pid,
rootUri: pathToFileURL(root).href,
capabilities: { experimental: {
...(functions ? { litheFunctions: { versions: [0] } } : { litheBuild: { versions: [0] } }),
...(functions ? { litheFunctions: { versions: [0] } } : { litheBuild: { versions: [0, 1] } }),
litheLogging: { versions: [0] },
} },
});
Expand Down
27 changes: 27 additions & 0 deletions scripts/test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,31 @@ async function prepareRuns(signal) {
assert.equal(launch(discovered).trim(), "Hello, Maven");
});

// Run on Current File: the provider names the class with a main method in one source file,
// and an entrypoint run prepares it without a target.
const entrypoints = (file) => report.step(`find the entrypoints of ${file}`, () => client.request("lithe/build/runEntrypoints", {
operationID: `entrypoints-${++operation}`, buildSystemID: "maven", root: ".", file,
}));
const mainEntrypoints = await entrypoints("app/src/main/java/demo/app/Main.java");
const libraryEntrypoints = await entrypoints("core/src/main/java/demo/core/Greeter.java");
const testEntrypoints = await entrypoints("core/src/test/java/demo/core/GreeterTest.java");
await check("a source file with a main method names its class and module", () => {
assert.deepEqual(mainEntrypoints, { format: "litheRunEntrypoints", version: 0, entrypoints: [
{ run: "main", name: "Main", entrypoint: "demo.app.Main", project: { name: "app", path: "app" } },
] });
assert.deepEqual(libraryEntrypoints.entrypoints, [], "a class without main has no entrypoint");
assert.deepEqual(testEntrypoints.entrypoints, [], "test sources are not on the runtime classpath");
});
const entrypoint = await report.step("prepare the Main entrypoint", () => client.request("lithe/build/prepareRun", {
operationID: `run-${++operation}`, buildSystemID: "maven", root: ".", options: {}, optionArguments: [], environment: {},
tool: { executable: maven }, run: "main", project: { name: "app", path: "app" }, userArguments: [],
launchOptions: { execution: "application", runtimeArguments: [], arguments: [], environment: {}, entrypoint: "demo.app.Main" },
}));
await check("an entrypoint run starts the chosen class without a target", () => {
assert.equal(entrypoint.arguments[entrypoint.arguments.indexOf("-cp") + 2], "demo.app.Main");
assert.equal(launch(entrypoint).trim(), "Hello, Maven");
});

const debug = await prepare({ name: "ServiceApplication", path: "service", tags: ["spring-boot"], properties: { mainClass: "demo.service.ServiceApplication" } }, {
launchOptions: { execution: "service", runtimeArguments: [], arguments: [], environment: {},
debug: { adapterID: "dev.example/java", configurationType: "java", target: { kind: "connection", host: "127.0.0.1", port: 51235 } } },
Expand Down Expand Up @@ -251,6 +276,8 @@ async function test(signal) {
assert.equal(runs["spring-boot"].execution, "service");
assert.deepEqual(runs.application.fromTargets.tags, ["java-application"]);
assert.ok(buildSystem.run.every((run) => run.source === "provider"));
assert.equal(runs.main.entrypoints, true, "Run on Current File starts any main class through the main run");
assert.equal(manifest.requires.buildProviders, 1);
});

const projectDependencies = await document("read project dependencies", buildSystem.dependencies, signal, { project: "app" });
Expand Down
8 changes: 4 additions & 4 deletions sdk.lock.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@
"schemaVersion": 1,
"source": {
"repository": "https://github.com/Lithe-IDEA/Lithe-core-rust",
"revision": "9425469bdaa5a8195d9cdf5e9f440165c9e79810"
"revision": "d833d6a71dfeaa5eda39d23f6a3a1a9ee29ff9ed"
},
"files": [
{
"upstream": "shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Backend.java",
"path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Backend.java",
"sha256": "3be1cee3007bc55786ae62894d2366aabce2a9af0669acfbc030e0afe3d90c9e"
"sha256": "a5f7ea6bc0cf5e78e663203d7cc65fb2522ebcf99462c24ebf0f6422bcb6d16c"
},
{
"upstream": "shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/CallContext.java",
Expand All @@ -28,7 +28,7 @@
{
"upstream": "shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Diagnostics.java",
"path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Diagnostics.java",
"sha256": "1268691d9cb950776e9f659d11d9480e51069e90aa6437f2809ac0e00c3a57d4"
"sha256": "a1e6fa4b743c0702a4b7f462cbad9539da32a523e51d8bf8a6a054bec82d14df"
},
{
"upstream": "shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Framing.java",
Expand Down Expand Up @@ -73,7 +73,7 @@
{
"upstream": "shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java",
"path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java",
"sha256": "c6e2fa8db5ffec78e757f3bdc4622e2beb6f697178f3631fd53e29e9237e29b7"
"sha256": "c84c26121c2997826269c5503dbd11cf437acfa13c2ab3c4f2ea29652a096712"
},
{
"upstream": "shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/StateStore.java",
Expand Down
Loading
Loading