diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7e57a6e..1e0aacd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,8 +22,8 @@ jobs: - uses: actions/setup-node@v4 with: node-version: 22 - # 17 builds and runs Maven (the last version is the default); the - # build provider is also tested on 8, the oldest plugin.json accepts. + # 17 builds the extension and runs the latest Maven (the last version + # is the default); the oldest Maven runs the extension on Java 8. - uses: actions/setup-java@v4 with: distribution: temurin @@ -32,16 +32,8 @@ jobs: 17 - name: Check script process deadlines and cleanup run: node scripts/test-process.mjs - - name: Verify vendored Java SDK sources - run: node scripts/sdk/verify-sdk.mjs - name: Check manifest and build the archive run: node scripts/package.mjs - - name: Test the build provider's snapshot with a fake Maven (Java 17) - run: node scripts/test-backend.mjs - - name: Test the build provider's snapshot with a fake Maven (Java 8) - env: - LITHE_TEST_JAVA: ${{ env.JAVA_HOME_8_X64 }}/bin/java - run: node scripts/test-backend.mjs - name: Download Maven ${{ matrix.maven }} if: matrix.maven != 'runner' env: @@ -52,10 +44,10 @@ jobs: echo "$(curl -fsSL "$base.sha512" | cut -d' ' -f1) $RUNNER_TEMP/maven.tar.gz" | sha512sum -c - tar -xzf "$RUNNER_TEMP/maven.tar.gz" -C "$RUNNER_TEMP" echo "MVN=$RUNNER_TEMP/apache-maven-$VERSION/bin/mvn" >> "$GITHUB_ENV" - - name: Run the provider and the declared commands with Maven + - name: Run the declared commands with Maven env: - # The oldest Maven also gets the oldest Java for the provider. - LITHE_TEST_JAVA: ${{ matrix.maven == 'runner' && 'java' || format('{0}/bin/java', env.JAVA_HOME_8_X64) }} + # The oldest Maven also runs on the oldest Java. + JAVA_HOME: ${{ matrix.maven == 'runner' && env.JAVA_HOME || env.JAVA_HOME_8_X64 }} run: node scripts/test.mjs - name: Validate against Lithe Store rules if: matrix.maven == 'runner' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9de4d77..8c3d8f2 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -27,39 +27,35 @@ jobs: java-version: | 8 17 - # --expect-tag requires the tag to match plugin.json and both POM versions. + # --expect-tag requires the tag to match plugin.json and the extension POM version. - name: Build the archive run: | set -o pipefail node scripts/package.mjs --expect-tag "$GITHUB_REF_NAME" | tee "$RUNNER_TEMP/checksums.txt" - - name: Test the build provider's snapshot on Java 8 + - name: Run the declared commands with Maven on Java 8 env: - LITHE_TEST_JAVA: ${{ env.JAVA_HOME_8_X64 }}/bin/java - run: node scripts/test-backend.mjs - - name: Run the provider and the declared commands with Maven + JAVA_HOME: ${{ env.JAVA_HOME_8_X64 }} run: node scripts/test.mjs - name: Publish release env: GH_TOKEN: ${{ github.token }} - # v0.1.0 was a trial release. v0.1.2 needs a host offering - # litheLogging 1, which stable Lithe 0.6.7 lacks. v0.1.3 also - # requires pluginFunctions 1, so stable hosts refuse to install it - # and the Store's requires map keeps them on 0.1.1. - PRERELEASE_TAGS: v0.1.0 v0.1.2 + # v0.0.1 follows plugin contract v0, which only the new desktop + # client installs, and that client ships as desktop-v* pre-releases. + PRERELEASE_TAGS: v0.0.1 run: | prerelease=false for tag in $PRERELEASE_TAGS; do if [[ "$tag" == "$GITHUB_REF_NAME" ]]; then prerelease=true; fi done { - echo "兼容性:需要同时提供 backend 2、pluginFunctions 1、projectGenerators 1 和结构化插件诊断(litheLogging 1)的 Lithe preview 开发版或更新的客户端。稳定版 Lithe 0.6.7 没有 pluginFunctions 1,会拒绝安装 0.1.3;稳定版请继续使用 0.1.1。0.1.2 预览版不再单独说明,由 0.1.3 取代。" + echo "兼容性:按插件契约 v0(schemaVersion 0、pluginAPIVersion 0)编写,需要新版 Lithe 桌面端(desktop-v* 预发布)。旧版 macOS Lithe 无法安装。" echo if [[ -s "docs/releases/$GITHUB_REF_NAME.md" ]]; then cat "docs/releases/$GITHUB_REF_NAME.md" echo fi if [[ "$prerelease" == true ]]; then - echo "安装:预发布版本,Lithe Store 自动追踪会跳过,暂不收录 Store。下载下面的 ZIP,在 设置 → 插件 的 ⚙ 菜单中选择 从磁盘安装插件…。" + echo "安装:预发布版本,Lithe Store 自动追踪会跳过,暂不收录 Store。下载下面的 ZIP,在 设置 → 插件 中点击页面标题栏右侧的 从文件安装…,选中 ZIP 后核对 SHA-256 并确认。" else echo "安装:Lithe Store(https://github.com/Lithe-IDEA/Lithe-store)中的 Maven 条目合并后,可在 设置 → 插件 → 插件市场 中搜索 Maven 并安装。" fi diff --git a/.gitignore b/.gitignore index 162897b..f743058 100644 --- a/.gitignore +++ b/.gitignore @@ -2,5 +2,4 @@ dist/ .artifacts/ extension/target/ .DS_Store -backend/target/ .cache/ diff --git a/NOTICE b/NOTICE index c8828eb..a77fb0d 100644 --- a/NOTICE +++ b/NOTICE @@ -17,8 +17,3 @@ resources, moved from the Java Support plugin), under the Apache License, Version 2.0. Their exact file paths and revision are not recorded. Copyright 2000-2024 JetBrains s.r.o. and contributors. - -The backend includes the Apache-2.0 licensed official Lithe Java plugin SDK -from Lithe-IDEA/lithe-plugin-docs. Its production sources and LICENSE are -vendored in vendor/, with upstream base revision, local structured logging -changes and exact SHA-256 per input recorded in sdk.lock.json. diff --git a/README.md b/README.md index 69cb736..b2c4bc3 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,16 @@ # Maven for Lithe -为 [Lithe](https://github.com/1lck/Lithe-IDEA) 提供 Maven 项目支持:识别 `pom.xml`,在 Maven 工具窗口里列出 +为 [Lithe](https://github.com/1lck/Lithe-IDEA) 提供 Maven 项目支持:识别 `pom.xml`,在构建窗口里列出 模块、生命周期和插件目标,运行任务和测试,查看依赖树。 -这是一个**社区插件**,用 Lithe 的声明式构建系统接口(插件 API 3 的 `buildSystems`)实现, -除了下面说的 Maven 扩展 jar 和读取项目用的 Java 后端,没有任何宿主代码。 +这是一个**社区插件**,用插件契约 v0 的声明式构建系统接口(`buildSystems`)实现。插件没有后端进程, +只有一份 `plugin.json`、新建项目模板和一个 Maven 扩展 jar。 -> English: Maven support for Lithe through the declarative `buildSystems` plugin API — project tree, lifecycle and -> plugin goals, profiles, test runs with JUnit reports, compiler diagnostics and the dependency tree. It runs your own -> Maven with a small bundled core extension that only reads the reactor, from a Java build provider that keeps the -> result in a snapshot, so reopening a project does not run Maven again until a POM or setting changes. +> English: Maven support for Lithe through the declarative `buildSystems` contract — project tree, lifecycle and +> plugin goals, profiles, test runs with JUnit reports, compiler diagnostics and the dependency tree. Lithe runs your +> own Maven with a small bundled core extension that only reads the reactor; the plugin has no backend process. -> **预览版**:0.1.3 需要提供 `backend: 2`、`pluginFunctions: 1`、`projectGenerators: 1` 和结构化插件诊断(`litheLogging: 1`)的 Lithe `preview` 开发版或更新的客户端。稳定版 Lithe 0.6.7 没有 `pluginFunctions: 1`,会拒绝安装 0.1.3;Store 的 `requires` 能力表让稳定版继续使用 0.1.1。0.1.3 同时发布到 Lithe Store。 +> **预发布**:按插件契约 v0(`schemaVersion: 0`、`pluginAPIVersion: 0`)编写,只能装进新版 Lithe 桌面端 +> (`desktop-v*` 预发布),旧版 macOS Lithe 无法安装。 ## 功能 @@ -20,32 +20,51 @@ | 生命周期 | `clean` `validate` `compile` `test` `package` `verify` `install` `site` `deploy`,可对整个反应堆或单个模块运行(`-pl`) | | 插件目标 | 每个模块实际使用的构建插件及其全部目标,按 `Plugins › <前缀>` 分组,运行时使用完整坐标 | | 自定义目标 | “Run Maven Goal…” 输入任意目标和参数 | -| 选项 | Profiles(从反应堆、父 POM 和 settings.xml 读取,可手动补充)、Settings 文件、本地仓库;工具栏开关 Offline(`-o`)和 Skip Tests(`-DskipTests`) | | 测试 | 运行模块、测试类或单个方法,读取 Surefire/Failsafe 的 JUnit XML 报告 | | 诊断 | 把编译输出中的 `[ERROR]`/`[WARNING] 文件:[行,列]` 显示为问题 | -| 依赖 | 按模块显示依赖树(含作用域和传递依赖),反应堆内未安装的兄弟模块也能解析;一次 Maven 运行读出全部模块,展开模块不再各跑一次 | -| 快照 | 项目和依赖保存在工作区状态目录,重新打开项目时直接显示;POM、`.mvn/` 配置、settings.xml、选项或 Maven/Java 变化后才重新运行 Maven,Reload 总是重新运行 | +| 依赖 | 显示整个反应堆或单个模块的依赖树(含作用域和传递依赖),反应堆内未安装的兄弟模块也能解析 | | 同步 | `pom.xml`、`.mvn/maven.config`、`.mvn/extensions.xml` 变化后重新读取项目 | +## 设置和构建选项 + +**插件设置**(设置 → 插件 → Maven →「设置」,也显示在「构建、执行、部署 › Maven」页): + +| 设置 | 说明 | +| --- | --- | +| Maven executable | 要运行的 `mvn`。留空时按下面「依赖的程序」的顺序查找;填写后总是使用这个程序,即使项目里有 `mvnw`。修改后构建模型自动重新读取 | + +**构建选项**(构建窗口 →「构建选项」),只对当前工作区生效: + +| 选项 | 传给 Maven 的内容 | +| --- | --- | +| JDK (JAVA_HOME) | 运行 Maven 的 JDK,设为环境变量 `JAVA_HOME` | +| Profiles | `-P `;候选值从反应堆、父 POM 和 settings.xml 读取,也可以手动补充 | +| Settings File | `-s <文件>` | +| Local Repository | `-Dmaven.repo.local=<目录>` | +| Offline | `-o`,声明为工具栏开关 | +| Skip Tests | `-DskipTests`,声明为工具栏开关 | + +JDK 是构建选项而不是插件设置,因为契约 v0 的插件设置不能向构建命令注入环境变量。 + ## 新建项目 -插件在 **New Project** 窗口提供两个条目: +插件在新建项目窗口提供两个条目: -- **Maven**:生成 Maven Java 项目,可选示例代码,可设置 GroupId 和 ArtifactId。 +- **Maven**:生成 Maven Java 项目,可选 Java release(8、11、17、21、25)、示例代码、GroupId 和 ArtifactId。 - **Maven Archetype**:用内置原型或自定义原型,由 `mvn` 生成项目。 -模板在 `io.github.lithe-idea.maven-build/templates/java/`,从 Java Support 插件移来。 -生成的项目需要 Java Support 提供 Java 语言支持。 +模板在 `io.github.lithe-idea.maven-build/templates/java/`。生成的项目需要另装 Java 语言支持插件才有代码智能。 ## 依赖的程序 -插件不带 Maven,使用你项目或电脑上的 Maven,按以下顺序查找: +插件不带 Maven,按以下顺序查找: -1. 项目里的 Maven Wrapper(`mvnw`,需要 `.mvn/wrapper/maven-wrapper.properties`); -2. 环境变量 `MAVEN_HOME` 下的 `bin/mvn`; -3. `PATH` 里的 `mvn`。 +1. 插件设置 Maven executable(填写后不再往下找;路径不存在时直接报错,不回退); +2. 项目里的 Maven Wrapper(`mvnw`,需要 `.mvn/wrapper/maven-wrapper.properties`); +3. 环境变量 `MAVEN_HOME` 下的 `bin/mvn`; +4. `PATH` 里的 `mvn`。 -要求 Maven 3.6.3 或更新版本、Java 8 或更新版本(读取项目的后端也用 Lithe 找到的这个 Java 运行)。没有 Maven 的话可以先安装: +要求 Maven 3.6.3 或更新版本、Java 8 或更新版本。没有 Maven 的话可以先安装: ```bash brew install maven @@ -53,118 +72,65 @@ brew install maven ## 工作方式 -读取项目和依赖由插件的构建后端 `lib/lithe-maven-backend.jar`(源码在 `backend/`)负责。Lithe 在第一次需要 -项目模型时用 Java 启动它,工作区关闭时结束它: - -- 需要重新读取时,后端用 `-Dmaven.ext.class.path` 给你的 Maven 加载随包提供的 - `lib/lithe-maven-extension.jar`(源码在 `extension/`),运行一个没有默认绑定的阶段 `pre-clean`。 - 扩展在 Maven 读完反应堆后,把模块、内容根、插件目标和 Profiles 写成 Lithe 的 `litheBuildModel` 文档, - 同时把**每个模块**的依赖树写成 `litheDependencies` 文档(`-Dlithe.modelOutput` / `-Dlithe.dependenciesOutput`)。 -- 结果连同输入指纹保存在 Lithe 给这个工作区的状态目录里的 `maven-snapshot.json`。指纹包含根目录下所有 - `pom.xml`(跳过 `target/`、`.git/`、`node_modules/`)、`.mvn/maven.config`、`extensions.xml`、`jvm.config`、 - Wrapper 配置、用户和全局 `settings.xml`、`-s` 指定的文件、选项、Maven 可执行文件及其修改时间、Java 版本和扩展版本。 - 指纹不变时,重新打开项目或展开模块直接用快照,不启动 Maven。 -- 同时到达的请求共用一次 Maven 运行;全部请求都取消后才结束 Maven。运行期间 POM 被修改时,本次结果照常显示但不保存。 -- 指纹看不到的变化(例如根目录外的父 POM、远程仓库里更新的 SNAPSHOT)请点 Reload,它总是重新运行 Maven。 -- 不会编译或打包,也不会生成 `target/`;解析依赖时只读 POM,不下载依赖 jar。 -- 没有 Lithe 的属性时扩展什么都不做;插件目录在运行时保持只读。 - -读取项目会执行 POM 中声明的 Maven 扩展和插件,首次读取还可能联网下载插件描述,所以 Lithe 会先确认你信任这个工作区。 +读取项目和依赖都是 `plugin.json` 里声明的 Maven 命令,由 Lithe 运行: -## Java 语言服务器的导入设置 - -旧版清单里的 `buildSystems[].languageImport` 已从插件契约删除。现在 Maven 插件导出插件函数 `languageImport.settings` -(版本 1,`context: "workspace"`),Java Support 在启动 JDT LS 前调用它,只接受白名单前缀内的键。 -这个函数由插件后端(同一个 `lib/lithe-maven-backend.jar`,以 `--plugin-backend` 启动,与构建提供方是两个进程)回答, -只读取 `<工作区>/.mvn/maven.config`,不运行 Maven、不写文件: - -| `maven.config` 参数 | 导出的键 | -| --- | --- | -| `-s` / `--settings <文件>` | `java.configuration.maven.userSettings` | -| `-gs` / `--global-settings <文件>` | `java.configuration.maven.globalSettings` | -| `-o` / `--offline` | `java.import.maven.offline.enabled` | +- Lithe 用 `-Dmaven.ext.class.path` 给你的 Maven 加载随包提供的 `lib/lithe-maven-extension.jar` + (源码在 `extension/`),运行一个没有默认绑定的阶段 `pre-clean`。 +- 读取项目时,扩展在 Maven 读完反应堆后把模块、内容根、插件目标和 Profiles 写成 `litheBuildModel` 文档 + (`-Dlithe.modelOutput=${outputFile}`)。 +- 读取依赖时,扩展把依赖树写成 `litheDependencies` 文档(`-Dlithe.dependenciesOutput=${outputFile}`)。 + 选中模块时用 `-Dlithe.dependenciesProject` 只导出这个模块,否则导出反应堆里的每个模块。 +- 输出文件由 Lithe 在这个工作区的插件状态目录(插件包之外的可写目录)里分配,Maven 退出后读取并删除。 +- 读取项目和依赖不会编译或打包,也不会生成 `target/`;解析依赖时只读 POM,不下载依赖 jar。 +- 没有 Lithe 的属性时扩展什么都不做;插件目录在运行时保持只读。 -文件不存在时对应的键不导出;`workspaceRoot` 必须落在已打开的本地工作区文件夹内,否则函数拒绝(`maven.invalidRoot`)。 -工具栏里保存的 Profiles、Settings File、Local Repository、Offline 选项只在宿主里,插件后端读不到,所以不会传给 JDT LS, -需要宿主把已存选项交给插件函数后才能恢复。 +读取项目会执行 POM 中声明的 Maven 扩展和插件,首次读取还可能联网下载插件描述,所以这两条命令都声明了 +`executesProjectCode` 和 `mayUseNetwork`,Lithe 会先确认你信任这个工作区。 ## 安装 -在 **设置 → 插件 → 插件市场** 中搜索 “Maven” 并按提示重启:稳定版 Lithe 会得到 0.1.1,支持 `pluginFunctions: 1` 的 preview 开发版或更新的客户端会得到 0.1.3。 -也可以从 [Releases](https://github.com/Lithe-IDEA/lithe-plugin-maven/releases) 下载 `maven-build-0.1.3-darwin.zip`, -在 **设置 → 插件** 的 ⚙ 菜单中选择 **从磁盘安装插件…**。 -Lithe 已预置 Lithe Store 社区插件源;如果你之前移除了它,先在 **⚙ → 管理插件仓库…** 中重新添加 -`https://github.com/Lithe-IDEA/Lithe-store`。 +1. 从 [Releases](https://github.com/Lithe-IDEA/lithe-plugin-maven/releases) 下载 `maven-build-<版本>-darwin.zip`。 +2. 在 Lithe 中打开 **设置 → 插件**,点击页面标题栏右侧的 **从文件安装…**,选中这个 zip,核对 SHA-256 和权限后确认。 -一个包同时支持 Apple Silicon 和 Intel Mac;Lithe for Windows 支持插件市场后会增加 Windows 包。 +一个包同时支持 Apple Silicon 和 Intel Mac。 ## 诊断日志 -0.1.2 起要求宿主提供 `litheLogging: 1`。SDK 通过类型化的 `lithe/log` 通知,把 Maven provider -操作交给宿主 v2 目录和统一 writer,写入当前会话的 `plugins/io.github.lithe-idea.maven-build/host` 通道。 -关键成功终态为 INFO、失败终态为 ERROR,包含单调耗时和稳定分类;取消不记失败。 -缓存保存失败或读取中项目变化属于可恢复降级,使用 WARN `degraded`,不记录异常正文、路径或环境值。 -模型快照继续属于 `${workspaceStateDir}`,不会搬到会话日志目录。 - -Maven 失败由 SDK 的请求边界记录一次,provider 不再重复打印构建输出。 -完整构建输出仍属于 Build Output,模型/依赖树 JSON 属于工作流数据。 -后端从 `vendor/` 直接编译官方 Java SDK 的结构化日志实现,使用 `lithe/log` 发送稳定分类、 -单调耗时和操作身份;原始异常与构建 tail 不进入日志。`sdk.lock.json` 记录真实上游基线、 -本轮尚未发布的源代码改动及每个文件的 SHA-256,没有沿用或伪造旧发版 JAR 的校验值。 - -排障时使用 Lithe 的独立日志窗口和诊断导出;不要开启输出源码、凭据、环境变量或协议正文的日志。 -Windows 的日志实现仍为 v1,未声明 Windows v2 已完成验收。 +插件没有自己的进程,也不发送 `lithe/log`。Maven 命令由 Lithe 启动,完整输出显示在构建输出里; +模型和依赖树文档属于工作流数据,不写进日志。排障时使用 Lithe 的日志窗口和诊断导出, +不要开启输出源码、凭据、环境变量或协议正文的日志。 ## 开发 ```text io.github.lithe-idea.maven-build/plugin.json # 插件描述,目录名必须等于插件 id -io.github.lithe-idea.maven-build/icons/ # 工具窗口、工具栏和新建项目图标(来源见 NOTICE) +io.github.lithe-idea.maven-build/icons/ # 构建窗口、工具栏和新建项目图标(来源见 NOTICE) io.github.lithe-idea.maven-build/templates/ # 新建项目的文件模板(Maven 项目),打包时检查路径是否存在 -extension/ # Maven 核心扩展,导出模型和依赖树 -backend/ # 构建后端(Java 8,Lithe 插件 SDK),快照和 Maven 运行 -vendor/ # 官方 Java SDK 生产源码和许可证(不带测试、JAR、target) -sdk.lock.json # SDK 上游基线、本轮改动身份、逐文件 SHA-256 -scripts/sdk/verify-sdk.mjs # 编译前拒绝漂移、遗漏或额外 SDK 文件 +extension/ # Maven 核心扩展(Java 8),导出模型和依赖树 test/fixtures/reactor/ # 三个模块的示例反应堆,供集成测试使用 +test/fixtures/fake-maven.mjs # 假 Maven,检查集成测试失败时的报告 scripts/package.mjs # 构建扩展并打包成 dist/maven-build-<版本>-darwin.zip -scripts/test.mjs # 用真实 Maven 经后端读取项目、运行清单里的命令并检查输出 -scripts/test-backend.mjs # 用假 Maven 计数,检查快照命中、失效、刷新、合并运行和取消 +scripts/test.mjs # 用真实 Maven 运行清单里的模型、依赖和测试命令并检查输出 +scripts/test-process.mjs # 进程超时、中断和清理回归,不需要 Maven +scripts/verify-scripts.mjs # 在临时副本里打包和测试,检查已有包和宿主 bundle 不被改动 .github/workflows/ci.yml # PR 时打包、用 Maven 3.6.3 和最新版测试,并用 Lithe Store 的规则检查 .github/workflows/release.yml # 推送 v<版本> 标签时发布 GitHub Release docs/releases/v<版本>.md # 该版本的变化,发布时并入 Release 说明(可选) ``` -本地需要 Node.js 22+、JDK(CI 用 17;扩展和后端都按 Java 8 编译,后端运行只需 Java 8)和 Maven(还需要 `zip`)。 - -后端把固定在 `vendor/lithe-plugin-sdk-java/src/main/java/` 的 SDK 生产源码一同按 Java 8 编译。 -打包前先校验 `sdk.lock.json`,缺失、改动或额外未登记文件都会拒绝;只读源码不共享可变构建状态。 -不再从网络下载 SDK JAR,也不接受 `LITHE_SDK_JAR` 替换构建输入。 -SDK 以 Apache-2.0 分发,源码许可证位于 `vendor/LICENSE`,安装包附带 `SDK-LICENSE`。 -如需更新,先从官方 SDK 仓库取真实生产源码,审查变更并更新基线和逐文件摘要,再执行验证。 - -开发或发布时直接运行: +本地需要 Node.js 22+、JDK(CI 用 17;扩展按 Java 8 编译)、Maven 和 `zip`。 ```bash node scripts/package.mjs -``` - -```bash node scripts/test.mjs ``` -后端的快照行为不需要 Maven,用假 Maven 计数验证;`LITHE_TEST_JAVA=/path/to/java` 可指定运行后端的 Java -(CI 用 Java 8 和 17 各跑一次,`test.mjs` 同样读取这个变量): - -```bash -node scripts/test-backend.mjs -``` - -`MVN=/path/to/mvn` 可为打包和测试指定 Maven 版本。脚本在 macOS/Linux 上运行;每次 Maven 调用默认限时 120 秒, -可用 `LITHE_MAVEN_TIMEOUT_MS` 调整(1–600000 毫秒);`zip` 限时 30 秒。到期或收到 SIGINT/SIGTERM 时, -脚本会终止本次启动的进程组,500 毫秒后升级为 SIGKILL,再最多等待 2 秒并报告清理失败。 -每个命令和检查的耗时、结果会写入 `.artifacts/test-stability/` 的 JSON、JUnit XML 和 HTML; -`LITHE_REPORT_DIR` 可以指定其他报告目录。真实 Maven 测试是依赖本机工具及 Maven 仓库的集成测试。 +`MVN=/path/to/mvn` 可为打包和测试指定 Maven 版本,`JAVA_HOME` 指定运行 Maven 的 JDK(CI 用 Maven 3.6.3 加 Java 8 +检查最低版本)。脚本在 macOS/Linux 上运行;每次 Maven 调用默认限时 120 秒,可用 `LITHE_MAVEN_TIMEOUT_MS` 调整 +(1–600000 毫秒);`zip` 限时 30 秒。到期或收到 SIGINT/SIGTERM 时,脚本会终止本次启动的进程组, +500 毫秒后升级为 SIGKILL,再最多等待 2 秒并报告清理失败。每个命令和检查的耗时、结果会写入 +`.artifacts/test-stability/` 的 JSON、JUnit XML 和 HTML;`LITHE_REPORT_DIR` 可以指定其他报告目录。 +`LITHE_CAPTURE_DIR=<目录>` 会把读到的模型和依赖文档另存一份(工作区路径写成 `${workspace}`),供 Lithe 的 Core 测试使用。 Node 子进程回归不需要 Maven 或联网,覆盖拒绝 SIGTERM 的子孙进程、父进程先退出、异常退出和中断清理: @@ -172,7 +138,7 @@ Node 子进程回归不需要 Maven 或联网,覆盖拒绝 SIGTERM 的子孙 node scripts/test-process.mjs ``` -要验证打包/测试前后已有插件、ZIP 和宿主 bundle 的文件清单及 SHA-256 不变,可运行: +要验证打包和测试前后已有插件、ZIP 和宿主 bundle 的文件清单及 SHA-256 不变,可运行: ```bash node scripts/verify-scripts.mjs --host-bundle /Applications/Lithe.app @@ -182,25 +148,26 @@ node scripts/verify-scripts.mjs --host-bundle /Applications/Lithe.app 保留原有 `dist/`,将新包、前后清单和逐项计时保存在 `.artifacts/script-verification/run-*/`,最后清理临时目录。 这只验证本次脚本工作流;宿主 UI 的实机验收需要另外执行。 -在 Lithe 开发版中,通过 **设置 → 插件 → ⚙ → 从磁盘安装插件…** 选择 `dist/package/io.github.lithe-idea.maven-build` -即可安装本地开发包(发行版 Lithe 不加载未签名的开发包)。 +本地开发时,用 **设置 → 插件 → 从文件安装…** 选择 `dist/maven-build-<版本>-darwin.zip` 安装。 -`plugin.json` 的完整格式见 lithe-plugin-docs 里的 -[插件契约](https://github.com/Lithe-IDEA/lithe-plugin-docs/blob/main/contract/v1/README.md) -和[构建工具接入指南](https://github.com/Lithe-IDEA/lithe-plugin-docs/blob/main/guides/build-tool-integration.md)。 +`plugin.json` 的完整格式见 Rust Core 仓库里的 +[插件契约](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/shared/plugins/contract/v1/README.md) +和[构建工具接入指南](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/shared/plugins/guides/build-tool-integration.md)。 ## 发布新版本 -1. 同时修改 `plugin.json`、`extension/pom.xml` 和 `backend/pom.xml` 的版本(例如 `0.2.0`;打包脚本会检查三者一致), - 确认 `sdk.lock.json` 已登记所用 SDK 源码、上游基线与全部 SHA-256,合入 `main`。 +1. 按语义化版本同时修改 `plugin.json` 和 `extension/pom.xml` 的版本(打包脚本会检查两者一致):只修 Bug 升修订号, + 加功能升次版本号,有不兼容的变化升主版本号。合入 `main`。 2. 推送同名标签: ```bash - git tag v0.2.0 && git push origin v0.2.0 + git tag v0.0.1 && git push origin v0.0.1 ``` -3. `Release` 工作流会核对标签与版本、打包、测试并发布 Release(说明里附 SHA-256)。`release.yml` 里 `PRERELEASE_TAGS` 列出的版本(`v0.1.0` 试用版、需要 `litheLogging: 1` 的 `v0.1.2`)会标为预发布版本。 -4. Lithe Store 的自动追踪会发现稳定版本并开合并请求,合并后用户即可在 Lithe 中更新。自动追踪会跳过预发布版本;需要收录时在 Store 中手工提交条目,并使用已发布 ZIP 的实际 SHA-256。 +3. `Release` 工作流会核对标签与版本、打包、测试并发布 Release(说明里附 SHA-256)。`release.yml` 里 + `PRERELEASE_TAGS` 列出的版本会标为预发布版本:目前是只能装进新版桌面端的 `v0.0.1`。 +4. Lithe Store 的自动追踪会发现稳定版本并开合并请求,合并后用户即可在 Lithe 中更新。自动追踪会跳过预发布版本; + 需要收录时在 Store 中手工提交条目,并使用已发布 ZIP 的实际 SHA-256。 ## 许可 diff --git a/backend/pom.xml b/backend/pom.xml deleted file mode 100644 index f2eb7b6..0000000 --- a/backend/pom.xml +++ /dev/null @@ -1,96 +0,0 @@ - - - - 4.0.0 - - io.github.lithe-idea - lithe-maven-backend - - 0.1.3 - jar - Lithe Maven build provider - - - UTF-8 - - 8 - - 2026-10-20T00:00:00Z - - - - ${project.basedir}/.. - lithe-maven-backend - - - org.apache.maven.plugins - maven-compiler-plugin - 3.14.0 - - - backend/src/main/java/**/*.java - vendor/lithe-plugin-sdk-java/src/main/java/**/*.java - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - io.github.litheidea.maven.backend.MavenBackend - - - ${project.version} - - - - - - - - - org.apache.maven.plugins - maven-clean-plugin - 3.4.0 - - - org.apache.maven.plugins - maven-resources-plugin - 3.3.1 - - - org.apache.maven.plugins - maven-compiler-plugin - 3.13.0 - - - org.apache.maven.plugins - maven-surefire-plugin - 3.5.2 - - - org.apache.maven.plugins - maven-jar-plugin - 3.4.2 - - - org.apache.maven.plugins - maven-install-plugin - 3.1.3 - - - - - diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/Fingerprint.java b/backend/src/main/java/io/github/litheidea/maven/backend/Fingerprint.java deleted file mode 100644 index 9ece30a..0000000 --- a/backend/src/main/java/io/github/litheidea/maven/backend/Fingerprint.java +++ /dev/null @@ -1,230 +0,0 @@ -package io.github.litheidea.maven.backend; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.FileVisitResult; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.SimpleFileVisitor; -import java.nio.file.attribute.BasicFileAttributes; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; - -/** - * A digest of everything that can change what Maven reports for a root. A - * snapshot is only reused when its fingerprint equals the current one. - * - * - * - *

Inputs outside these, such as a parent POM outside the root or a changed - * SNAPSHOT in a remote repository, need an explicit refresh. - */ -final class Fingerprint { - /** Bumped when the inputs below change meaning. */ - private static final int VERSION = 1; - private static final int MAX_DEPTH = 24; - private static final int MAX_ENTRIES = 50_000; - private static final Set SKIPPED = new HashSet<>(Arrays.asList("target", ".git", "node_modules")); - private static final List ENVIRONMENT = Arrays.asList( - "JAVA_HOME", "MAVEN_HOME", "M2_HOME", "MAVEN_OPTS", "MAVEN_ARGS", "MAVEN_CONFIG"); - private static final List SETTINGS_FLAGS = Arrays.asList( - "-s", "--settings", "-gs", "--global-settings", "-t", "--toolchains", "-gt", "--global-toolchains"); - - private final MessageDigest digest; - - private Fingerprint() { - try { - digest = MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException error) { - throw new IllegalStateException(error); - } - } - - static String of(Inputs inputs) throws IOException { - Fingerprint fingerprint = new Fingerprint(); - fingerprint.add("fingerprint", Integer.toString(VERSION)); - fingerprint.add("backend", MavenBackend.VERSION); - fingerprint.add("root", inputs.root.toString()); - fingerprint.addPoms(inputs.root); - for (String name : Arrays.asList("maven.config", "extensions.xml", "jvm.config", "wrapper/maven-wrapper.properties")) { - fingerprint.addFile(".mvn/" + name, inputs.root.resolve(".mvn").resolve(name)); - } - - Path userHome = Paths.get(System.getProperty("user.home")); - fingerprint.addFile("userSettings", userHome.resolve(".m2/settings.xml")); - fingerprint.addFile("userToolchains", userHome.resolve(".m2/toolchains.xml")); - Path mavenHome = mavenHome(inputs); - if (mavenHome != null) { - fingerprint.add("mavenHome", mavenHome.toString()); - fingerprint.addFile("globalSettings", mavenHome.resolve("conf/settings.xml")); - } - List configArguments = mavenConfig(inputs.root); - for (List arguments : Arrays.asList(inputs.optionArguments, configArguments)) { - for (String file : settingsFiles(arguments)) { - fingerprint.addFile("settingsFile " + file, inputs.root.resolve(file)); - } - } - - fingerprint.add("optionArguments", String.join("\u0000", inputs.optionArguments)); - for (Map.Entry entry : new TreeMap<>(inputs.hostEnvironment).entrySet()) { - fingerprint.add("hostEnvironment " + entry.getKey(), entry.getValue()); - } - for (String name : ENVIRONMENT) { - fingerprint.add("environment " + name, inputs.environment.get(name)); - } - fingerprint.add("maven", inputs.maven.toString()); - fingerprint.addStamp("mavenStamp", inputs.maven); - fingerprint.add("java.version", System.getProperty("java.version")); - fingerprint.addFile("extension", inputs.extensionJar); - return fingerprint.hex(); - } - - /** {@code -s file}, {@code --settings file}, {@code --settings=file} and {@code -sfile} forms. */ - static List settingsFiles(List arguments) { - List files = new java.util.ArrayList<>(); - for (int index = 0; index < arguments.size(); index++) { - String argument = arguments.get(index); - for (String flag : SETTINGS_FLAGS) { - if (argument.equals(flag) && index + 1 < arguments.size()) { - files.add(arguments.get(++index)); - break; - } - if (flag.startsWith("--") && argument.startsWith(flag + "=")) { - files.add(argument.substring(flag.length() + 1)); - break; - } - } - } - return files; - } - - /** The Maven installation an {@code mvn} script belongs to; none for a wrapper. */ - private static Path mavenHome(Inputs inputs) { - if (inputs.maven.getFileName().toString().startsWith("mvnw")) { - return null; - } - try { - Path real = inputs.maven.toRealPath(); - Path bin = real.getParent(); - return bin == null || bin.getParent() == null ? null : bin.getParent(); - } catch (IOException error) { - return null; - } - } - - private static List mavenConfig(Path root) { - Path config = root.resolve(".mvn/maven.config"); - if (!Files.isRegularFile(config)) { - return Collections.emptyList(); - } - try { - String text = new String(Files.readAllBytes(config), StandardCharsets.UTF_8).trim(); - return text.isEmpty() ? Collections.emptyList() : Arrays.asList(text.split("\\s+")); - } catch (IOException error) { - return Collections.emptyList(); - } - } - - private void addPoms(Path root) throws IOException { - TreeMap poms = new TreeMap<>(); - int[] entries = {0}; - boolean[] truncated = {false}; - Files.walkFileTree(root, Collections.emptySet(), MAX_DEPTH, new SimpleFileVisitor() { - @Override - public FileVisitResult preVisitDirectory(Path directory, BasicFileAttributes attributes) { - if (!directory.equals(root) && SKIPPED.contains(directory.getFileName().toString())) { - return FileVisitResult.SKIP_SUBTREE; - } - return count(); - } - - @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException { - if (attributes.isRegularFile() && file.getFileName().toString().equals("pom.xml")) { - poms.put(root.relativize(file).toString(), sha256(Files.readAllBytes(file))); - } - return count(); - } - - @Override - public FileVisitResult visitFileFailed(Path file, IOException error) { - return count(); - } - - private FileVisitResult count() { - if (++entries[0] > MAX_ENTRIES) { - truncated[0] = true; - return FileVisitResult.TERMINATE; - } - return FileVisitResult.CONTINUE; - } - }); - for (Map.Entry pom : poms.entrySet()) { - add("pom " + pom.getKey(), pom.getValue()); - } - add("pomWalk", truncated[0] ? "truncated" : "complete"); - } - - private void addFile(String label, Path path) throws IOException { - if (Files.isRegularFile(path)) { - add(label, sha256(Files.readAllBytes(path))); - } else { - add(label, null); - } - } - - private void addStamp(String label, Path path) { - try { - Path real = path.toRealPath(); - add(label, real + " " + Files.getLastModifiedTime(real).toMillis() + " " + Files.size(real)); - } catch (IOException error) { - add(label, null); - } - } - - private void add(String label, String value) { - digest.update(label.getBytes(StandardCharsets.UTF_8)); - digest.update((byte) 0); - // Absent and empty differ. - digest.update(value == null ? new byte[] {1} : ("=" + value).getBytes(StandardCharsets.UTF_8)); - digest.update((byte) 0); - } - - private String hex() { - return hex(digest.digest()); - } - - private static String sha256(byte[] bytes) { - try { - return hex(MessageDigest.getInstance("SHA-256").digest(bytes)); - } catch (NoSuchAlgorithmException error) { - throw new IllegalStateException(error); - } - } - - private static String hex(byte[] bytes) { - StringBuilder text = new StringBuilder(bytes.length * 2); - for (byte value : bytes) { - text.append(Character.forDigit((value >> 4) & 0xf, 16)).append(Character.forDigit(value & 0xf, 16)); - } - return text.toString(); - } -} diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/Inputs.java b/backend/src/main/java/io/github/litheidea/maven/backend/Inputs.java deleted file mode 100644 index 05a1eb6..0000000 --- a/backend/src/main/java/io/github/litheidea/maven/backend/Inputs.java +++ /dev/null @@ -1,28 +0,0 @@ -package io.github.litheidea.maven.backend; - -import java.nio.file.Path; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -/** What one Maven run reads, as resolved for one request. */ -final class Inputs { - final Path root; - final Path maven; - final List optionArguments; - /** The environment Maven runs with. */ - final Map environment; - /** The part of it the host's options contributed. */ - final Map hostEnvironment; - final Path extensionJar; - - Inputs(Path root, Path maven, List optionArguments, Map environment, - Map hostEnvironment, Path extensionJar) { - this.root = root; - this.maven = maven; - this.optionArguments = Collections.unmodifiableList(optionArguments); - this.environment = Collections.unmodifiableMap(environment); - this.hostEnvironment = Collections.unmodifiableMap(hostEnvironment); - this.extensionJar = extensionJar; - } -} diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/LanguageImport.java b/backend/src/main/java/io/github/litheidea/maven/backend/LanguageImport.java deleted file mode 100644 index cde4026..0000000 --- a/backend/src/main/java/io/github/litheidea/maven/backend/LanguageImport.java +++ /dev/null @@ -1,136 +0,0 @@ -package io.github.litheidea.maven.backend; - -import io.github.litheidea.plugin.sdk.CallContext; -import io.github.litheidea.plugin.sdk.Json; -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.nio.file.Paths; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -/** - * The plugin function {@code languageImport.settings} (version 1) that Java - * Support calls before it starts JDT LS: the import settings Maven's own - * project configuration implies. It reads {@code .mvn/maven.config} only, runs - * nothing and writes nothing; the workspace root it is asked about must lie - * inside an open local workspace folder. - * - *

{@code -s/--settings} becomes {@code java.configuration.maven.userSettings}, - * {@code -gs/--global-settings} {@code java.configuration.maven.globalSettings} - * and {@code -o/--offline} {@code java.import.maven.offline.enabled}. - */ -final class LanguageImport { - static final String FUNCTION = "languageImport.settings"; - private static final long MAX_CONFIG_BYTES = 64 * 1024; - - private LanguageImport() {} - - /** The function handler. */ - static Object handle(Map params, CallContext context) throws Exception { - String requested = Json.string(params, "workspaceRoot"); - if (requested == null || !Paths.get(requested).isAbsolute()) { - throw new PluginError("maven.invalidRoot", "workspaceRoot must be an absolute path."); - } - Map workspace = context.workspaceContext(); - if (workspace == null) { - throw new PluginError("maven.noWorkspaceContext", "The call carries no workspace context."); - } - Path root = Paths.get(requested).toRealPath(); - Map answer = context.host().workspace().getFolders(workspace).get(10, TimeUnit.SECONDS); - if (!insideFolder(root, answer.get("folders"))) { - throw new PluginError("maven.invalidRoot", "workspaceRoot is not inside an open workspace folder."); - } - context.throwIfCancelled(); - return settings(root); - } - - private static boolean insideFolder(Path root, Object folders) throws IOException { - if (!(folders instanceof List)) { - return false; - } - for (Object folder : (List) folders) { - Object path = folder instanceof Map ? ((Map) folder).get("path") : null; - if (path instanceof String && root.startsWith(Paths.get((String) path).toRealPath())) { - return true; - } - } - return false; - } - - /** {@code { settings }} for the Maven build at {@code root}. */ - static Map settings(Path root) throws IOException { - Map settings = new LinkedHashMap<>(); - Path config = root.resolve(".mvn").resolve("maven.config"); - if (Files.isRegularFile(config) && Files.size(config) <= MAX_CONFIG_BYTES) { - List tokens = tokens(new String(Files.readAllBytes(config), StandardCharsets.UTF_8)); - for (int index = 0; index < tokens.size(); index++) { - String token = tokens.get(index); - String next = index + 1 < tokens.size() ? tokens.get(index + 1) : null; - if (token.equals("-o") || token.equals("--offline")) { - settings.put("java.import.maven.offline.enabled", Boolean.TRUE); - } else if (token.equals("-s") || token.equals("--settings")) { - put(settings, "java.configuration.maven.userSettings", root, next); - } else if (token.startsWith("--settings=")) { - put(settings, "java.configuration.maven.userSettings", root, token.substring(11)); - } else if (token.equals("-gs") || token.equals("--global-settings")) { - put(settings, "java.configuration.maven.globalSettings", root, next); - } else if (token.startsWith("--global-settings=")) { - put(settings, "java.configuration.maven.globalSettings", root, token.substring(18)); - } - } - } - Map result = new LinkedHashMap<>(); - result.put("settings", settings); - return result; - } - - private static void put(Map settings, String key, Path root, String value) { - if (value == null || value.isEmpty() || value.startsWith("-")) { - return; - } - Path path = root.resolve(value).normalize(); - if (Files.isRegularFile(path)) { - settings.put(key, path.toString()); - } - } - - /** Whitespace-separated tokens; double or single quotes keep spaces. */ - static List tokens(String text) { - List tokens = new ArrayList<>(); - StringBuilder current = new StringBuilder(); - char quote = 0; - boolean started = false; - for (int index = 0; index < text.length(); index++) { - char c = text.charAt(index); - if (quote != 0) { - if (c == quote) { - quote = 0; - } else { - current.append(c); - } - } else if (c == '"' || c == '\'') { - quote = c; - started = true; - } else if (Character.isWhitespace(c)) { - if (started) { - tokens.add(current.toString()); - current.setLength(0); - started = false; - } - } else { - current.append(c); - started = true; - } - } - if (started) { - tokens.add(current.toString()); - } - return tokens; - } -} diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/MavenBackend.java b/backend/src/main/java/io/github/litheidea/maven/backend/MavenBackend.java deleted file mode 100644 index 34e7c75..0000000 --- a/backend/src/main/java/io/github/litheidea/maven/backend/MavenBackend.java +++ /dev/null @@ -1,201 +0,0 @@ -package io.github.litheidea.maven.backend; - -import io.github.litheidea.plugin.sdk.Backend; -import io.github.litheidea.plugin.sdk.CallContext; -import io.github.litheidea.plugin.sdk.Json; -import io.github.litheidea.plugin.sdk.PluginError; -import io.github.litheidea.plugin.sdk.StateStore; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -/** - * Lithe's build provider for Maven. It answers {@code lithe/build/model} and - * {@code lithe/build/dependencies} for every Maven root of one workspace. - * - *

One Maven run with the bundled extension writes both the model and the - * dependency tree of every module. The result is kept in - * {@code maven-snapshot.json} in the workspace state directory, so a request - * whose inputs (see {@link Fingerprint}) did not change, also after Lithe - * restarted, is answered without starting Maven. A request with - * {@code refresh: true} always runs Maven. - */ -public final class MavenBackend { - static final String VERSION = version(); - - private final Backend backend = Backend.create("lithe-maven-backend", VERSION); - private final String stateDirectory; - private final boolean pluginBackend; - private volatile Path workspaceRoot; - private volatile Snapshots snapshots; - private volatile MavenRuns runs; - - private MavenBackend(String stateDirectory, boolean pluginBackend) { - this.stateDirectory = stateDirectory; - this.pluginBackend = pluginBackend; - } - - public static void main(String[] arguments) { - boolean pluginBackend = Arrays.asList(arguments).contains("--plugin-backend"); - new MavenBackend(argument(arguments, "--state"), pluginBackend).serve(); - } - - private void serve() { - if (pluginBackend) { - // The plugin backend (manifest `backend`) only exports plugin functions - // to other plugins; the build provider is the other launch of this JAR. - backend.function(LanguageImport.FUNCTION, LanguageImport::handle); - backend.listen(); - return; - } - backend.onInitialize((params, negotiated) -> { - workspaceRoot = workspaceRoot(Json.string(params, "rootUri")); - Path state = null; - if (stateDirectory != null && !stateDirectory.isEmpty()) { - // `--state ${workspaceStateDir}`: writable and kept across restarts. - StateStore store = StateStore.open(Paths.get(stateDirectory)); - snapshots = new Snapshots(store, backend); - state = store.directory(); - } else { - backend.diagnostics().degraded("initialize", "maven.stateUnavailable"); - } - runs = new MavenRuns(snapshots, backend, state); - }); - backend.onModel((params, context) -> copy(load(params, context).model())); - backend.onDependencies(this::dependencies); - backend.listen(); - } - - private Object dependencies(Map params, CallContext context) throws Exception { - Path root = root(params); - MavenRuns.Loaded loaded = load(params, context); - Object selected = params.get("project"); - if (!(selected instanceof Map)) { - return copy(loaded.dependencies()); - } - String path = Json.string(Json.object(selected), "path"); - if (path == null) { - throw new PluginError("maven.invalidProject", "The selected project has no path."); - } - Map result = new LinkedHashMap<>(); - result.put("dependencies", Projects.dependenciesOf(loaded, root, path)); - return result; - } - - private MavenRuns.Loaded load(Map params, CallContext context) throws Exception { - if (runs == null) { - throw new PluginError("maven.notInitialized", "The Maven backend was not initialized."); - } - Path root = root(params); - if (!Files.isDirectory(root)) { - throw new PluginError("maven.missingRoot", root + " is not a directory."); - } - Map environment = environment(params.get("environment")); - Object tool = params.get("tool"); - String executable = tool instanceof Map ? Json.string(Json.object(tool), "executable") : null; - Path maven = MavenExecutable.resolve(executable, root, environment); - Inputs inputs = new Inputs(root, maven, strings(params.get("optionArguments")), - environment, hostEnvironment(params.get("environment")), extensionJar()); - boolean refresh = Boolean.TRUE.equals(params.get("refresh")); - return runs.load(inputs, refresh, context.cancellation()); - } - - private Path root(Map params) { - String root = Json.string(params, "root"); - Path base = workspaceRoot == null ? Paths.get("").toAbsolutePath() : workspaceRoot; - return base.resolve(root == null || root.isEmpty() ? "." : root).toAbsolutePath().normalize(); - } - - /** - * The backend's own environment with what the host's options contribute - * on top. JAVA_HOME defaults to the runtime Lithe started this backend - * with, which is the JDK it found for Maven too. - */ - private static Map environment(Object fromHost) { - Map environment = new LinkedHashMap<>(System.getenv()); - environment.putAll(hostEnvironment(fromHost)); - if (!environment.containsKey("JAVA_HOME")) { - environment.put("JAVA_HOME", System.getProperty("java.home")); - } - return environment; - } - - private static Map hostEnvironment(Object fromHost) { - Map result = new LinkedHashMap<>(); - if (fromHost instanceof Map) { - for (Map.Entry entry : ((Map) fromHost).entrySet()) { - if (entry.getKey() instanceof String && entry.getValue() instanceof String) { - result.put((String) entry.getKey(), (String) entry.getValue()); - } - } - } - return result; - } - - private static List strings(Object value) { - if (!(value instanceof List)) { - return Collections.emptyList(); - } - List result = new ArrayList<>(); - for (Object item : (List) value) { - if (item instanceof String) { - result.add((String) item); - } - } - return result; - } - - /** The extension ships next to this JAR: {@code lib/lithe-maven-extension.jar}. */ - private static Path extensionJar() { - try { - Path self = Paths.get(MavenBackend.class.getProtectionDomain().getCodeSource().getLocation().toURI()); - Path extension = self.resolveSibling("lithe-maven-extension.jar"); - if (Files.isRegularFile(extension)) { - return extension; - } - throw new PluginError("maven.missingExtension", - "The plugin package is missing lib/lithe-maven-extension.jar. Reinstall the Maven plugin."); - } catch (URISyntaxException | RuntimeException error) { - if (error instanceof PluginError) { - throw (PluginError) error; - } - throw new PluginError("maven.missingExtension", "The Maven plugin cannot locate its extension.", error); - } - } - - private static Path workspaceRoot(String rootUri) throws IOException { - if (rootUri == null) { - return Paths.get("").toAbsolutePath(); - } - // `Paths.get(URI)` accepts the trailing slash a directory URI may carry. - return Paths.get(URI.create(rootUri)).toAbsolutePath().normalize(); - } - - /** A shallow copy: the SDK stamps {@code format} on the returned document. */ - private static Map copy(Map document) { - return new LinkedHashMap<>(document); - } - - private static String version() { - String version = MavenBackend.class.getPackage().getImplementationVersion(); - return version == null ? "development" : version; - } - - private static String argument(String[] arguments, String name) { - for (int index = 0; index + 1 < arguments.length; index++) { - if (arguments[index].equals(name)) { - return arguments[index + 1]; - } - } - return null; - } -} diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/MavenExecutable.java b/backend/src/main/java/io/github/litheidea/maven/backend/MavenExecutable.java deleted file mode 100644 index de46eb4..0000000 --- a/backend/src/main/java/io/github/litheidea/maven/backend/MavenExecutable.java +++ /dev/null @@ -1,54 +0,0 @@ -package io.github.litheidea.maven.backend; - -import io.github.litheidea.plugin.sdk.PluginError; -import java.io.File; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Map; - -/** - * The Maven a run uses. Lithe resolves the executable from plugin.json's - * {@code invocation} (wrapper, MAVEN_HOME, PATH, the user's override) and - * passes it as {@code tool.executable}. A host that predates that parameter - * passes nothing; the same order is then followed here. - */ -final class MavenExecutable { - private MavenExecutable() {} - - static Path resolve(String fromHost, Path root, Map environment) { - if (fromHost != null && !fromHost.isEmpty()) { - Path path = root.resolve(fromHost).toAbsolutePath().normalize(); - if (!Files.isRegularFile(path) || !Files.isExecutable(path)) { - throw new PluginError("maven.notFound", "The Maven executable " + path + " is missing or not executable."); - } - return path; - } - Path wrapper = root.resolve("mvnw"); - if (Files.isRegularFile(root.resolve(".mvn/wrapper/maven-wrapper.properties")) && Files.isExecutable(wrapper)) { - return wrapper; - } - String home = environment.get("MAVEN_HOME"); - if (home != null && !home.isEmpty()) { - Path mvn = Paths.get(home, "bin", "mvn"); - if (Files.isRegularFile(mvn) && Files.isExecutable(mvn)) { - return mvn.toAbsolutePath().normalize(); - } - } - String path = environment.get("PATH"); - if (path != null) { - for (String directory : path.split(File.pathSeparator)) { - if (directory.isEmpty()) { - continue; - } - Path mvn = Paths.get(directory, "mvn"); - if (Files.isRegularFile(mvn) && Files.isExecutable(mvn)) { - return mvn.toAbsolutePath().normalize(); - } - } - } - throw new PluginError("maven.notFound", - "Lithe found no Maven: no Maven Wrapper in the project, no MAVEN_HOME and no mvn on PATH. " - + "Install Maven 3.6.3 or newer, for example with `brew install maven`."); - } -} diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/MavenRuns.java b/backend/src/main/java/io/github/litheidea/maven/backend/MavenRuns.java deleted file mode 100644 index 63624b1..0000000 --- a/backend/src/main/java/io/github/litheidea/maven/backend/MavenRuns.java +++ /dev/null @@ -1,265 +0,0 @@ -package io.github.litheidea.maven.backend; - -import io.github.litheidea.plugin.sdk.Backend; -import io.github.litheidea.plugin.sdk.Cancellation; -import io.github.litheidea.plugin.sdk.CancelledException; -import io.github.litheidea.plugin.sdk.Json; -import io.github.litheidea.plugin.sdk.PluginError; -import io.github.litheidea.plugin.sdk.Processes; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.Deque; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.function.Consumer; -import java.util.stream.Stream; - -/** - * Answers a request from the snapshot, or from one Maven run shared by every - * request that needs it. - * - *

A run belongs to no single request: it goes on while any request still - * waits for it and is stopped once all of them were cancelled. Its result is - * saved only when the inputs did not change while Maven ran, so a POM edited - * mid-run never hides behind a snapshot of the old one. - */ -final class MavenRuns { - /** The model and the dependency tree of every module of one root. */ - static final class Loaded { - private final Map model; - private final Map dependencies; - - Loaded(Map model, Map dependencies) { - this.model = model; - this.dependencies = dependencies; - } - - Map model() { - return model; - } - - Map dependencies() { - return dependencies; - } - } - - /** One Maven run and the requests waiting for it. */ - private static final class Flight { - final String key; - final CompletableFuture result = new CompletableFuture<>(); - final Cancellation cancellation = new Cancellation(); - int waiters; - - Flight(String key) { - this.key = key; - } - } - - private static final int ERROR_LINES = 40; - - private final Snapshots snapshots; - private final Backend backend; - private final Path workDirectory; - private final Map flights = new HashMap<>(); - private final ExecutorService executor = Executors.newCachedThreadPool(runnable -> { - Thread thread = new Thread(runnable, "maven-run"); - thread.setDaemon(true); - return thread; - }); - - /** - * @param workDirectory where a run's output files go; the system's - * temporary directory when null - */ - MavenRuns(Snapshots snapshots, Backend backend, Path workDirectory) { - this.snapshots = snapshots; - this.backend = backend; - this.workDirectory = workDirectory; - } - - Loaded load(Inputs inputs, boolean refresh, Cancellation request) throws Exception { - String fingerprint = Fingerprint.of(inputs); - if (!refresh && snapshots != null) { - Loaded stored = snapshots.read(inputs.root, fingerprint); - if (stored != null) { - return stored; - } - } - request.throwIfCancelled(); - Flight flight; - synchronized (flights) { - String key = inputs.root + "\u0000" + fingerprint; - flight = flights.get(key); - if (flight == null) { - Flight started = new Flight(key); - flights.put(key, started); - executor.execute(() -> fly(started, inputs, fingerprint)); - flight = started; - } - flight.waiters++; - } - Flight joined = flight; - CompletableFuture mine = new CompletableFuture<>(); - joined.result.whenComplete((value, error) -> { - if (error != null) { - mine.completeExceptionally(error); - } else { - mine.complete(value); - } - }); - Cancellation.Registration registration = request.onCancel(() -> { - leave(joined); - mine.completeExceptionally(new CancelledException("The request was cancelled.")); - }); - try { - return mine.get(); - } catch (ExecutionException error) { - Throwable cause = error.getCause(); - if (cause instanceof Exception) { - throw (Exception) cause; - } - throw error; - } finally { - registration.remove(); - } - } - - /** The last waiter leaving stops the run. */ - private void leave(Flight flight) { - synchronized (flights) { - if (--flight.waiters > 0 || flight.result.isDone()) { - return; - } - flights.remove(flight.key, flight); - } - flight.cancellation.cancel("Every request waiting for Maven was cancelled."); - } - - private void fly(Flight flight, Inputs inputs, String before) { - try { - Loaded loaded = run(inputs, flight.cancellation); - if (snapshots != null) { - if (before.equals(Fingerprint.of(inputs))) { - snapshots.write(inputs.root, before, loaded); - } else { - backend.diagnostics().degraded("lithe/build/model", "maven.inputsChanged"); - } - } - flight.result.complete(loaded); - } catch (Throwable error) { - flight.result.completeExceptionally(error); - } finally { - synchronized (flights) { - flights.remove(flight.key, flight); - } - } - } - - private Loaded run(Inputs inputs, Cancellation cancellation) throws IOException { - Path work = workDirectory == null - ? Files.createTempDirectory("lithe-maven-") - : Files.createTempDirectory(workDirectory, "run-"); - try { - Path model = work.resolve("model.json"); - Path dependencies = work.resolve("dependencies.json"); - List command = new ArrayList<>(); - command.add(inputs.maven.toString()); - command.add("-B"); - command.add("-ntp"); - command.addAll(inputs.optionArguments); - command.add("-Dmaven.ext.class.path=" + inputs.extensionJar); - command.add("-Dlithe.modelOutput=" + model); - // No lithe.dependenciesProject: every module's tree, in the same run. - command.add("-Dlithe.dependenciesOutput=" + dependencies); - command.add("pre-clean"); - Tail tail = new Tail(ERROR_LINES); - Processes.Result result = Processes.run(command, new Processes.Options() - .directory(inputs.root) - .environment(inputs.environment) - .cancellation(cancellation) - .maxOutputBytes(64 * 1024) - .onStdout(tail) - .onStderr(tail)); - if (result.exitCode() != 0) { - String output = tail.errors(); - // The SDK records this failed request once. Build output belongs - // to the response, never to the diagnostic stderr stream. - throw new PluginError("maven.loadFailed", "Maven could not read the project (exit status " - + result.exitCode() + ")." + (output.isEmpty() ? "" : "\n" + output)); - } - return new Loaded(document(model, "model"), document(dependencies, "dependency tree")); - } finally { - delete(work); - } - } - - private static Map document(Path file, String what) { - try { - Object value = Json.parse(new String(Files.readAllBytes(file), StandardCharsets.UTF_8)); - if (value instanceof Map) { - return Json.object(value); - } - } catch (IOException | RuntimeException error) { - throw new PluginError("maven.invalidOutput", "Maven finished without writing the " + what + ".", error); - } - throw new PluginError("maven.invalidOutput", "Maven wrote an unreadable " + what + "."); - } - - private static void delete(Path directory) { - try (Stream paths = Files.walk(directory)) { - paths.sorted(Comparator.reverseOrder()).forEach(path -> path.toFile().delete()); - } catch (IOException ignored) { - // A leftover file in the state directory is harmless. - } - } - - /** The last lines of Maven's output, for the error a failed run reports. */ - private static final class Tail implements Consumer { - private final int limit; - private final Deque lines = new ArrayDeque<>(); - private final StringBuilder partial = new StringBuilder(); - - Tail(int limit) { - this.limit = limit; - } - - @Override - public synchronized void accept(String text) { - partial.append(text); - int end; - while ((end = partial.indexOf("\n")) >= 0) { - lines.addLast(partial.substring(0, end)); - partial.delete(0, end + 1); - if (lines.size() > limit) { - lines.removeFirst(); - } - } - } - - /** {@code [ERROR]} lines when there are any, otherwise the whole tail. */ - synchronized String errors() { - List all = new ArrayList<>(lines); - if (partial.length() > 0) { - all.add(partial.toString()); - } - List errors = new ArrayList<>(); - for (String line : all) { - if (line.startsWith("[ERROR]")) { - errors.add(line); - } - } - String text = String.join("\n", errors.isEmpty() ? all : errors).trim(); - return text.length() > 4000 ? text.substring(text.length() - 4000) : text; - } - } -} diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/Projects.java b/backend/src/main/java/io/github/litheidea/maven/backend/Projects.java deleted file mode 100644 index 37464f3..0000000 --- a/backend/src/main/java/io/github/litheidea/maven/backend/Projects.java +++ /dev/null @@ -1,69 +0,0 @@ -package io.github.litheidea.maven.backend; - -import io.github.litheidea.plugin.sdk.Json; -import io.github.litheidea.plugin.sdk.PluginError; -import java.io.IOException; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -/** - * Picks one project's subtree out of the workspace dependency document. - * - *

The extension lists every reactor project as a node with its - * coordinates but without its path; the model has both. A selected path is - * matched to a model project, and that project's coordinates to its node. - */ -final class Projects { - private Projects() {} - - static List dependenciesOf(MavenRuns.Loaded loaded, Path root, String path) { - Path wanted = root.resolve(path).toAbsolutePath().normalize(); - List projects = list(loaded.model().get("projects")); - List nodes = list(loaded.dependencies().get("dependencies")); - for (int index = 0; index < projects.size(); index++) { - Map project = Json.object(projects.get(index)); - String projectPath = Json.string(project, "path"); - if (projectPath == null || !samePath(wanted, root.resolve(projectPath))) { - continue; - } - Map properties = Json.object(project.get("properties")); - for (Object candidate : nodes) { - Map node = Json.object(candidate); - if (Objects.equals(node.get("group"), properties.get("groupId")) - && Objects.equals(node.get("name"), properties.get("artifactId")) - && Objects.equals(node.get("version"), properties.get("version"))) { - return new ArrayList<>(list(node.get("children"))); - } - } - // Same order as the reactor, when coordinates are missing. - if (nodes.size() == projects.size() - && Objects.equals(Json.object(nodes.get(index)).get("name"), project.get("name"))) { - return new ArrayList<>(list(Json.object(nodes.get(index)).get("children"))); - } - } - throw new PluginError("maven.unknownProject", "Maven reports no project at " + path + "."); - } - - private static boolean samePath(Path wanted, Path candidate) { - Path normalized = candidate.toAbsolutePath().normalize(); - if (normalized.equals(wanted)) { - return true; - } - try { - return normalized.toRealPath().equals(wanted.toRealPath()); - } catch (IOException error) { - return false; - } - } - - private static List list(Object value) { - List result = new ArrayList<>(); - if (value instanceof List) { - result.addAll((List) value); - } - return result; - } -} diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/Snapshots.java b/backend/src/main/java/io/github/litheidea/maven/backend/Snapshots.java deleted file mode 100644 index c3ca261..0000000 --- a/backend/src/main/java/io/github/litheidea/maven/backend/Snapshots.java +++ /dev/null @@ -1,109 +0,0 @@ -package io.github.litheidea.maven.backend; - -import io.github.litheidea.plugin.sdk.Backend; -import io.github.litheidea.plugin.sdk.Json; -import io.github.litheidea.plugin.sdk.StateStore; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -/** - * {@code maven-snapshot.json}: the last Maven result of each root, with the - * fingerprint of the inputs it was computed from. - * - *
- * { "snapshotVersion": 1,
- *   "roots": { "/abs/root": { "fingerprint", "savedAt", "model", "dependencies" } } }
- * 
- * - *

The {@link StateStore} replaces the file atomically. A file that cannot - * be read, has another {@code snapshotVersion} or lacks a field is a miss, - * never an error: the next run overwrites it. - */ -final class Snapshots { - static final String KEY = "maven-snapshot"; - static final int VERSION = 1; - /** Roots kept per workspace; the least recently saved go first. */ - private static final int MAX_ROOTS = 32; - - private final StateStore store; - private final Backend backend; - - Snapshots(StateStore store, Backend backend) { - this.store = store; - this.backend = backend; - } - - /** The stored result for {@code root}, or null when there is none for {@code fingerprint}. */ - synchronized MavenRuns.Loaded read(Path root, String fingerprint) { - Map entry = Json.object(roots(store.read(KEY, null)).get(root.toString())); - if (!fingerprint.equals(entry.get("fingerprint")) - || !(entry.get("model") instanceof Map) || !(entry.get("dependencies") instanceof Map)) { - return null; - } - return new MavenRuns.Loaded(Json.object(entry.get("model")), Json.object(entry.get("dependencies"))); - } - - synchronized void write(Path root, String fingerprint, MavenRuns.Loaded loaded) { - Map roots = roots(store.read(KEY, null)); - Map entry = new LinkedHashMap<>(); - entry.put("fingerprint", fingerprint); - entry.put("savedAt", System.currentTimeMillis()); - entry.put("model", loaded.model()); - entry.put("dependencies", loaded.dependencies()); - roots.remove(root.toString()); - roots.put(root.toString(), entry); - prune(roots); - Map snapshot = new LinkedHashMap<>(); - snapshot.put("snapshotVersion", VERSION); - snapshot.put("roots", roots); - try { - store.write(KEY, snapshot); - } catch (IOException | RuntimeException error) { - // The result is still answered; only the next start runs Maven again. - backend.diagnostics().degraded("lithe/build/model", "maven.snapshotSaveFailed"); - } - } - - private static Map roots(Object stored) { - Map result = new LinkedHashMap<>(); - if (!(stored instanceof Map)) { - return result; - } - Object version = ((Map) stored).get("snapshotVersion"); - Object roots = ((Map) stored).get("roots"); - if (!(version instanceof Number) || ((Number) version).doubleValue() != VERSION || !(roots instanceof Map)) { - return result; - } - for (Map.Entry entry : ((Map) roots).entrySet()) { - if (entry.getKey() instanceof String && entry.getValue() instanceof Map) { - result.put((String) entry.getKey(), entry.getValue()); - } - } - return result; - } - - /** Drops roots that no longer exist, then the oldest beyond {@link #MAX_ROOTS}. */ - private static void prune(Map roots) { - roots.keySet().removeIf(root -> !Files.isDirectory(Paths.get(root))); - if (roots.size() <= MAX_ROOTS) { - return; - } - List> entries = new ArrayList<>(roots.entrySet()); - entries.sort(Comparator.comparingDouble(entry -> savedAt(entry.getValue()))); - for (int index = 0; index < entries.size() - MAX_ROOTS; index++) { - roots.remove(entries.get(index).getKey()); - } - } - - private static double savedAt(Object entry) { - Object value = Json.object(entry).get("savedAt"); - return value instanceof Number ? ((Number) value).doubleValue() : 0; - } -} diff --git a/docs/releases/v0.0.1.md b/docs/releases/v0.0.1.md new file mode 100644 index 0000000..97a65d8 --- /dev/null +++ b/docs/releases/v0.0.1.md @@ -0,0 +1,17 @@ +0.0.1 是按插件契约 v0 重新发布的首个版本。 + +功能: +- 识别工作区最外层的 `pom.xml`,`` 组成模块树。 +- 生命周期 `clean` 到 `deploy`,可对整个反应堆或单个模块运行;每个模块的插件目标按 `Plugins › <前缀>` 分组。 +- 运行模块、测试类或单个测试方法,读取 Surefire/Failsafe 的 JUnit XML 报告。 +- 编译输出里的 `[ERROR]`、`[WARNING]` 显示为问题。 +- 整个反应堆或单个模块的依赖树,反应堆内未安装的兄弟模块也能解析。 +- 插件设置 Maven executable;构建选项 JDK (JAVA_HOME)、Profiles、Settings File、Local Repository、Offline、Skip Tests。 +- 新建项目:Maven(可选 Java release 8、11、17、21、25)和 Maven Archetype。 +- 插件没有后端进程:读取项目和依赖是 `plugin.json` 声明的 Maven 命令,由 Lithe 运行,随包的 Maven 扩展只读取反应堆。 + +权限:`process.build`、`project.generate`。 + +兼容性: +- 只能装进新版 Lithe 桌面端(`desktop-v*` 预发布),旧版 macOS Lithe 无法安装。 +- 本版本是预发布,Lithe Store 的自动追踪会跳过它。 diff --git a/docs/releases/v0.1.2.md b/docs/releases/v0.1.2.md deleted file mode 100644 index 4721ffc..0000000 --- a/docs/releases/v0.1.2.md +++ /dev/null @@ -1,6 +0,0 @@ -0.1.2 的变化: - -- 构建后端接入 litheLogging 1:关键请求成功记 INFO、失败记 ERROR,带耗时和稳定分类,写入 Lithe 日志窗口的 `plugins/io.github.lithe-idea.maven-build/host` 通道;取消不记失败。 -- 没有 `--state` 目录、快照保存失败、读取期间项目发生变化时各记一次 WARN `degraded`。Maven 失败只由 SDK 记录一次 ERROR,不再重复打印构建输出;源码、凭据、环境变量和构建输出不进入日志。 -- 后端直接编译 `vendor/` 下官方 Java SDK 的源码(逐文件 SHA-256 校验),不再下载 SDK JAR;安装包附带 `SDK-LICENSE`。 -- 移除宿主已删除的 `languageImport` 清单字段(Core 严格校验会拒绝它);改为导出插件函数 `languageImport.settings`,由插件后端(`--plugin-backend`)按 `.mvn/maven.config` 的 `-s`、`-gs`、`-o` 向 Java Support 提供导入设置,需要 `backend: 2` 与 `pluginFunctions: 1`。 diff --git a/docs/releases/v0.1.3.md b/docs/releases/v0.1.3.md deleted file mode 100644 index c05d617..0000000 --- a/docs/releases/v0.1.3.md +++ /dev/null @@ -1,10 +0,0 @@ -0.1.3 自 0.1.2 以来的变化: - -- 移除宿主已删除的 `buildSystems.languageImport` 清单字段(新版 Core 严格校验会拒绝它);改为导出插件函数 `languageImport.settings`,由插件后端(`--plugin-backend`,Java)按 `.mvn/maven.config` 的 `-s`、`-gs`、`-o` 向 Java Support 提供 Maven 导入设置。 -- 接手 Java Support 的 Maven 新建项目入口:新增 Maven 项目生成器、Maven Archetype 生成器及项目模板(`projectGenerators`)。 -- 清单新增 `backend: 2`、`pluginFunctions: 1`、`projectGenerators: 1` 要求,权限新增 `backend.launch`、`project.generate`、`workspace.metadata`。 -- 包含 0.1.2 的 litheLogging 1 结构化诊断,以及直接编译 `vendor/` 下官方 Java SDK 源码。 - -兼容性: -- 旧版 Lithe(稳定版 0.6.7)没有 `pluginFunctions 1`,会拒绝安装本版本;Store 条目逐项复制 `requires`,让稳定版继续选择 0.1.1。0.1.1 仍声明 `languageImport`,因此新版 Core 不再接受 0.1.1,需要升级到 0.1.3。 -- 本版本不再声明 `languageImport`。仍读取该字段的旧宿主(例如 0.6.7)在启用 0.1.3 后无法把 Maven 设置带入 Java 导入。 diff --git a/extension/pom.xml b/extension/pom.xml index 99f14ae..8bb240a 100644 --- a/extension/pom.xml +++ b/extension/pom.xml @@ -15,7 +15,7 @@ io.github.lithe-idea lithe-maven-extension - 0.1.3 + 0.0.1 jar Lithe Maven extension diff --git a/extension/src/main/java/io/github/litheidea/maven/DependencyExport.java b/extension/src/main/java/io/github/litheidea/maven/DependencyExport.java index 53929da..4830932 100644 --- a/extension/src/main/java/io/github/litheidea/maven/DependencyExport.java +++ b/extension/src/main/java/io/github/litheidea/maven/DependencyExport.java @@ -63,7 +63,7 @@ Map document(String projectPath) throws MavenExecutionException } Map document = new LinkedHashMap<>(); document.put("format", "litheDependencies"); - document.put("version", 1); + document.put("version", 0); document.put("dependencies", dependencies); return document; } diff --git a/extension/src/main/java/io/github/litheidea/maven/ModelExport.java b/extension/src/main/java/io/github/litheidea/maven/ModelExport.java index dd489ee..5ae690a 100644 --- a/extension/src/main/java/io/github/litheidea/maven/ModelExport.java +++ b/extension/src/main/java/io/github/litheidea/maven/ModelExport.java @@ -84,7 +84,7 @@ Map document() { optionValues.put("profiles", new ArrayList<>(profileIds())); Map document = new LinkedHashMap<>(); document.put("format", "litheBuildModel"); - document.put("version", 1); + document.put("version", 0); document.put("projects", projects); document.put("tasks", tasks); document.put("contentRoots", contentRoots); diff --git a/io.github.lithe-idea.maven-build/plugin.json b/io.github.lithe-idea.maven-build/plugin.json index 204ca1e..39a57f9 100644 --- a/io.github.lithe-idea.maven-build/plugin.json +++ b/io.github.lithe-idea.maven-build/plugin.json @@ -1,36 +1,35 @@ { - "schemaVersion": 2, + "schemaVersion": 0, "id": "io.github.lithe-idea.maven-build", "displayName": "Maven", - "version": "0.1.3", - "pluginAPIVersion": 3, - "requires": { "backend": 2, "buildProviders": 1, "buildSystems": 1, "pluginFunctions": 1, "projectGenerators": 1, "serverProcess": 1 }, - "vendor": { - "id": "io.github.lithe-idea", - "displayName": "Lithe Community", - "signatureRequirement": "none" - }, - "permissions": ["backend.launch", "languageServer.launch", "process.build", "project.generate", "workspace.metadata"], + "version": "0.0.1", + "pluginAPIVersion": 0, + "requires": {"buildSystems": 0, "projectGenerators": 0, "settings": 0}, + "vendor": {"id": "io.github.lithe-idea", "displayName": "Lithe Community", "signatureRequirement": "none"}, + "permissions": ["process.build", "project.generate"], "activationEvents": ["onBuildSystem:maven"], - "languages": [], - "backend": { - "launch": { "kind": "runtime", "tool": "java", "minimumVersion": "8", "entry": "lib/lithe-maven-backend.jar" }, - "arguments": ["--plugin-backend"] - }, - "pluginFunctions": { - "exports": [{ "id": "languageImport.settings", "version": 1, "context": "workspace" }] - }, + "settings": [ + { + "id": "mavenExecutable", + "type": "file", + "title": "Maven executable", + "description": "The mvn program to run. Leave empty to use the project's Maven wrapper (mvnw), then MAVEN_HOME, then mvn on PATH. A path set here is always used, even when the project has a wrapper.", + "default": "", + "placeholder": "Automatic: mvnw, MAVEN_HOME, PATH", + "effect": "reload", + "page": {"buildSystemID": "maven"}, + "section": "Maven" + } + ], "buildSystems": [ { "id": "maven", "displayName": "Maven", - "icon": { "path": "icons/maven.svg" }, - "detection": { - "markers": ["pom.xml"], - "nesting": "outermost" - }, + "icon": {"path": "icons/maven.svg"}, + "detection": {"markers": ["pom.xml"], "nesting": "outermost"}, "invocation": { "executables": [ + {"id": "selected", "kind": "setting", "settingID": "mavenExecutable"}, { "kind": "projectFile", "path": "mvnw", @@ -43,12 +42,16 @@ "requires": [".mvn/wrapper/maven-wrapper.properties"], "platforms": ["windows"] }, - { "kind": "environment", "variable": "MAVEN_HOME", "path": "bin/mvn", "platforms": ["macos", "linux"] }, - { "kind": "environment", "variable": "MAVEN_HOME", "path": "bin/mvn.cmd", "platforms": ["windows"] }, - { "kind": "command", "command": "mvn" } + { + "kind": "environment", + "variable": "MAVEN_HOME", + "path": "bin/mvn", + "platforms": ["macos", "linux"] + }, + {"kind": "environment", "variable": "MAVEN_HOME", "path": "bin/mvn.cmd", "platforms": ["windows"]}, + {"kind": "command", "command": "mvn"} ], "environmentInputs": ["MAVEN_HOME"], - "runtimeDependencies": [{ "id": "java", "minimumVersion": "8" }], "globalArguments": [ "-B", "-ntp", @@ -57,10 +60,16 @@ "${optionArguments:localRepository}", "${optionArguments:offline}" ], - "version": { "arguments": ["--version"], "pattern": "Apache Maven (\\d+\\.\\d+\\.\\d+)" }, + "version": {"arguments": ["--version"], "pattern": "Apache Maven (\\d+\\.\\d+\\.\\d+)"}, "minimumVersion": "3.6.3" }, "options": [ + { + "id": "javaHome", + "displayName": "JDK (JAVA_HOME)", + "kind": "directory", + "environment": {"JAVA_HOME": "${value}"} + }, { "id": "profiles", "displayName": "Profiles", @@ -70,7 +79,12 @@ "presentation": "tree", "arguments": ["-P", "${value}"] }, - { "id": "settingsFile", "displayName": "Settings File", "kind": "file", "arguments": ["-s", "${value}"] }, + { + "id": "settingsFile", + "displayName": "Settings File", + "kind": "file", + "arguments": ["-s", "${value}"] + }, { "id": "localRepository", "displayName": "Local Repository", @@ -82,7 +96,7 @@ "displayName": "Offline", "kind": "boolean", "presentation": "toolbar", - "icon": { "path": "icons/offline.svg" }, + "icon": {"path": "icons/offline.svg"}, "arguments": ["-o"] }, { @@ -90,22 +104,22 @@ "displayName": "Skip Tests", "kind": "boolean", "presentation": "toolbar", - "icon": { "path": "icons/skipTests.svg" }, + "icon": {"path": "icons/skipTests.svg"}, "arguments": ["-DskipTests"] } ], - "provider": { - "launch": { - "kind": "runtime", - "tool": "java", - "minimumVersion": "8", - "entry": "lib/lithe-maven-backend.jar" - }, - "arguments": ["--state", "${workspaceStateDir}"], + "model": { + "source": "command", + "arguments": [ + "-Dmaven.ext.class.path=${pluginDir}/lib/lithe-maven-extension.jar", + "-Dlithe.modelOutput=${outputFile}", + "pre-clean" + ], + "output": "outputFile", + "decoder": "litheBuildModel", "executesProjectCode": true, "mayUseNetwork": true }, - "model": { "source": "provider" }, "tasks": [ { "id": "clean", @@ -114,8 +128,8 @@ "category": ["Lifecycle"], "scopes": ["workspace", "project"], "arguments": [ - { "value": "-pl", "when": "nestedProjectSelected" }, - { "value": "${project.path}", "when": "nestedProjectSelected" }, + {"value": "-pl", "when": "nestedProjectSelected"}, + {"value": "${project.path}", "when": "nestedProjectSelected"}, "clean" ] }, @@ -126,8 +140,8 @@ "category": ["Lifecycle"], "scopes": ["workspace", "project"], "arguments": [ - { "value": "-pl", "when": "nestedProjectSelected" }, - { "value": "${project.path}", "when": "nestedProjectSelected" }, + {"value": "-pl", "when": "nestedProjectSelected"}, + {"value": "${project.path}", "when": "nestedProjectSelected"}, "validate" ] }, @@ -138,8 +152,8 @@ "category": ["Lifecycle"], "scopes": ["workspace", "project"], "arguments": [ - { "value": "-pl", "when": "nestedProjectSelected" }, - { "value": "${project.path}", "when": "nestedProjectSelected" }, + {"value": "-pl", "when": "nestedProjectSelected"}, + {"value": "${project.path}", "when": "nestedProjectSelected"}, "compile" ] }, @@ -150,8 +164,8 @@ "category": ["Lifecycle"], "scopes": ["workspace", "project"], "arguments": [ - { "value": "-pl", "when": "nestedProjectSelected" }, - { "value": "${project.path}", "when": "nestedProjectSelected" }, + {"value": "-pl", "when": "nestedProjectSelected"}, + {"value": "${project.path}", "when": "nestedProjectSelected"}, "${optionArguments:skipTests}", "test" ] @@ -163,8 +177,8 @@ "category": ["Lifecycle"], "scopes": ["workspace", "project"], "arguments": [ - { "value": "-pl", "when": "nestedProjectSelected" }, - { "value": "${project.path}", "when": "nestedProjectSelected" }, + {"value": "-pl", "when": "nestedProjectSelected"}, + {"value": "${project.path}", "when": "nestedProjectSelected"}, "${optionArguments:skipTests}", "package" ] @@ -176,8 +190,8 @@ "category": ["Lifecycle"], "scopes": ["workspace", "project"], "arguments": [ - { "value": "-pl", "when": "nestedProjectSelected" }, - { "value": "${project.path}", "when": "nestedProjectSelected" }, + {"value": "-pl", "when": "nestedProjectSelected"}, + {"value": "${project.path}", "when": "nestedProjectSelected"}, "${optionArguments:skipTests}", "verify" ] @@ -189,8 +203,8 @@ "category": ["Lifecycle"], "scopes": ["workspace", "project"], "arguments": [ - { "value": "-pl", "when": "nestedProjectSelected" }, - { "value": "${project.path}", "when": "nestedProjectSelected" }, + {"value": "-pl", "when": "nestedProjectSelected"}, + {"value": "${project.path}", "when": "nestedProjectSelected"}, "${optionArguments:skipTests}", "install" ] @@ -202,8 +216,8 @@ "category": ["Lifecycle"], "scopes": ["workspace", "project"], "arguments": [ - { "value": "-pl", "when": "nestedProjectSelected" }, - { "value": "${project.path}", "when": "nestedProjectSelected" }, + {"value": "-pl", "when": "nestedProjectSelected"}, + {"value": "${project.path}", "when": "nestedProjectSelected"}, "site" ] }, @@ -214,8 +228,8 @@ "category": ["Lifecycle"], "scopes": ["workspace", "project"], "arguments": [ - { "value": "-pl", "when": "nestedProjectSelected" }, - { "value": "${project.path}", "when": "nestedProjectSelected" }, + {"value": "-pl", "when": "nestedProjectSelected"}, + {"value": "${project.path}", "when": "nestedProjectSelected"}, "${optionArguments:skipTests}", "deploy" ] @@ -227,8 +241,8 @@ "category": ["Plugins"], "fromModel": true, "arguments": [ - { "value": "-pl", "when": "nestedProjectSelected" }, - { "value": "${project.path}", "when": "nestedProjectSelected" }, + {"value": "-pl", "when": "nestedProjectSelected"}, + {"value": "${project.path}", "when": "nestedProjectSelected"}, "${optionArguments:skipTests}", "${task.property:goal}" ] @@ -240,8 +254,8 @@ "scopes": ["workspace", "project"], "requiresUserArguments": true, "arguments": [ - { "value": "-pl", "when": "nestedProjectSelected" }, - { "value": "${project.path}", "when": "nestedProjectSelected" }, + {"value": "-pl", "when": "nestedProjectSelected"}, + {"value": "${project.path}", "when": "nestedProjectSelected"}, "${optionArguments:skipTests}", "${userArguments}" ] @@ -251,12 +265,15 @@ "scopes": ["workspace", "project"], "filters": ["suite", "case"], "arguments": [ - { "value": "-pl", "when": "nestedProjectSelected" }, - { "value": "${project.path}", "when": "nestedProjectSelected" }, - { "value": "-am", "when": ["nestedProjectSelected", "suiteSelected"] }, - { "value": "-Dtest=${test.suite}", "when": ["suiteSelected", "noCaseSelected"] }, - { "value": "-Dtest=${test.suite}#${test.case}", "when": ["suiteSelected", "caseSelected"] }, - { "value": "-Dsurefire.failIfNoSpecifiedTests=false", "when": "suiteSelected" }, + {"value": "-pl", "when": "nestedProjectSelected"}, + {"value": "${project.path}", "when": "nestedProjectSelected"}, + { + "value": "-am", + "when": ["nestedProjectSelected", "suiteSelected"] + }, + {"value": "-Dtest=${test.suite}", "when": ["suiteSelected", "noCaseSelected"]}, + {"value": "-Dtest=${test.suite}#${test.case}", "when": ["suiteSelected", "caseSelected"]}, + {"value": "-Dsurefire.failIfNoSpecifiedTests=false", "when": "suiteSelected"}, "test" ], "results": { @@ -274,7 +291,7 @@ "column": 4, "message": 5, "severity": 1, - "severities": { "ERROR": "error", "WARNING": "warning" } + "severities": {"ERROR": "error", "WARNING": "warning"} }, { "regex": "^\\[(ERROR|WARNING)\\] file://(.+?\\.kts?):(\\d+):(\\d+) (.+)$", @@ -283,13 +300,28 @@ "column": 4, "message": 5, "severity": 1, - "severities": { "ERROR": "error", "WARNING": "warning" } + "severities": {"ERROR": "error", "WARNING": "warning"} } ] }, - "dependencies": { "source": "provider", "scopes": ["workspace", "project"] }, - "sync": { "watch": [".mvn/extensions.xml", ".mvn/maven.config", "pom.xml"] }, - "layout": { "excluded": ["target"] } + "dependencies": { + "source": "command", + "scopes": ["workspace", "project"], + "arguments": [ + "-Dmaven.ext.class.path=${pluginDir}/lib/lithe-maven-extension.jar", + "-Dlithe.dependenciesOutput=${outputFile}", + {"value": "-Dlithe.dependenciesProject=./${project.path}", "when": "projectSelected"}, + "pre-clean" + ], + "output": "outputFile", + "decoder": "litheDependencies", + "executesProjectCode": true, + "mayUseNetwork": true + }, + "sync": { + "watch": [".mvn/extensions.xml", ".mvn/maven.config", "pom.xml"] + }, + "layout": {"excluded": ["target"]} } ], "projectGenerators": [ @@ -299,21 +331,24 @@ "description": "A Java project built with Maven.", "section": "project", "order": 20, - "icon": { "path": "icons/maven-project.svg", "darkPath": "icons/maven-project_dark.svg", "mode": "original" }, + "icon": {"path": "icons/maven-project.svg", "darkPath": "icons/maven-project_dark.svg", "mode": "original"}, "fields": [ { - "id": "jdk", - "type": "runtime", - "title": "JDK", - "runtime": "java", - "minimumVersion": "11" - }, - { - "id": "addSampleCode", - "type": "boolean", - "title": "Add sample code", - "default": true + "id": "javaRelease", + "type": "enum", + "title": "Java release", + "description": "The Java release the project compiles for (maven.compiler.release). The JDK that runs Maven must support it.", + "presentation": "menu", + "default": "17", + "options": [ + {"value": "8", "title": "8"}, + {"value": "11", "title": "11"}, + {"value": "17", "title": "17"}, + {"value": "21", "title": "21"}, + {"value": "25", "title": "25"} + ] }, + {"id": "addSampleCode", "type": "boolean", "title": "Add sample code", "default": true}, { "id": "groupId", "type": "text", @@ -335,33 +370,30 @@ "maxLength": 200 } ], - "requirements": [ - { "languageID": "java" }, - { "buildSystemID": "maven" } - ], + "requirements": [{"languageID": "java"}, {"buildSystemID": "maven"}], "steps": [ - { "kind": "files", "source": "templates/java/maven" }, + {"kind": "files", "source": "templates/java/maven"}, { "kind": "files", "source": "templates/java/standard-sample", - "when": { "field": "addSampleCode", "equals": true } + "when": {"field": "addSampleCode", "equals": true} }, { "kind": "files", "source": "templates/java/standard-sample-main", "target": "src/main/java/${field.groupId|package|path}", - "when": { "field": "addSampleCode", "equals": true } + "when": {"field": "addSampleCode", "equals": true} }, { "kind": "files", "source": "templates/java/standard-empty", - "when": { "field": "addSampleCode", "equals": false } + "when": {"field": "addSampleCode", "equals": false} } ], "openFiles": [ { "path": "src/main/java/${field.groupId|package|path}/Main.java", - "when": { "field": "addSampleCode", "equals": true } + "when": {"field": "addSampleCode", "equals": true} } ] }, @@ -371,16 +403,8 @@ "description": "A project generated by Maven from an archetype.", "section": "generator", "order": 10, - "icon": { "path": "icons/maven-project.svg", "darkPath": "icons/maven-project_dark.svg", "mode": "original" }, + "icon": {"path": "icons/maven-project.svg", "darkPath": "icons/maven-project_dark.svg", "mode": "original"}, "fields": [ - { - "id": "jdk", - "type": "runtime", - "title": "JDK", - "description": "Maven runs with this JDK, and the new project uses it.", - "runtime": "java", - "minimumVersion": "11" - }, { "id": "archetype", "type": "enum", @@ -388,14 +412,14 @@ "presentation": "menu", "default": "maven-archetype-quickstart", "options": [ - { "value": "maven-archetype-quickstart", "title": "maven-archetype-quickstart" }, - { "value": "maven-archetype-webapp", "title": "maven-archetype-webapp" }, - { "value": "maven-archetype-simple", "title": "maven-archetype-simple" }, - { "value": "maven-archetype-j2ee-simple", "title": "maven-archetype-j2ee-simple" }, - { "value": "maven-archetype-plugin", "title": "maven-archetype-plugin" }, - { "value": "maven-archetype-archetype", "title": "maven-archetype-archetype" }, - { "value": "maven-archetype-site-simple", "title": "maven-archetype-site-simple" }, - { "value": "custom", "title": "Custom archetype…" } + {"value": "maven-archetype-quickstart", "title": "maven-archetype-quickstart"}, + {"value": "maven-archetype-webapp", "title": "maven-archetype-webapp"}, + {"value": "maven-archetype-simple", "title": "maven-archetype-simple"}, + {"value": "maven-archetype-j2ee-simple", "title": "maven-archetype-j2ee-simple"}, + {"value": "maven-archetype-plugin", "title": "maven-archetype-plugin"}, + {"value": "maven-archetype-archetype", "title": "maven-archetype-archetype"}, + {"value": "maven-archetype-site-simple", "title": "maven-archetype-site-simple"}, + {"value": "custom", "title": "Custom archetype…"} ] }, { @@ -405,7 +429,7 @@ "pattern": "[A-Za-z_][A-Za-z0-9_]*(\\.[A-Za-z_][A-Za-z0-9_-]*)*", "maxLength": 200, "placeholder": "org.example.archetypes", - "visibleWhen": { "field": "archetype", "equals": "custom" } + "visibleWhen": {"field": "archetype", "equals": "custom"} }, { "id": "archetypeArtifactId", @@ -414,7 +438,7 @@ "pattern": "[A-Za-z0-9_][A-Za-z0-9_.-]*", "maxLength": 200, "placeholder": "my-archetype", - "visibleWhen": { "field": "archetype", "equals": "custom" } + "visibleWhen": {"field": "archetype", "equals": "custom"} }, { "id": "archetypeVersion", @@ -463,10 +487,7 @@ "maxLength": 200 } ], - "requirements": [ - { "languageID": "java" }, - { "buildSystemID": "maven" } - ], + "requirements": [{"languageID": "java"}, {"buildSystemID": "maven"}], "steps": [ { "kind": "command", @@ -475,17 +496,31 @@ "-B", "org.apache.maven.plugins:maven-archetype-plugin:3.3.1:generate", "-DinteractiveMode=false", - { "value": "-DarchetypeGroupId=org.apache.maven.archetypes", "when": { "field": "archetype", "notEquals": "custom" } }, - { "value": "-DarchetypeArtifactId=${field.archetype}", "when": { "field": "archetype", "notEquals": "custom" } }, - { "value": "-DarchetypeGroupId=${field.archetypeGroupId}", "when": { "field": "archetype", "equals": "custom" } }, - { "value": "-DarchetypeArtifactId=${field.archetypeArtifactId}", "when": { "field": "archetype", "equals": "custom" } }, - { "value": "-DarchetypeVersion=${field.archetypeVersion}", "when": { "field": "archetypeVersion", "notEquals": "" } }, + { + "value": "-DarchetypeGroupId=org.apache.maven.archetypes", + "when": {"field": "archetype", "notEquals": "custom"} + }, + { + "value": "-DarchetypeArtifactId=${field.archetype}", + "when": {"field": "archetype", "notEquals": "custom"} + }, + { + "value": "-DarchetypeGroupId=${field.archetypeGroupId}", + "when": {"field": "archetype", "equals": "custom"} + }, + { + "value": "-DarchetypeArtifactId=${field.archetypeArtifactId}", + "when": {"field": "archetype", "equals": "custom"} + }, + { + "value": "-DarchetypeVersion=${field.archetypeVersion}", + "when": {"field": "archetypeVersion", "notEquals": ""} + }, "-DgroupId=${field.groupId}", "-DartifactId=${field.artifactId}", "-Dversion=${field.version}", "-Dpackage=${field.packageName}" ], - "environment": { "JAVA_HOME": "${field.jdk}" }, "collect": "${field.artifactId}", "mayUseNetwork": true, "timeoutSeconds": 900 diff --git a/io.github.lithe-idea.maven-build/templates/java/maven/pom.xml b/io.github.lithe-idea.maven-build/templates/java/maven/pom.xml index 3fa0e0e..e22d102 100644 --- a/io.github.lithe-idea.maven-build/templates/java/maven/pom.xml +++ b/io.github.lithe-idea.maven-build/templates/java/maven/pom.xml @@ -9,7 +9,7 @@ 1.0-SNAPSHOT - {{ field.jdk.major }} + {{ field.javaRelease }} UTF-8 diff --git a/scripts/backend-client.mjs b/scripts/backend-client.mjs deleted file mode 100644 index 1cf5288..0000000 --- a/scripts/backend-client.mjs +++ /dev/null @@ -1,153 +0,0 @@ -// Talks to lib/lithe-maven-backend.jar the way Lithe does: LSP base-protocol -// frames over the process's stdio, `initialize` offering litheBuild 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 { spawn } from "node:child_process"; -import { pathToFileURL } from "node:url"; - -export const WAIT_MS = 20_000; - -export class BackendClient { - #buffer = Buffer.alloc(0); - #pending = new Map(); - #nextId = 1; - stderr = ""; - diagnostics = []; - - /** Starts `java -jar --state ` (or `args`); `javaOptions` go before `-jar`. */ - constructor({ java = "java", jar, state, env = process.env, javaOptions = [], timeoutMs = WAIT_MS, args, hostRequests = {} }) { - this.timeoutMs = timeoutMs; - // Answers to requests the backend sends to the host, keyed by method. - this.hostRequests = hostRequests; - this.child = spawn(java, [...javaOptions, "-jar", jar, ...(args ?? ["--state", state])], { - env, stdio: ["pipe", "pipe", "pipe"], detached: true, - }); - this.exited = new Promise((resolve) => this.child.once("exit", (code, signal) => { - this.#fail(`the backend exited with ${signal ?? `status ${code}`}`); - resolve(signal ?? code); - })); - this.child.once("error", (error) => this.#fail(`cannot start the backend: ${error.message}`)); - this.child.stdout.on("data", (chunk) => this.#read(chunk)); - this.child.stderr.on("data", (chunk) => { this.stderr += chunk; }); - this.child.stdin.on("error", () => {}); - } - - /** Sends a request; `response` settles with the whole response message. */ - send(method, params) { - const id = this.#nextId++; - const response = new Promise((resolve, reject) => { - const timer = setTimeout(() => { - this.#pending.delete(id); - reject(new Error(`no response to ${method} #${id} within ${this.timeoutMs} ms\nbackend stderr:\n${this.stderr}`)); - }, this.timeoutMs); - this.#pending.set(id, (message) => { - clearTimeout(timer); - if (message instanceof Error) reject(message); - else resolve(message); - }); - }); - this.#write({ jsonrpc: "2.0", id, method, params }); - return { id, response }; - } - - /** Sends a request and resolves with its result, or rejects with its error. */ - async request(method, params) { - const message = await this.send(method, params).response; - if (message.error) { - const error = new Error(`${method} failed: ${message.error.message}`); - error.response = message.error; - throw error; - } - return message.result; - } - - notify(method, params) { - this.#write({ jsonrpc: "2.0", method, params }); - } - - cancel(id) { - this.notify("$/cancelRequest", { id }); - } - - async initialize(root, { functions = false } = {}) { - const result = await this.request("initialize", { - processId: process.pid, - rootUri: pathToFileURL(root).href, - capabilities: { experimental: { - ...(functions ? { litheFunctions: { versions: [1, 2, 3] } } : { litheBuild: { versions: [1] } }), - litheLogging: { versions: [1] }, - } }, - }); - this.notify("initialized", {}); - return result; - } - - /** `shutdown` and `exit`; resolves with the exit code. */ - async close() { - if (this.child.exitCode === null && this.child.signalCode === null) { - await this.request("shutdown", null); - this.notify("exit", null); - this.child.stdin.end(); - } - return bounded(this.exited, "the backend to exit"); - } - - /** Ends the backend's whole process group, for teardown after a failure. */ - kill() { - if (!this.child.pid) return; - // macOS answers EPERM for a group whose members already exited but are not reaped yet. - try { process.kill(-this.child.pid, "SIGKILL"); } - catch (error) { if (error.code !== "ESRCH" && error.code !== "EPERM") throw error; } - } - - #write(message) { - const body = Buffer.from(JSON.stringify(message), "utf8"); - this.child.stdin.write(Buffer.concat([Buffer.from(`Content-Length: ${body.length}\r\n\r\n`, "ascii"), body])); - } - - /** Rejects every waiting request; nothing more will answer them. */ - #fail(reason) { - const error = new Error(`${reason}\nbackend stderr:\n${this.stderr}`); - for (const settle of this.#pending.values()) settle(error); - this.#pending.clear(); - } - - #read(chunk) { - this.#buffer = Buffer.concat([this.#buffer, chunk]); - for (;;) { - const headerEnd = this.#buffer.indexOf("\r\n\r\n"); - if (headerEnd < 0) return; - const length = Number(/Content-Length: *(\d+)/i.exec(this.#buffer.subarray(0, headerEnd).toString("ascii"))?.[1]); - if (!Number.isSafeInteger(length)) return this.#broken("a frame without Content-Length"); - if (this.#buffer.length < headerEnd + 4 + length) return; - let message; - try { message = JSON.parse(this.#buffer.subarray(headerEnd + 4, headerEnd + 4 + length).toString("utf8")); } - catch { return this.#broken("a frame that is not JSON"); } - this.#buffer = this.#buffer.subarray(headerEnd + 4 + length); - if (message.method === "lithe/log") { - this.diagnostics.push(message.params); - } else if (message.id !== undefined && message.method !== undefined) { - const answer = this.hostRequests[message.method]; - this.#write(answer === undefined - ? { jsonrpc: "2.0", id: message.id, error: { code: -32601, message: "unsupported" } } - : { jsonrpc: "2.0", id: message.id, result: answer(message.params) }); - } else if (message.id !== undefined && message.method === undefined) { - this.#pending.get(message.id)?.(message); - this.#pending.delete(message.id); - } - } - } - - #broken(what) { - this.#fail(`the backend wrote ${what}`); - this.kill(); - } -} - -export function bounded(promise, description, timeoutMs = WAIT_MS) { - let timer; - return Promise.race([ - promise, - new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`timed out waiting for ${description}`)), timeoutMs); }), - ]).finally(() => clearTimeout(timer)); -} diff --git a/scripts/package.mjs b/scripts/package.mjs index dcb4e7b..0997077 100644 --- a/scripts/package.mjs +++ b/scripts/package.mjs @@ -2,22 +2,18 @@ // Packages the plugin into dist/--darwin.zip, the asset name // Lithe Store's release tracker recognizes (docs/publishing.md there). // -// The package is plain data plus two jars, built here with Maven and copied -// to lib/: the Maven core extension in extension/, which runs inside the -// user's own Maven, and the build provider in backend/, which Lithe starts -// with Java 8 or newer. Neither carries native code, so one archive serves -// every Mac. The unpacked package stays in dist/package/ for installing a -// local development copy into Lithe. -// -// The backend compiles the official SDK sources pinned by sdk.lock.json into -// the same JAR. Every input is verified before Maven runs; build outputs and -// plugin runtime state never become part of the source lock. +// The package is plain data plus one jar, built here with Maven and copied to +// lib/: the Maven core extension in extension/. Lithe never starts it; the +// model and dependency commands in plugin.json load it into the user's own +// Maven with -Dmaven.ext.class.path, and it writes the canonical documents +// Lithe decodes. It carries no native code, so one archive serves every Mac. +// The unpacked package stays in dist/package/ for installing a local +// development copy into Lithe. // // Usage: node scripts/package.mjs [--expect-tag ] import { mavenTimeout, runCommand, withInterrupts, ZIP_TIMEOUT_MS } from "./process.mjs"; import { createReport } from "./report.mjs"; -import { verifySdk } from "./sdk/verify-sdk.mjs"; import { createHash } from "node:crypto"; import { cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs"; import { isAbsolute, join, resolve } from "node:path"; @@ -26,7 +22,6 @@ const PACKAGE_DIR = "io.github.lithe-idea.maven-build"; const ASSET_PREFIX = "maven-build"; const PLATFORM = "darwin"; const EXTENSION_JAR = "extension/target/lithe-maven-extension.jar"; -const BACKEND_JAR = "backend/target/lithe-maven-backend.jar"; const PACKAGE_ROOT = join("dist", "package"); const manifest = JSON.parse(readFileSync(`${PACKAGE_DIR}/plugin.json`, "utf8")); @@ -34,8 +29,6 @@ const extensionPom = readFileSync("extension/pom.xml", "utf8"); const pomVersion = (pom, artifact) => new RegExp(`${artifact}\\s*(?:\\s*)?([^<]+)`, "s") .exec(pom)?.[1]; const extensionVersion = pomVersion(extensionPom, "lithe-maven-extension"); -const backendPom = readFileSync("backend/pom.xml", "utf8"); -const backendVersion = pomVersion(backendPom, "lithe-maven-backend"); const problems = []; if (manifest.id !== PACKAGE_DIR) problems.push(`plugin.json id ${manifest.id} must equal the directory ${PACKAGE_DIR}`); if (!/^[0-9]+\.[0-9]+\.[0-9]+$/.test(manifest.version)) problems.push(`version ${manifest.version} is not MAJOR.MINOR.PATCH`); @@ -44,9 +37,6 @@ if (manifest.id === "dev.lithe" || manifest.id.startsWith("dev.lithe.")) problem if (extensionVersion !== manifest.version) { problems.push(`extension/pom.xml version ${extensionVersion} must equal plugin.json version ${manifest.version}`); } -if (backendVersion !== manifest.version) { - problems.push(`backend/pom.xml version ${backendVersion} must equal plugin.json version ${manifest.version}`); -} const tagFlag = process.argv.indexOf("--expect-tag"); if (tagFlag >= 0) { @@ -92,19 +82,11 @@ const report = createReport("package"); const timeoutMs = mavenTimeout(); await withInterrupts(async (signal) => { try { - await report.step("verify the vendored plugin SDK", verifySdk); await report.step("build the Maven extension", async () => { await runCommand(process.env.MVN ?? "mvn", ["-B", "-ntp", "-q", "-f", "extension/pom.xml", "clean", "package"], { timeoutMs, signal }); if (!existsSync(EXTENSION_JAR)) throw new Error(`${EXTENSION_JAR} was not built`); }); - await report.step("build the Maven backend", async () => { - await runCommand(process.env.MVN ?? "mvn", [ - "-B", "-ntp", "-q", "-f", "backend/pom.xml", "clean", "package", - ], { timeoutMs, signal }); - if (!existsSync(BACKEND_JAR)) throw new Error(`${BACKEND_JAR} was not built`); - }); - await report.step("assemble the plugin package", () => { signal.throwIfAborted(); rmSync("dist", { recursive: true, force: true }); @@ -112,10 +94,8 @@ await withInterrupts(async (signal) => { cpSync(PACKAGE_DIR, packageRoot, { recursive: true }); mkdirSync(join(packageRoot, "lib"), { recursive: true }); cpSync(EXTENSION_JAR, join(packageRoot, "lib", "lithe-maven-extension.jar")); - cpSync(BACKEND_JAR, join(packageRoot, "lib", "lithe-maven-backend.jar")); cpSync("LICENSE", join(packageRoot, "LICENSE")); cpSync("NOTICE", join(packageRoot, "NOTICE")); - cpSync("vendor/LICENSE", join(packageRoot, "SDK-LICENSE")); assertNoLinks(packageRoot); }); diff --git a/scripts/sdk/verify-sdk.mjs b/scripts/sdk/verify-sdk.mjs deleted file mode 100644 index b352bb4..0000000 --- a/scripts/sdk/verify-sdk.mjs +++ /dev/null @@ -1,42 +0,0 @@ -import { createHash } from 'node:crypto'; -import { lstat, readFile, readdir } from 'node:fs/promises'; -import { dirname, join, resolve } from 'node:path'; -import { fileURLToPath, pathToFileURL } from 'node:url'; - -const repository = resolve(dirname(fileURLToPath(import.meta.url)), '../..'); - -/** Verify every vendored production source before building the backend. */ -export async function verifySdk(root = repository) { - const lock = JSON.parse(await readFile(join(root, 'sdk.lock.json'), 'utf8')); - if (lock.schemaVersion !== 1 || !/^[0-9a-f]{40}$/.test(lock.source?.revision) || !Array.isArray(lock.files) || lock.source.repository !== 'https://github.com/Lithe-IDEA/lithe-plugin-docs') { - throw new Error('The SDK lock must identify its upstream base and every source hash.'); - } - const expected = new Set(); - for (const entry of lock.files) { - if (!entry.path?.startsWith('vendor/') || entry.path.includes('\\') - || entry.path.split('/').some((part) => !part || part === '.' || part === '..') - || !/^[0-9a-f]{64}$/.test(entry.sha256) || expected.has(entry.path) - || (entry.localChanges === true && (!Object.hasOwn(entry, 'upstreamSha256') || (entry.upstreamSha256 !== null && !/^[0-9a-f]{64}$/.test(entry.upstreamSha256))))) { - throw new Error('Invalid or duplicate SDK source lock entry.'); - } - const file = join(root, entry.path); - if (!(await lstat(file)).isFile()) throw new Error(`SDK input is not a regular file: ${entry.path}`); - const digest = createHash('sha256').update(await readFile(file)).digest('hex'); - if (digest !== entry.sha256) throw new Error(`SDK SHA-256 mismatch: ${entry.path}`); - expected.add(entry.path); - } - async function walk(directory, prefix) { - for (const entry of await readdir(directory, { withFileTypes: true })) { - const name = `${prefix}/${entry.name}`; - if (entry.isDirectory()) await walk(join(directory, entry.name), name); - else if (!expected.delete(name)) throw new Error(`Unpinned SDK input: ${name}`); - } - } - await walk(join(root, 'vendor'), 'vendor'); - if (expected.size) throw new Error('A pinned SDK source is missing.'); -} - -if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { - await verifySdk(); - console.log('Vendored Java SDK source hashes verified.'); -} diff --git a/scripts/test-backend.mjs b/scripts/test-backend.mjs deleted file mode 100644 index d6b669c..0000000 --- a/scripts/test-backend.mjs +++ /dev/null @@ -1,353 +0,0 @@ -#!/usr/bin/env node -// Drives lib/lithe-maven-backend.jar from dist/package over its stdio, as -// Lithe does, with test/fixtures/fake-maven-backend.mjs as Maven. The fake -// logs every run, so the checks count Maven runs exactly: the snapshot -// survives a restart, POM edits and refresh invalidate it, concurrent -// requests share one run, an edit during a run is not saved, and cancelling -// ends Maven and its process tree. No Maven or network is needed. -// -// Run scripts/package.mjs first. LITHE_TEST_JAVA selects the Java that runs -// the backend (default `java`), so CI also checks Java 8. -// -// Usage: node scripts/test-backend.mjs - -import assert from "node:assert/strict"; -import { spawnSync } from "node:child_process"; -import { appendFileSync, chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join, resolve } from "node:path"; -import { BackendClient, bounded } from "./backend-client.mjs"; -import { withInterrupts } from "./process.mjs"; -import { createReport } from "./report.mjs"; - -const PACKAGE_DIR = "io.github.lithe-idea.maven-build"; -const jar = resolve("dist", "package", PACKAGE_DIR, "lib", "lithe-maven-backend.jar"); -if (!existsSync(jar)) { - console.error("✗ dist/package is missing the backend; run node scripts/package.mjs first"); - process.exit(1); -} -const java = process.env.LITHE_TEST_JAVA ?? "java"; -// `java -version` prints to stderr; Java 8 and older report 1.. -const [, first, second] = /version "(\d+)(?:\.(\d+))?/.exec(spawnSync(java, ["-version"], { encoding: "utf8" }).stderr) ?? []; -const javaMajor = Number(first) === 1 ? Number(second) : Number(first); -console.log(`backend runtime: ${java} (Java ${javaMajor})`); - -// Real paths: on macOS the temporary directory is reached through a link. -const scratch = realpathSync(mkdtempSync(join(tmpdir(), "lithe-maven-backend-test-"))); -const root = join(scratch, "reactor"); -const state = join(scratch, "state"); -const snapshotFile = join(state, "maven-snapshot.json"); -const controlFile = join(scratch, "control.json"); -const runLog = join(scratch, "runs.log"); -const fakeMaven = join(scratch, "bin", "mvn"); -const report = createReport("backend"); -const clients = new Set(); -let failed = false; - -const runs = () => existsSync(runLog) ? readFileSync(runLog, "utf8").trim().split("\n").map((line) => JSON.parse(line)) : []; -const pids = (file) => existsSync(file) ? readFileSync(file, "utf8").trim().split("\n").filter(Boolean).map(Number) : []; -const alive = (pid) => { - try { process.kill(pid, 0); return true; } - catch (error) { if (error.code === "ESRCH") return false; throw error; } -}; -const control = (value) => writeFileSync(controlFile, JSON.stringify(value)); -const sleep = (ms) => new Promise((done) => setTimeout(done, ms)); -async function until(condition, description, timeoutMs = 10_000) { - const deadline = Date.now() + timeoutMs; - while (!condition()) { - if (Date.now() > deadline) throw new Error(`timed out waiting for ${description}`); - await sleep(20); - } -} -const touch = (relative, text) => appendFileSync(join(root, relative), `\n\n`); -const params = (extra = {}) => ({ - buildSystemID: "maven", root: ".", options: {}, optionArguments: [], environment: {}, - tool: { executable: fakeMaven }, ...extra, -}); - -async function start() { - const client = new BackendClient({ - java, jar, state, - // A private home keeps the developer's ~/.m2/settings.xml out of the fingerprint. - javaOptions: [`-Duser.home=${join(scratch, "home")}`], - env: { ...process.env, FAKE_MAVEN_CONTROL: controlFile, FAKE_MAVEN_LOG: runLog }, - }); - clients.add(client); - const initialized = await client.initialize(root); - assert.deepEqual(initialized.capabilities.experimental.litheBuild, { version: 1 }); - return client; -} -async function stop(client) { - assert.equal(await client.close(), 0, `the backend exits cleanly\n${client.stderr}`); - clients.delete(client); -} -const check = async (name, body) => { - try { await report.step(name, body); } - catch (error) { failed = true; console.error(error.stack); } -}; - -async function test() { - try { - cpSync(resolve("test", "fixtures", "reactor"), root, { recursive: true }); - mkdirSync(join(scratch, "bin")); - mkdirSync(join(scratch, "home")); - const fixture = resolve("test", "fixtures", "fake-maven-backend.mjs"); - const wrapper = `#!/bin/sh\nFAKE_MAVEN_SELF="$0" exec ${JSON.stringify(process.execPath)} ${JSON.stringify(fixture)} "$@"\n`; - writeFileSync(fakeMaven, wrapper); - chmodSync(fakeMaven, 0o755); - control({}); - - let client = await start(); - - await check("the first request runs Maven once for the model and every module's dependencies", async () => { - const model = await client.request("lithe/build/model", params()); - assert.equal(model.format, "litheBuildModel"); - assert.deepEqual(model.projects.map((project) => project.name), ["reactor", "core", "app"]); - assert.equal(runs().length, 1); - const [run] = runs(); - assert.equal(run.cwd, root); - assert.ok(run.argv.includes("pre-clean") && run.argv.includes("-B") && run.argv.includes("-ntp")); - assert.ok(run.argv.some((arg) => arg.startsWith("-Dmaven.ext.class.path=") && arg.endsWith("lithe-maven-extension.jar"))); - - const app = await client.request("lithe/build/dependencies", params({ project: { name: "app", path: "app" } })); - assert.equal(app.format, "litheDependencies"); - assert.deepEqual(app.dependencies.map((node) => [node.group, node.name, node.scope]), [["demo", "core", "compile"]]); - const workspace = await client.request("lithe/build/dependencies", params({ project: null })); - assert.deepEqual(workspace.dependencies.map((node) => node.name), ["reactor", "core", "app"]); - const reactor = await client.request("lithe/build/dependencies", params({ project: { name: "reactor", path: "." } })); - assert.deepEqual(reactor.dependencies, []); - assert.equal(runs().length, 1, "dependencies come from the same run"); - - const snapshot = JSON.parse(readFileSync(snapshotFile, "utf8")).value; - assert.equal(snapshot.snapshotVersion, 1); - assert.deepEqual(Object.keys(snapshot.roots), [root]); - }); - - await check("an unknown project is an error, not an empty tree", async () => { - const { response } = client.send("lithe/build/dependencies", params({ project: { name: "nope", path: "nope" } })); - const message = await response; - assert.equal(message.error?.data?.code, "maven.unknownProject"); - }); - - await check("a restarted backend answers from the snapshot without running Maven", async () => { - await stop(client); - client = await start(); - const model = await client.request("lithe/build/model", params()); - assert.equal(model.fakeRun, 1); - const app = await client.request("lithe/build/dependencies", params({ project: { name: "app", path: "app" } })); - assert.equal(app.dependencies[0].name, "core"); - assert.equal(runs().length, 1); - }); - - await check("editing a module's POM invalidates the snapshot", async () => { - touch("app/pom.xml", "edited"); - assert.equal((await client.request("lithe/build/model", params())).fakeRun, 2); - assert.equal((await client.request("lithe/build/model", params())).fakeRun, 2); - assert.equal(runs().length, 2); - }); - - await check("refresh runs Maven even when the snapshot is current", async () => { - assert.equal((await client.request("lithe/build/model", params({ refresh: true }))).fakeRun, 3); - assert.equal((await client.request("lithe/build/model", params())).fakeRun, 3); - assert.equal(runs().length, 3); - }); - - await check("changed options and .mvn/maven.config invalidate the snapshot", async () => { - assert.equal((await client.request("lithe/build/model", params({ optionArguments: ["-o"] }))).fakeRun, 4); - assert.ok(runs().at(-1).argv.includes("-o"), "option arguments reach Maven"); - mkdirSync(join(root, ".mvn")); - writeFileSync(join(root, ".mvn", "maven.config"), "-Pci\n"); - assert.equal((await client.request("lithe/build/model", params({ optionArguments: ["-o"] }))).fakeRun, 5); - assert.equal((await client.request("lithe/build/model", params({ optionArguments: ["-o"] }))).fakeRun, 5); - }); - - await check("concurrent requests share one Maven run", async () => { - touch("core/pom.xml", "concurrent"); - const gate = join(scratch, "gate-concurrent"); - control({ gate }); - const before = runs().length; - const model = client.send("lithe/build/model", params()); - const app = client.send("lithe/build/dependencies", params({ project: { name: "app", path: "app" } })); - await until(() => existsSync(`${gate}.started`), "Maven to start"); - await sleep(300); - writeFileSync(gate, ""); - const [modelResponse, appResponse] = await Promise.all([model.response, app.response]); - assert.ok(modelResponse.result && appResponse.result, JSON.stringify([modelResponse, appResponse])); - assert.equal(runs().length, before + 1); - control({}); - }); - - await check("a POM edited while Maven runs is answered but not saved", async () => { - const gate = join(scratch, "gate-edit"); - control({ gate }); - const saved = readFileSync(snapshotFile, "utf8"); - const pending = client.send("lithe/build/model", params({ refresh: true })); - await until(() => existsSync(`${gate}.started`), "Maven to start"); - touch("core/pom.xml", "edited during the run"); - writeFileSync(gate, ""); - const response = await pending.response; - assert.equal(response.result?.fakeRun, runs().length); - assert.equal(readFileSync(snapshotFile, "utf8"), saved, "the snapshot file is unchanged"); - control({}); - const before = runs().length; - await client.request("lithe/build/model", params()); - assert.equal(runs().length, before + 1, "the edit is read by a new run"); - await client.request("lithe/build/model", params()); - assert.equal(runs().length, before + 1, "and that run is saved"); - }); - - await check("Maven goes on while another request still waits for it", async () => { - const gate = join(scratch, "gate-partial-cancel"); - control({ gate }); - touch("app/pom.xml", "partial cancel"); - const before = runs().length; - const first = client.send("lithe/build/model", params()); - const second = client.send("lithe/build/dependencies", params({ project: { name: "core", path: "core" } })); - await until(() => existsSync(`${gate}.started`), "Maven to start"); - const maven = runs().at(-1).pid; - client.cancel(first.id); - assert.equal((await first.response).error?.code, -32800); - await sleep(300); - assert.ok(alive(maven), "Maven still runs for the second request"); - writeFileSync(gate, ""); - const result = (await second.response).result; - assert.deepEqual(result.dependencies.map((node) => node.name), ["junit"]); - assert.equal(runs().length, before + 1); - control({}); - }); - - await check("cancelling every waiting request ends Maven and its process tree", async () => { - const gate = join(scratch, "gate-cancel"); - control({ gate, child: true }); - touch("app/pom.xml", "cancel"); - const saved = readFileSync(snapshotFile, "utf8"); - const first = client.send("lithe/build/model", params()); - const second = client.send("lithe/build/model", params()); - await until(() => existsSync(`${gate}.started`) && pids(`${runLog}.children`).length > 0, "Maven and its child to start"); - const maven = runs().at(-1).pid; - const [child] = pids(`${runLog}.children`); - client.cancel(first.id); - client.cancel(second.id); - assert.equal((await first.response).error?.code, -32800); - assert.equal((await second.response).error?.code, -32800); - await until(() => !alive(maven), "Maven to end", 8_000); - if (javaMajor >= 9) { - await until(() => !alive(child), "Maven's child to end", 8_000); - } else { - // Java 8 cannot list descendants; Lithe's process scope ends them with the backend. - console.log(` Java ${javaMajor}: only Maven itself is stopped; ending its child here`); - try { process.kill(child, "SIGKILL"); } catch (error) { if (error.code !== "ESRCH") throw error; } - } - assert.equal(readFileSync(snapshotFile, "utf8"), saved, "a cancelled run saves nothing"); - control({}); - rmSync(`${runLog}.children`); - }); - - await check("a failed Maven run reports Maven's errors and keeps the old snapshot", async () => { - control({ exit: 1 }); - const saved = readFileSync(snapshotFile, "utf8"); - const { response } = client.send("lithe/build/model", params({ refresh: true })); - const { error } = await response; - assert.equal(error?.data?.code, "maven.loadFailed"); - assert.match(error.message, /\[ERROR\] fake failure for the backend test/); - assert.doesNotMatch(error.message, /Scanning for projects/); - assert.equal(readFileSync(snapshotFile, "utf8"), saved); - const terminal = client.diagnostics.at(-1); - assert.equal(terminal.kind, "operationFailed"); - assert.equal(terminal.operation, "lithe/build/model"); - assert.equal(terminal.code, "maven.loadFailed"); - assert.ok(!JSON.stringify(client.diagnostics).includes("fake failure for the backend test")); - assert.equal(client.stderr, "", "Maven output and exceptions never cross the SDK stderr boundary"); - control({}); - }); - - await check("Maven that succeeds without readable documents is an error, not an empty model", async () => { - const saved = readFileSync(snapshotFile, "utf8"); - for (const output of ["missing", "malformed"]) { - control({ output }); - const { error } = await client.send("lithe/build/model", params({ refresh: true })).response; - assert.equal(error?.data?.code, "maven.invalidOutput", output); - } - assert.equal(readFileSync(snapshotFile, "utf8"), saved); - control({}); - }); - - await check("a corrupt snapshot or one of an unknown version is a miss", async () => { - await client.request("lithe/build/model", params()); - let before = runs().length; - await stop(client); - writeFileSync(snapshotFile, "{not JSON"); - client = await start(); - await client.request("lithe/build/model", params()); - assert.equal(runs().length, before + 1); - - const stored = JSON.parse(readFileSync(snapshotFile, "utf8")); - stored.value.snapshotVersion = 2; - writeFileSync(snapshotFile, JSON.stringify(stored)); - before = runs().length; - await client.request("lithe/build/model", params()); - assert.equal(runs().length, before + 1); - assert.equal(JSON.parse(readFileSync(snapshotFile, "utf8")).value.snapshotVersion, 1, "the next run rewrites it"); - }); - - await check("without tool.executable the backend uses the project's Maven Wrapper", async () => { - mkdirSync(join(root, ".mvn", "wrapper"), { recursive: true }); - writeFileSync(join(root, ".mvn", "wrapper", "maven-wrapper.properties"), "distributionUrl=https://example.invalid/maven.zip\n"); - writeFileSync(join(root, "mvnw"), readFileSync(fakeMaven)); - chmodSync(join(root, "mvnw"), 0o755); - const { tool, ...rest } = params(); - await client.request("lithe/build/model", rest); - assert.equal(runs().at(-1).self, join(root, "mvnw")); - }); - - await check("the plugin backend serves languageImport.settings from .mvn/maven.config inside an open workspace folder", async () => { - const project = join(scratch, "language-import"); - mkdirSync(join(project, ".mvn"), { recursive: true }); - writeFileSync(join(project, "team-settings.xml"), ""); - writeFileSync(join(project, ".mvn", "maven.config"), '-B --offline\n-s "team-settings.xml"\n-gs missing.xml\n'); - const contextRef = { contextID: "ctx", generation: 1 }; - const functions = new BackendClient({ - java, jar, args: ["--plugin-backend"], - hostRequests: { "lithe/host/workspace/getFolders": () => ({ folders: [{ rootID: "r", name: "w", path: scratch }] }) }, - }); - clients.add(functions); - const initialized = await functions.initialize(project, { functions: true }); - assert.deepEqual(initialized.capabilities.experimental.litheFunctions.functions, [{ id: "languageImport.settings" }]); - const invoke = (workspaceRoot, context = contextRef) => functions.send("lithe/function/invoke", { - functionID: "languageImport.settings", operationID: `op-${Math.random()}`, params: { workspaceRoot }, ...(context ? { context } : {}), - }).response; - const answer = await invoke(project); - assert.deepEqual(answer.result, { settings: { - "java.import.maven.offline.enabled": true, - "java.configuration.maven.userSettings": join(project, "team-settings.xml"), - } }); - assert.equal((await invoke(tmpdir())).error?.data?.code, "maven.invalidRoot"); - assert.equal((await invoke("relative")).error?.data?.code, "maven.invalidRoot"); - assert.equal((await invoke(project, null)).error?.data?.code, "maven.noWorkspaceContext"); - assert.equal(await functions.close(), 0, `the plugin backend exits cleanly\n${functions.stderr}`); - clients.delete(functions); - }); - - await check("the backend exits on shutdown and leaves no Maven behind", async () => { - await stop(client); - for (const { pid } of runs()) assert.ok(!alive(pid), `Maven ${pid} ended`); - }); - } catch (error) { - failed = true; - report.failure("backend lane failed", error); - console.error(error.stack); - } finally { - for (const client of clients) { - if (failed) console.error(`backend stderr:\n${client.stderr}`); - client.kill(); - await bounded(client.exited, "the backend to be killed").catch(() => {}); - } - for (const pid of [...runs().map((run) => run.pid), ...pids(`${runLog}.children`)]) { - try { process.kill(pid, "SIGKILL"); } catch (error) { if (error.code !== "ESRCH") throw error; } - } - try { await report.step("remove the scratch workspace", () => rmSync(scratch, { recursive: true, force: true })); } - finally { report.write(); } - } - process.exitCode = failed ? 1 : 0; -} -await withInterrupts(test); diff --git a/scripts/test-process.mjs b/scripts/test-process.mjs index 171eed8..55f1333 100644 --- a/scripts/test-process.mjs +++ b/scripts/test-process.mjs @@ -90,7 +90,7 @@ await withInterrupts(async (signal) => { assertGone(records, 3); })); } - await check("a provider that cannot start or answers garbage fails both the lane and its reports", async () => { + await check("a Maven that fails or writes garbage fails both the lane and its reports", async () => { const cwd = join(scratch, "invalid-output"); mkdirSync(cwd); mkdirSync(join(cwd, "test/fixtures/reactor"), { recursive: true }); @@ -99,16 +99,15 @@ await withInterrupts(async (signal) => { mkdirSync(join(plugin, "lib"), { recursive: true }); cpSync(join(packageId, "plugin.json"), join(plugin, "plugin.json")); writeFileSync(join(plugin, "lib/lithe-maven-extension.jar"), "test placeholder"); - writeFileSync(join(plugin, "lib/lithe-maven-backend.jar"), "test placeholder"); - const fake = join(cwd, "fake-java.mjs"); - cpSync(resolve("test/fixtures/fake-java.mjs"), fake); + const fake = join(cwd, "fake-maven.mjs"); + cpSync(resolve("test/fixtures/fake-maven.mjs"), fake); chmodSync(fake, 0o755); const temporary = join(cwd, "tmp"); mkdirSync(temporary); for (const mode of ["exit", "malformed"]) { const reports = join(cwd, mode); await assert.rejects(runCommand(process.execPath, [resolve("scripts/test.mjs")], { - cwd, env: { ...process.env, LITHE_TEST_JAVA: fake, FAKE_JAVA_MODE: mode, TMPDIR: temporary, LITHE_REPORT_DIR: reports }, + cwd, env: { ...process.env, MVN: fake, FAKE_MAVEN_MODE: mode, TMPDIR: temporary, LITHE_REPORT_DIR: reports }, stdio: "ignore", timeoutMs: 5_000, graceMs: 4_000, }), /status 1/); const result = JSON.parse(readFileSync(join(reports, "maven-integration.json"), "utf8")); diff --git a/scripts/test.mjs b/scripts/test.mjs index 7779679..8723823 100644 --- a/scripts/test.mjs +++ b/scripts/test.mjs @@ -1,14 +1,14 @@ #!/usr/bin/env node -// Runs test/fixtures/reactor with a real Maven: the model and dependency -// trees through the packaged build provider (lib/lithe-maven-backend.jar, -// which runs Maven with the extension), and the commands plugin.json -// declares. It checks the documents Lithe receives; Lithe's own tests decode -// them, this script makes sure Maven produces them. The provider's caching is -// covered by scripts/test-backend.mjs with a fake Maven. +// Runs test/fixtures/reactor with a real Maven, the way Lithe runs the +// commands plugin.json declares: the model and dependency commands load +// lib/lithe-maven-extension.jar into Maven and write the documents Lithe +// decodes to ${outputFile}; the test command runs a filtered suite. It checks +// the documents Lithe receives; Lithe's own tests decode them, this script +// makes sure Maven produces them. // // Run scripts/package.mjs first. MVN selects the Maven executable (default -// `mvn`), so CI can also check the oldest supported Maven; LITHE_TEST_JAVA -// the Java that runs the provider (default `java`). +// `mvn`), so CI can also check the oldest supported Maven; JAVA_HOME selects +// the Java that runs it, as the JDK build option does in Lithe. // // LITHE_CAPTURE_DIR=

also copies the documents there, with the // scratch workspace written as `${workspace}`, for Lithe's Core tests. @@ -16,8 +16,6 @@ // Usage: node scripts/test.mjs import assert from "node:assert/strict"; -import { spawnSync } from "node:child_process"; -import { BackendClient, bounded } from "./backend-client.mjs"; import { mavenTimeout, runCommand, withInterrupts } from "./process.mjs"; import { createReport } from "./report.mjs"; import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; @@ -27,7 +25,7 @@ import { join, resolve } from "node:path"; const PACKAGE_DIR = "io.github.lithe-idea.maven-build"; const pluginDir = resolve("dist", "package", PACKAGE_DIR); const maven = process.env.MVN ?? "mvn"; -if (!existsSync(join(pluginDir, "lib", "lithe-maven-extension.jar")) || !existsSync(join(pluginDir, "lib", "lithe-maven-backend.jar"))) { +if (!existsSync(join(pluginDir, "lib", "lithe-maven-extension.jar"))) { console.error("✗ dist/package is missing; run node scripts/package.mjs first"); process.exit(1); } @@ -39,7 +37,7 @@ const buildSystem = manifest.buildSystems[0]; * option has a value, so `${optionArguments:…}` contributes nothing, and a * conditional argument is kept when its conditions hold. */ -function expand(list, { project, suite }) { +function expand(list, { project, suite, outputFile }) { const conditions = { projectSelected: project !== undefined, noProjectSelected: project === undefined, @@ -57,6 +55,7 @@ function expand(list, { project, suite }) { result.push( value .replaceAll("${pluginDir}", pluginDir) + .replaceAll("${outputFile}", outputFile ?? "") .replaceAll("${project.path}", project ?? "") .replaceAll("${test.suite}", suite ?? ""), ); @@ -75,6 +74,7 @@ function run(name, root, list, signal, values = {}) { const scratch = realpathSync(mkdtempSync(join(tmpdir(), "lithe-maven-test-"))); const root = join(scratch, "reactor"); +const outputs = join(scratch, "outputs"); const captureDir = process.env.LITHE_CAPTURE_DIR; function capture(name, document) { if (!captureDir) return; @@ -94,47 +94,31 @@ const check = async (name, body) => { } }; -/** The executable Lithe would pass as tool.executable: MVN, or `mvn` on PATH. */ -function mavenExecutable() { - if (maven.includes("/")) return resolve(maven); - const found = spawnSync("/bin/sh", ["-c", 'command -v "$0"', maven], { encoding: "utf8" }).stdout.trim(); - if (!found) throw new Error(`${maven} is not on PATH`); - return found; +/** + * Runs a declared command that writes its document to ${outputFile}, as the + * model and dependency commands do, and returns the parsed document. Like + * Lithe, it reads the file only after Maven exits successfully. + */ +async function document(name, declaration, signal, values = {}) { + assert.equal(declaration.source, "command"); + assert.equal(declaration.output, "outputFile"); + const outputFile = join(outputs, `${name.replaceAll(/[^A-Za-z0-9]+/g, "-")}.json`); + await run(name, root, declaration.arguments, signal, { ...values, outputFile }); + return JSON.parse(readFileSync(outputFile, "utf8")); } async function test(signal) { - let backend; - const stopBackend = () => backend?.kill(); - signal.addEventListener("abort", stopBackend, { once: true }); try { cpSync(resolve("test", "fixtures", "reactor"), root, { recursive: true }); + mkdirSync(outputs); - backend = new BackendClient({ - java: process.env.LITHE_TEST_JAVA ?? "java", - jar: join(pluginDir, "lib", "lithe-maven-backend.jar"), - state: join(scratch, "state"), - timeoutMs, - }); - await report.step("start the build provider", () => backend.initialize(root)); - const params = (extra = {}) => ({ - buildSystemID: "maven", root: ".", options: {}, optionArguments: [], environment: {}, - tool: { executable: mavenExecutable() }, ...extra, - }); - const model = await report.step("read the reactor model", () => backend.request("lithe/build/model", params())); + const model = await document("read the reactor model", buildSystem.model, signal); capture("model.json", model); - await check("model diagnostics use one typed terminal without Maven output", async () => { - const terminals = backend.diagnostics.filter((entry) => entry.operation === "lithe/build/model"); - assert.equal(terminals.length, 1); - assert.equal(terminals[0].kind, "operationFinished"); - assert.ok(Number.isSafeInteger(terminals[0].durationMs) && terminals[0].durationMs >= 0); - assert.deepEqual(Object.keys(terminals[0]).sort(), ["durationMs", "kind", "operation", "operationId"]); - assert.equal(terminals[0].operationId, "2"); - assert.equal(backend.stderr, ""); - }); const byName = (name) => model.projects.find((project) => project.name === name); await check("the model lists the reactor and its aggregator tree", () => { assert.equal(model.format, "litheBuildModel"); + assert.equal(model.version, 0); assert.deepEqual(model.projects.map((project) => project.name), ["reactor", "core", "app"]); assert.equal(byName("reactor").displayName, "Demo Reactor"); assert.equal(byName("core").parent, byName("reactor").path); @@ -172,19 +156,16 @@ async function test(signal) { assert.ok(!model.contentRoots.some((entry) => entry.project === byName("reactor").path)); }); - const projectDependencies = await report.step("read project dependencies", () => backend.request( - "lithe/build/dependencies", params({ project: { name: "app", path: "app" } }), - )); + const projectDependencies = await document("read project dependencies", buildSystem.dependencies, signal, { project: "app" }); capture("app-dependencies.json", projectDependencies); await check("a project's tree resolves an uninstalled sibling from the reactor", () => { const tree = projectDependencies; assert.equal(tree.format, "litheDependencies"); + assert.equal(tree.version, 0); assert.deepEqual(tree.dependencies.map((node) => [node.group, node.name, node.scope]), [["demo", "core", "compile"]]); }); - const workspaceDependencies = await report.step("read workspace dependencies", () => backend.request( - "lithe/build/dependencies", params({ project: null }), - )); + const workspaceDependencies = await document("read workspace dependencies", buildSystem.dependencies, signal); capture("dependencies.json", workspaceDependencies); await check("the workspace tree has one node per project with transitive children", () => { const tree = workspaceDependencies; @@ -194,13 +175,6 @@ async function test(signal) { assert.equal(junit.children[0].name, "hamcrest-core"); }); - await check("one Maven run serves the model and every tree, and is saved for the next start", async () => { - const saved = JSON.parse(readFileSync(join(scratch, "state", "maven-snapshot.json"), "utf8")).value; - assert.equal(saved.snapshotVersion, 1); - assert.deepEqual(saved.roots[root].model, model); - assert.equal(await backend.close(), 0); - }); - await check("reading the model and dependencies builds nothing", () => { for (const directory of ["target", "core/target", "app/target"]) { assert.ok(!existsSync(join(root, directory)), `${directory} was not created`); @@ -223,13 +197,7 @@ async function test(signal) { failed = true; report.failure("integration lane failed", error); console.error(error.stack); - if (backend) console.error(`build provider stderr:\n${backend.stderr}`); } finally { - signal.removeEventListener("abort", stopBackend); - if (backend) { - backend.kill(); - await bounded(backend.exited, "the build provider to end").catch(() => {}); - } try { await report.step("remove the scratch reactor", () => rmSync(scratch, { recursive: true, force: true })); } finally { report.write(); } } diff --git a/scripts/verify-scripts.mjs b/scripts/verify-scripts.mjs index 268ae65..71f4a5c 100644 --- a/scripts/verify-scripts.mjs +++ b/scripts/verify-scripts.mjs @@ -39,10 +39,10 @@ const unchanged = (name) => { await withInterrupts(async (signal) => { try { - for (const path of [packageId, "scripts", "extension", "backend", "vendor", "sdk.lock.json", "test", "LICENSE", "NOTICE"]) { + for (const path of [packageId, "scripts", "extension", "test", "LICENSE", "NOTICE"]) { cpSync(resolve(path), join(scratch, path), { recursive: true, - filter: (source) => source !== resolve("extension/target") && source !== resolve("backend/target"), + filter: (source) => source !== resolve("extension/target"), }); } const timeoutMs = mavenTimeout(); diff --git a/sdk.lock.json b/sdk.lock.json deleted file mode 100644 index 453b59b..0000000 --- a/sdk.lock.json +++ /dev/null @@ -1,104 +0,0 @@ -{ - "schemaVersion": 1, - "source": { - "repository": "https://github.com/Lithe-IDEA/lithe-plugin-docs", - "revision": "29b245c0e1d77c761d9032a3144a301d1818bfc7", - "localChanges": "Structured logging lithe/log implementation from the accompanying SDK working tree. Per-file hashes identify these reviewed inputs; no published release is claimed." - }, - "files": [ - { - "upstream": "LICENSE", - "path": "vendor/LICENSE", - "sha256": "93ff573f89d32394501fcc82767e73b1824add861f088bbd3eec9e0afae20d21" - }, - { - "upstream": "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": "c5430ea55f5ee73a88b8c6c3517cf6bc2237827b009ae1844c105254b7f48a24", - "localChanges": true, - "upstreamSha256": "c1943d63121ce20dfadf24dfcac50581da4371356fb5f7ee30962b41b2fd04a2" - }, - { - "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/CallContext.java", - "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CallContext.java", - "sha256": "c41fcc2cbc6533215ee9034409292ddeb6237d6c3defdd65b2cdfb8fb848dde8", - "localChanges": true, - "upstreamSha256": "8157d980a585b85ed31b96ad974fe980e167b6c0b7701b2636328ba84c0b62af" - }, - { - "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Cancellation.java", - "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Cancellation.java", - "sha256": "826c246360a607eb40ce950202db0988a465718082dc22be539f045139671db3", - "localChanges": true, - "upstreamSha256": "87eb1a9b673f59774ac1688393f62f8aa5379ead1ed2464b50ab64a0d6ad80d9" - }, - { - "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/CancelledException.java", - "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CancelledException.java", - "sha256": "699c054b1857a0518fd244ff193bc87445495ae40cbf7cc34436ac92ba42973e" - }, - { - "upstream": "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": "e6b70f167f1b030509fccf399745bc7693023eabeff1201696e866340d546ec9", - "localChanges": true, - "upstreamSha256": null - }, - { - "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Framing.java", - "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Framing.java", - "sha256": "510a82f0c29e634d4235326ed9abccc2c618f795e9aca6c354d516c7dce278db" - }, - { - "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Host.java", - "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Host.java", - "sha256": "ff2cc8830645722173a257aec66adec94cfae7d5a91501b1024e2843954dc8f1" - }, - { - "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/HostChannel.java", - "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostChannel.java", - "sha256": "79e337d8fc495c1c993d33205f70d79a0baa5fe49c054ef7032f02ce500f147c", - "localChanges": true, - "upstreamSha256": "1830ac36651759f3b4f77bda5fb23fd4b478a2c153671fc01920af38faefd09f" - }, - { - "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/HostError.java", - "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostError.java", - "sha256": "8072d652209042f578c3eaf49600f8797ed19662b8119581772f60a3b972fa96" - }, - { - "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Json.java", - "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Json.java", - "sha256": "7ff4a54ab5003cd86046db3b35110b4906b97fc56b8d934f33e6f51eb96dd5ed" - }, - { - "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/PluginError.java", - "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginError.java", - "sha256": "882485659c7e77833ebb383dd8175b7eede292596696f63678fbcd868c029806", - "localChanges": true, - "upstreamSha256": "33dec00015fc1611084bd99063e90dbce3c306e99b83faed1cd6a2f8cab24de7" - }, - { - "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/PluginSdkError.java", - "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginSdkError.java", - "sha256": "ced28c084e0f0d1d5c42d29d1c85b6528e065b9a933f7a6ab0a4eae1bcd6a520" - }, - { - "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Processes.java", - "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Processes.java", - "sha256": "86b50e196fb23ccd28e576b524a8da2d8928ac3113bbcd105180ceaef9981319", - "localChanges": true, - "upstreamSha256": "e1a499d9fc526179c624be1084188e2a394e46f5d5c512cc5c3e3b3d39661aeb" - }, - { - "upstream": "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": "b491ba1a55f869bf29ba337684fe0a1c42c00b9ae8887dac508cc508748d419d" - }, - { - "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/StateStore.java", - "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/StateStore.java", - "sha256": "c56519730a9243d5ce9e8333025456bd934890bd7ad134de3b8e8fb9fd28bfe4" - } - ] -} diff --git a/test/fixtures/fake-java.mjs b/test/fixtures/fake-java.mjs deleted file mode 100644 index 120b216..0000000 --- a/test/fixtures/fake-java.mjs +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env node -// Stands in for the Java that runs the build provider, so the integration -// lane's failure reporting is checked without Java or Maven: -// FAKE_JAVA_MODE=exit the provider cannot start -// FAKE_JAVA_MODE=malformed the provider answers with a frame that is not JSON -if (process.env.FAKE_JAVA_MODE === "exit") { - console.error("fake java: cannot start the provider"); - process.exit(3); -} -process.stdout.write("Content-Length: 5\r\n\r\n{nope"); -setInterval(() => {}, 60_000); diff --git a/test/fixtures/fake-maven-backend.mjs b/test/fixtures/fake-maven-backend.mjs deleted file mode 100644 index ebcff90..0000000 --- a/test/fixtures/fake-maven-backend.mjs +++ /dev/null @@ -1,102 +0,0 @@ -// Stands in for `mvn` when scripts/test-backend.mjs drives the backend. It -// logs each run, writes the two documents the extension would write for the -// reactor in its working directory, and obeys a control file the test -// rewrites between steps: -// { "gate": "" } write .started, then wait until exists -// { "child": true } start a SIGTERM-ignoring child and log its PID -// { "exit": } print an [ERROR] line and exit with the status -// { "output": "missing" | "malformed" } succeed without the documents, or with invalid JSON -import { spawn } from "node:child_process"; -import { appendFileSync, existsSync, readFileSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; - -const control = existsSync(process.env.FAKE_MAVEN_CONTROL ?? "") - ? JSON.parse(readFileSync(process.env.FAKE_MAVEN_CONTROL, "utf8")) - : {}; -const log = process.env.FAKE_MAVEN_LOG; -const argv = process.argv.slice(2); -appendFileSync(log, `${JSON.stringify({ pid: process.pid, self: process.env.FAKE_MAVEN_SELF, cwd: process.cwd(), argv })}\n`); - -if (control.child) { - const child = spawn(process.execPath, ["-e", "process.on('SIGTERM', () => {}); setInterval(() => {}, 60_000)"], { stdio: "ignore" }); - appendFileSync(`${log}.children`, `${child.pid}\n`); -} -if (control.gate) { - writeFileSync(`${control.gate}.started`, `${process.pid}\n`); - const deadline = Date.now() + 30_000; - while (!existsSync(control.gate)) { - if (Date.now() > deadline) process.exit(97); - await new Promise((resolve) => setTimeout(resolve, 20)); - } -} -if (control.exit) { - console.log("[INFO] Scanning for projects..."); - console.log("[ERROR] fake failure for the backend test"); - process.exit(control.exit); -} - -const value = (name) => argv.find((arg) => arg.startsWith(`-D${name}=`))?.slice(name.length + 3); -if (value("lithe.dependenciesProject") !== undefined) throw new Error("the backend must export every module"); -const modelOutput = value("lithe.modelOutput"); -const dependenciesOutput = value("lithe.dependenciesOutput"); -if (!modelOutput || !dependenciesOutput) throw new Error("expected both output properties"); -if (control.output === "missing") process.exit(0); -if (control.output === "malformed") { - writeFileSync(modelOutput, "{invalid JSON"); - writeFileSync(dependenciesOutput, "{invalid JSON"); - process.exit(0); -} - -const tag = (xml, name) => new RegExp(`<${name}>([^<]*)`).exec(xml)?.[1]; -const withoutParent = (xml) => xml.replace(/[\s\S]*?<\/parent>/, "").replace(/[\s\S]*<\/dependencies>/, ""); -function read(directory, parent) { - const xml = readFileSync(join(directory, "pom.xml"), "utf8"); - const own = withoutParent(xml); - const project = { - groupId: tag(own, "groupId") ?? parent?.groupId, - artifactId: tag(own, "artifactId"), - version: tag(own, "version") ?? parent?.version, - packaging: tag(own, "packaging") ?? "jar", - path: directory, - displayName: tag(own, "name"), - parentPath: parent?.path, - }; - project.dependencies = [...xml.matchAll(/([\s\S]*?)<\/dependency>/g)].map(([, body]) => ({ - name: tag(body, "artifactId"), - group: tag(body, "groupId"), - version: tag(body, "version").replace("${project.version}", project.version), - scope: tag(body, "scope") ?? "compile", - properties: { type: "jar" }, - children: [], - })); - const modules = [...xml.matchAll(/([^<]+)<\/module>/g)].map(([, name]) => name); - return [project, ...modules.flatMap((name) => read(join(directory, name), project))]; -} -const projects = read(process.cwd()); -const run = readFileSync(log, "utf8").trim().split("\n").length; - -writeFileSync(modelOutput, JSON.stringify({ - format: "litheBuildModel", - version: 1, - fakeRun: run, - projects: projects.map((project) => ({ - name: project.artifactId, - path: project.path, - ...(project.displayName ? { displayName: project.displayName } : {}), - ...(project.parentPath ? { parent: project.parentPath } : {}), - properties: { groupId: project.groupId, artifactId: project.artifactId, version: project.version, packaging: project.packaging }, - })), - tasks: [], - contentRoots: [], -})); -writeFileSync(dependenciesOutput, JSON.stringify({ - format: "litheDependencies", - version: 1, - dependencies: projects.map((project) => ({ - name: project.artifactId, - group: project.groupId, - version: project.version, - properties: { kind: "project", packaging: project.packaging }, - children: project.dependencies, - })), -})); diff --git a/test/fixtures/fake-maven.mjs b/test/fixtures/fake-maven.mjs new file mode 100644 index 0000000..dd54446 --- /dev/null +++ b/test/fixtures/fake-maven.mjs @@ -0,0 +1,13 @@ +#!/usr/bin/env node +// Stands in for Maven, so the integration lane's failure reporting is checked +// without Java or Maven: +// FAKE_MAVEN_MODE=exit Maven fails before writing the model +// FAKE_MAVEN_MODE=malformed Maven succeeds but the model is not JSON +import { writeFileSync } from "node:fs"; + +if (process.env.FAKE_MAVEN_MODE === "exit") { + console.error("fake mvn: the build failed"); + process.exit(1); +} +const output = process.argv.slice(2).find((arg) => arg.startsWith("-Dlithe.modelOutput=")); +if (output) writeFileSync(output.slice("-Dlithe.modelOutput=".length), "{nope"); diff --git a/vendor/LICENSE b/vendor/LICENSE deleted file mode 100644 index 69bef1d..0000000 --- a/vendor/LICENSE +++ /dev/null @@ -1,203 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or - Object form, that is based on (or derived from) the Work and - for which the editorial revisions, annotations, elaborations, - or other modifications represent, as a whole, an original work - of authorship. For the purposes of this License, Derivative Works - shall not include works that remain separable from, or merely link - (or bind by name) to the interfaces of, the Work and Derivative Works - thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of - its distribution, then any Derivative Works that You - distribute must include a readable copy of the attribution - notices contained within such NOTICE file, excluding those - notices that do not pertain to any part of the Derivative - Works, in at least one of the following places: within a - NOTICE text file distributed as part of the Derivative Works; - within the Source form or documentation, if provided along with - the Derivative Works; or, within a display generated by the - Derivative Works, if and wherever such third-party notices - normally appear. The contents of the NOTICE file are for - informational purposes only and do not modify the License. - You may add Your own attribution notices within Derivative - Works that You distribute, alongside or as an addendum to - the NOTICE text from the Work, provided that such additional - attribution notices cannot be construed as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing - the origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as - a result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[ ]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Backend.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Backend.java deleted file mode 100644 index b71b683..0000000 --- a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Backend.java +++ /dev/null @@ -1,1417 +0,0 @@ -package io.github.litheidea.plugin.sdk; - -import java.io.FileDescriptor; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintStream; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionException; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Supplier; - -/** - * The plugin backend session: one process the host starts from the plugin's - * manifest and talks to over stdio with the LSP base protocol. - * - *

The SDK owns everything Lithe manages uniformly -- the lifecycle, protocol - * negotiation, cancellation, error codes, and the {@code lithe/*} namespace -- - * and leaves the plugin free to decide what its handlers do. Declare handlers, - * then call {@link #listen()}. Handlers run on their own threads, so several - * calls can be in flight at once; shared plugin state needs its own locking. - * - *

Host services ({@code lithe/host/*}) of plugin-function protocols 2 and 3 - * are in {@link #host()}, or a handler's {@link CallContext#host()}. - * - *

Contract: {@code contract/v1/README.md} ("Build providers" - * and "Plugin functions"). Behaviour and error codes match the Node.js SDK. - */ -public final class Backend { - /** Answers a typed build request or a plugin function. */ - @FunctionalInterface - public interface Handler { - Object handle(Map params, CallContext context) throws Exception; - } - - /** Answers a standard LSP request, for a backend that is also a language server. */ - @FunctionalInterface - public interface RequestHandler { - Object handle(Object params, CallContext context) throws Exception; - } - - /** Handles a standard LSP notification. */ - @FunctionalInterface - public interface NotificationHandler { - void handle(Object params) throws Exception; - } - - /** - * Handles {@code lithe/host/commands/didRun} for one of the plugin's - * commands. {@code workspaceContext} is the {@code { contextID, generation }} - * of the window the command ran in, or null. - */ - @FunctionalInterface - public interface CommandHandler { - void handle(String commandId, Map workspaceContext) throws Exception; - } - - /** Runs before the {@code initialize} answer. */ - @FunctionalInterface - public interface InitializeHook { - void run(Map params, Negotiated negotiated) throws Exception; - } - - /** Runs on {@code shutdown}, after running calls were cancelled. */ - @FunctionalInterface - public interface ShutdownHook { - void run() throws Exception; - } - - /** Protocols the host agreed to in {@code initialize}. */ - public static final class Negotiated { - static final Negotiated NONE = new Negotiated(0, 0); - - private final int functionsVersion; - private final int buildVersion; - - Negotiated(int functionsVersion, int buildVersion) { - this.functionsVersion = functionsVersion; - this.buildVersion = buildVersion; - } - - /** Whether the host negotiated plugin functions ({@code litheFunctions}). */ - public boolean functions() { - return functionsVersion > 0; - } - - /** - * Selected plugin-function version (1-3), or zero when unavailable. - * Version 2 adds host credentials; version 3 workspace contexts, the - * other host services, and host notifications. - */ - public int functionsVersion() { - return functionsVersion; - } - - /** Whether the host negotiated typed build requests. */ - public boolean build() { - return buildVersion > 0; - } - - /** Selected build protocol version, or zero when unavailable. */ - public int buildVersion() { - return buildVersion; - } - } - - private enum Phase { IDLE, LISTENING, INITIALIZING, READY, SHUTTING_DOWN, EXITED } - - /** Canonical result format of each typed build request. */ - private static final Map BUILD_FORMATS; - - static { - Map formats = new HashMap<>(); - formats.put(Protocol.BUILD_MODEL, "litheBuildModel"); - formats.put(Protocol.BUILD_DEPENDENCIES, "litheDependencies"); - formats.put(Protocol.BUILD_DISCOVER_TESTS, "litheTestDiscovery"); - BUILD_FORMATS = Collections.unmodifiableMap(formats); - } - - private volatile boolean logging; - private boolean loggingReady; - private final List> earlyDiagnostics = new ArrayList<>(); - private final java.util.Set quietSuccess = new java.util.HashSet<>(); - private final String name; - private final String version; - private final Map capabilities; - private final Object lock = new Object(); - private final Object writeLock = new Object(); - private final Map functions = new HashMap<>(); - private final Map buildHandlers = new HashMap<>(); - private final Map requestHandlers = new HashMap<>(); - private final Map notificationHandlers = new HashMap<>(); - private final Map commandHandlers = new HashMap<>(); - private final Map hostNotificationHandlers = new HashMap<>(); - private NotificationHandler contextsHandler; - private final List initializeHooks = new ArrayList<>(); - private final List shutdownHooks = new ArrayList<>(); - /** Host requests being handled, by JSON-RPC ID. */ - private final Map incoming = new HashMap<>(); - /** Requests this backend sent to the host, by JSON-RPC ID. */ - private final Map outgoing = new HashMap<>(); - private final AtomicInteger nextRequestId = new AtomicInteger(1); - private final ExecutorService executor = Executors.newCachedThreadPool(new ThreadNamer()); - private final HostChannel channel = new HostChannel(new Wire()); - private final Host host = new Host(channel, Collections.emptyList()); - /** Serializes register/unregister so the host sees them in call order. */ - private CompletableFuture registrations = CompletableFuture.completedFuture(null); - private volatile Phase phase = Phase.IDLE; - private volatile Negotiated negotiated = Negotiated.NONE; - private volatile Map initializeParams; - private volatile OutputStream output; - private volatile PrintStream errorOutput = System.err; - private int exitCode = 1; - - private Backend(String name, String version, Map capabilities) { - Object experimental = capabilities.get("experimental"); - if (experimental instanceof Map - && (((Map) experimental).containsKey("litheBuild") - || ((Map) experimental).containsKey("litheFunctions") - || ((Map) experimental).containsKey("litheLogging"))) { - throw new PluginSdkError("sdk.capabilities.reserved", - "litheBuild and litheFunctions are negotiated by the SDK; declare handlers instead."); - } - this.name = name == null ? "lithe-plugin-backend" : name; - this.version = version; - this.capabilities = new LinkedHashMap<>(capabilities); - } - - /** - * Creates a backend. - * - * @param name reported as {@code serverInfo.name} and used as the log prefix - * @param version reported as {@code serverInfo.version}; may be null - */ - public static Backend create(String name, String version) { - return new Backend(name, version, Collections.emptyMap()); - } - - /** - * Creates a backend that also declares standard LSP server capabilities. - * {@code experimental.litheBuild} and {@code experimental.litheFunctions} - * are negotiated by the SDK and cannot be set here. - */ - public static Backend create(String name, String version, Map capabilities) { - return new Backend(name, version, capabilities == null ? Collections.emptyMap() : capabilities); - } - - /** Protocols the host agreed to in {@code initialize}; both false before it. */ - public Negotiated negotiated() { - return negotiated; - } - - /** - * Host services of plugin-function protocols 2 and 3, usable once the - * session is ready. Prefer a handler's {@link CallContext#host()}, whose - * requests end with the call. - */ - public Host host() { - return host; - } - - /** The host's {@code initialize} params, or null before it arrives. */ - public Map initializeParams() { - return initializeParams; - } - - /** IDs of the functions this backend currently serves, sorted. */ - public List functionIds() { - synchronized (lock) { - List ids = new ArrayList<>(functions.keySet()); - Collections.sort(ids); - return ids; - } - } - - /** Answers {@code lithe/build/model} with a {@code litheBuildModel} document. */ - public Backend onModel(Handler handler) { - return declareBuild(Protocol.BUILD_MODEL, handler); - } - - /** Answers {@code lithe/build/dependencies} with a {@code litheDependencies} document. */ - public Backend onDependencies(Handler handler) { - return declareBuild(Protocol.BUILD_DEPENDENCIES, handler); - } - - /** Executes a bounded provider task; requires build protocol 2 or newer. */ - public Backend onExecute(Handler handler) { - return declareBuild(Protocol.BUILD_EXECUTE, handler); - } - - /** Runs exact test selectors; requires build protocol 3 or newer. */ - public Backend onTest(Handler handler) { - return declareBuild(Protocol.BUILD_TEST, handler); - } - - /** Returns the upstream engine's runnable test selectors, with the format stamped. */ - public Backend onDiscoverTests(Handler handler) { - return declareBuild(Protocol.BUILD_DISCOVER_TESTS, handler); - } - - /** Prepares native executable target facts; requires build protocol 5. */ - public Backend onPrepareDebug(Handler handler) { - return declareBuild(Protocol.BUILD_PREPARE_DEBUG, handler); - } - - /** Prepares a portable application launch with build protocol 4 or newer. */ - public Backend onPrepareRun(Handler handler) { - return declareBuild(Protocol.BUILD_PREPARE_RUN, handler); - } - - /** - * Declares a plugin function offered from the start, in the {@code initialize} - * answer. To add one later, use {@link #registerFunction}. - * - * @param id dot-separated lowerCamelCase segments, such as {@code snapshot.refresh} - */ - public Backend function(String id, Handler handler) { - synchronized (lock) { - if (!beforeAnswer()) { - throw new PluginSdkError("sdk.function.lateDeclaration", - "After initialize, add functions with registerFunction()."); - } - checkNewFunction(id, handler); - functions.put(id, handler); - } - return this; - } - - /** Handles a standard LSP request, for a backend that is also a language server. */ - public Backend onRequest(String method, RequestHandler handler) { - checkDeclared(method, handler); - synchronized (lock) { - requestHandlers.put(method, handler); - } - return this; - } - - /** Handles a standard LSP notification. */ - public Backend onNotification(String method, NotificationHandler handler) { - checkDeclared(method, handler); - synchronized (lock) { - notificationHandlers.put(method, handler); - } - return this; - } - - /** - * Handles {@code lithe/host/commands/didRun} for one of the plugin's - * commands (protocol 3). It is an event: the host waits for no result. - * - * @param commandId the command's ID from the manifest, 1-128 of {@code [a-z0-9.-]} - */ - public Backend onCommand(String commandId, CommandHandler handler) { - if (!Protocol.isCommandId(commandId)) { - throw new PluginSdkError("sdk.command.invalidID", "Command ID \"" + commandId + "\" must be 1-128 of [a-z0-9.-]."); - } - if (handler == null) { - throw new IllegalArgumentException("A command handler must not be null."); - } - synchronized (lock) { - commandHandlers.put(commandId, handler); - } - return this; - } - - /** - * Handles {@code lithe/host/workspace/didChangeContexts} (protocol 3) with - * {@code { revision }}; call {@code host().workspace().listContexts()} for - * the contexts. - */ - public Backend onContextsChanged(NotificationHandler handler) { - if (handler == null) { - throw new IllegalArgumentException("A handler must not be null."); - } - synchronized (lock) { - contextsHandler = handler; - } - return this; - } - - /** - * Handles a {@code lithe/host/*} notification a later host adds. Commands, - * context changes, and subscription events have their own APIs. - */ - public Backend onHostNotification(String method, NotificationHandler handler) { - if (method == null || !method.startsWith(Protocol.HOST_PREFIX)) { - throw new PluginSdkError("sdk.method.invalid", method + " is not a host notification."); - } - if (method.equals(Protocol.HOST_DID_CHANGE_CONTEXTS) || method.equals(Protocol.HOST_SUBSCRIPTION_NOTIFY) - || method.equals(Protocol.HOST_COMMAND_DID_RUN)) { - throw new PluginSdkError("sdk.method.reserved", - method + " is routed by the SDK; use onCommand, onContextsChanged, or Host.subscribe."); - } - if (handler == null) { - throw new IllegalArgumentException("A handler must not be null."); - } - synchronized (lock) { - hostNotificationHandlers.put(method, handler); - } - return this; - } - - /** Runs before the {@code initialize} answer, with the host's params and the negotiation. */ - public Backend onInitialize(InitializeHook hook) { - synchronized (lock) { - initializeHooks.add(hook); - } - return this; - } - - /** Runs on {@code shutdown}, after running calls were cancelled. */ - public Backend onShutdown(ShutdownHook hook) { - synchronized (lock) { - shutdownHooks.add(hook); - } - return this; - } - - /** - * Adds a function. Before the {@code initialize} answer (including from an - * {@link #onInitialize} hook) it joins the initial list; afterwards the host - * must accept it first. The future completes once the function is served. - */ - public CompletableFuture registerFunction(String id, Handler handler) { - synchronized (lock) { - if (beforeAnswer()) { - try { - checkNewFunction(id, handler); - functions.put(id, handler); - return CompletableFuture.completedFuture(null); - } catch (RuntimeException error) { - return failed(error); - } - } - } - return queueRegistration(() -> { - synchronized (lock) { - requireFunctions(); - checkNewFunction(id, handler); - // Installed before the request: the host may invoke it as soon as - // its registry changed, before this backend reads the reply. - functions.put(id, handler); - } - Map entry = new LinkedHashMap<>(); - entry.put("id", id); - Map params = new LinkedHashMap<>(); - params.put("functions", Collections.singletonList(entry)); - return request(Protocol.FUNCTION_REGISTER, params).handle((result, error) -> { - if (error != null) { - synchronized (lock) { - functions.remove(id); - quietSuccess.remove(id); - } - throw new CompletionException(unwrap(error)); - } - return null; - }); - }); - } - - /** Withdraws a function. The host ends its running calls as revoked. */ - public CompletableFuture unregisterFunction(String id) { - synchronized (lock) { - if (beforeAnswer()) { - if (functions.remove(id) == null) { - return failed(unknownFunction(id)); - } - quietSuccess.remove(id); - return CompletableFuture.completedFuture(null); - } - } - return queueRegistration(() -> { - synchronized (lock) { - requireFunctions(); - if (!functions.containsKey(id)) { - throw unknownFunction(id); - } - } - Map params = new LinkedHashMap<>(); - params.put("ids", Collections.singletonList(id)); - return request(Protocol.FUNCTION_UNREGISTER, params).thenApply(result -> { - List running = new ArrayList<>(); - synchronized (lock) { - functions.remove(id); - quietSuccess.remove(id); - for (Call call : incoming.values()) { - if (id.equals(call.functionId)) { - running.add(call); - } - } - } - for (Call call : running) { - call.cancellation.cancel("The function was withdrawn."); - } - return null; - }); - }); - } - - /** Sends a standard LSP request to the host. {@code lithe/*} methods are reserved. */ - public CompletableFuture sendRequest(String method, Object params) { - checkOutgoing(method); - return request(method, params); - } - - /** Sends a standard LSP notification to the host. {@code lithe/*} methods are reserved. */ - public void sendNotification(String method, Object params) { - checkOutgoing(method); - Map message = message(null, method); - if (params != null) { - message.put("params", params); - } - write(message); - } - - public Diagnostics diagnostics() { return new Diagnostics(this, null); } - - public Backend suppressSuccessDiagnostics(String operation) { - if (!loggingOperation(operation)) throw new PluginSdkError("sdk.logging.invalidOperation", "Suppress a registered operation."); - synchronized (lock) { quietSuccess.add(operation); } - return this; - } - - boolean loggingOperation(String operation) { - synchronized (lock) { return Diagnostics.OPERATIONS.contains(operation) || functions.containsKey(operation); } - } - - void logFact(Map params) { - synchronized (lock) { - if (!logging) return; - if (!loggingReady) { if (earlyDiagnostics.size() < 8) earlyDiagnostics.add(params); return; } - } - Map notification = message(null, "lithe/log"); - notification.put("params", params); - write(notification); - } - - /** - * Serves the host over stdio until it sends {@code exit} or closes stdin, - * then exits the process with the session's exit code: 0 after a - * {@code shutdown}, 1 otherwise. {@code System.out} is redirected to stderr - * first, because stdout carries the protocol and a stray line there would - * end the session. - */ - public void listen() { - OutputStream protocol = new FileOutputStream(FileDescriptor.out); - System.setOut(System.err); - int code = listen(System.in, protocol, System.err); - System.exit(code); - } - - /** - * Serves the host over the given streams and returns the exit code once the - * session ended, without exiting the process. Blocks the calling thread. - */ - public int listen(InputStream input, OutputStream output, PrintStream errorOutput) { - synchronized (lock) { - if (phase != Phase.IDLE) { - throw new PluginSdkError("sdk.listen.repeated", "A backend listens once."); - } - phase = Phase.LISTENING; - this.output = output; - this.errorOutput = errorOutput; - } - Framing.Decoder decoder = new Framing.Decoder(); - byte[] chunk = new byte[64 * 1024]; - try { - while (phase != Phase.EXITED) { - int count = input.read(chunk); - if (count < 0) { - finish(phase == Phase.SHUTTING_DOWN ? 0 : 1); - break; - } - List messages; - try { - messages = decoder.push(chunk, 0, count); - } catch (Framing.FramingException error) { - diagnostics().terminal("notification", new IllegalStateException(), System.nanoTime()); - finish(1); - break; - } - for (Object message : messages) { - if (phase == Phase.EXITED) { - break; - } - dispatch(message); - } - } - } catch (IOException error) { - finish(1); - } - synchronized (lock) { - return exitCode; - } - } - - private void dispatch(Object message) { - if (message == Framing.MALFORMED) { - respond(null, null, error(Protocol.PARSE_ERROR, "The message is not valid JSON.")); - return; - } - // Valid JSON that is not a message object, such as `null` or a batch. - if (!(message instanceof Map)) { - respond(null, null, error(Protocol.INVALID_REQUEST, "The message is not a JSON-RPC object.")); - return; - } - Map object = Json.object(message); - Object id = object.get("id"); - Object method = object.get("method"); - if (!(method instanceof String)) { - if (id != null) { - settleOutgoing(object); - } - return; - } - if (id != null) { - handleRequest(id, (String) method, object.get("params")); - } else { - handleNotification((String) method, object.get("params")); - } - } - - private void handleRequest(Object id, String method, Object params) { - if (method.equals(Protocol.INITIALIZE)) { - initialize(id, params instanceof Map ? Json.object(params) : new LinkedHashMap<>()); - return; - } - if (method.equals(Protocol.SHUTDOWN)) { - shutdown(id); - return; - } - Phase current = phase; - if (current == Phase.LISTENING || current == Phase.INITIALIZING) { - respond(id, null, error(Protocol.SERVER_NOT_INITIALIZED, "The backend is not initialized.")); - return; - } - if (current != Phase.READY) { - respond(id, null, error(Protocol.INVALID_REQUEST, "The backend is shutting down.")); - return; - } - if (method.equals(Protocol.FUNCTION_INVOKE)) { - invokeFunction(id, params); - return; - } - Handler build; - RequestHandler handler; - synchronized (lock) { - build = negotiated.buildVersion() >= Protocol.buildMethodVersion(method) ? buildHandlers.get(method) : null; - handler = requestHandlers.get(method); - } - if (build != null) { - if (params != null && !(params instanceof Map)) { - respond(id, null, error(Protocol.INVALID_PARAMS, method + " params must be an object.")); - return; - } - Map arguments = Json.object(params); - invokeBuild(id, method, arguments, build); - return; - } - if (handler != null) { - run(id, null, null, context -> handler.handle(params, context), result -> result, null); - return; - } - respond(id, null, error(Protocol.METHOD_NOT_FOUND, "Unsupported method: " + method)); - } - - private void handleNotification(String method, Object params) { - if (method.equals(Protocol.EXIT)) { - finish(phase == Phase.SHUTTING_DOWN ? 0 : 1); - return; - } - if (method.equals(Protocol.CANCEL_REQUEST)) { - Object id = params instanceof Map ? ((Map) params).get("id") : null; - Call call; - synchronized (lock) { - call = incoming.get(requestKey(id)); - } - if (call != null) { - call.cancellation.cancel("The request was cancelled."); - } - return; - } - if (phase != Phase.READY || method.equals(Protocol.INITIALIZED)) { - return; - } - if (method.startsWith(Protocol.HOST_PREFIX)) { - hostNotification(method, params); - return; - } - NotificationHandler handler; - synchronized (lock) { - handler = notificationHandlers.get(method); - } - if (handler == null) { - return; - } - notifyHandler(method, () -> handler.handle(params)); - } - - /** - * Routes a host notification. Core checked its shape and the session's - * grant; one this SDK does not know is ignored, as the contract asks. - */ - private void hostNotification(String method, Object raw) { - if (negotiated.functionsVersion() < Protocol.CONTEXT_VERSION || !(raw instanceof Map)) { - return; - } - Map params = Json.object(raw); - if (method.equals(Protocol.HOST_SUBSCRIPTION_NOTIFY)) { - channel.deliver(params); - return; - } - if (method.equals(Protocol.HOST_COMMAND_DID_RUN)) { - Object commandId = params.get("commandID"); - CommandHandler handler; - synchronized (lock) { - handler = commandId instanceof String ? commandHandlers.get(commandId) : null; - } - if (handler == null) { - diagnostics().degraded("notification", "command_unhandled"); - return; - } - Map context = workspaceContext(params.get("context")); - notifyHandler(method, () -> handler.handle((String) commandId, context)); - return; - } - NotificationHandler handler; - synchronized (lock) { - handler = method.equals(Protocol.HOST_DID_CHANGE_CONTEXTS) ? contextsHandler : hostNotificationHandlers.get(method); - } - if (handler != null) { - notifyHandler(method, () -> handler.handle(params)); - } - } - - private interface Notified { - void run() throws Exception; - } - - /** Runs a notification handler off the reader thread; a failure is logged. */ - private void notifyHandler(String method, Notified handler) { - executor.execute(() -> { - try { - handler.run(); - } catch (Throwable error) { - diagnostics().terminal("notification", error, System.nanoTime()); - } - }); - } - - private void initialize(Object id, Map params) { - Negotiated agreed; - List hooks; - synchronized (lock) { - if (phase != Phase.LISTENING) { - respond(id, null, error(Protocol.INVALID_REQUEST, "initialize was already received.")); - return; - } - phase = Phase.INITIALIZING; - initializeParams = params; - Map offered = experimental(params.get("capabilities")); - loggingReady = false; - earlyDiagnostics.clear(); - logging = offers(offered.get("litheLogging"), 1); - if (!logging) { - phase = Phase.LISTENING; - respond(id, null, error(Protocol.INVALID_REQUEST, "The backend requires litheLogging version 1.")); - return; - } - int buildVersion = 0; - if (!buildHandlers.isEmpty()) { - for (int version = Protocol.BUILD_VERSION; version > 0; version--) { - if (offers(offered.get("litheBuild"), version)) { - buildVersion = version; - break; - } - } - } - int functionsVersion = 0; - for (int version = Protocol.FUNCTIONS_VERSION; version > 0; version--) { - if (offers(offered.get("litheFunctions"), version)) { - functionsVersion = version; - break; - } - } - agreed = new Negotiated(functionsVersion, buildVersion); - negotiated = agreed; - hooks = new ArrayList<>(initializeHooks); - } - executor.execute(() -> { - try { - for (InitializeHook hook : hooks) { - hook.run(params, agreed); - } - } catch (Throwable failure) { - synchronized (lock) { - if (phase == Phase.INITIALIZING) { - phase = Phase.LISTENING; - } - } - respond(id, null, toResponseError(failure, null)); - return; - } - synchronized (lock) { - // A shutdown or exit that arrived while a hook ran ended the - // session; finishing initialize must not reopen it. - if (phase != Phase.INITIALIZING) { - respond(id, null, error(Protocol.INVALID_REQUEST, "The session ended during initialize.")); - return; - } - if (!agreed.functions() && !functions.isEmpty()) { - diagnostics().degraded("initialize", "functions_unavailable"); - } - Map experimental = new LinkedHashMap<>(experimental(capabilities)); - experimental.put("litheLogging", singleton("version", 1)); - if (agreed.build()) { - experimental.put("litheBuild", singleton("version", agreed.buildVersion())); - } - if (agreed.functions()) { - List offered = new ArrayList<>(); - for (String functionId : functionIds()) { - offered.add(singleton("id", functionId)); - } - Map entry = singleton("version", agreed.functionsVersion()); - entry.put("functions", offered); - experimental.put("litheFunctions", entry); - } - Map answered = new LinkedHashMap<>(capabilities); - answered.put("experimental", experimental); - Map serverInfo = singleton("name", name); - if (version != null) { - serverInfo.put("version", version); - } - Map result = singleton("capabilities", answered); - result.put("serverInfo", serverInfo); - phase = Phase.READY; - respond(id, result, null); - loggingReady = true; - List> early = new ArrayList<>(earlyDiagnostics); - earlyDiagnostics.clear(); - for (Map fact : early) logFact(fact); - } - }); - } - - private void shutdown(Object id) { - List hooks; - synchronized (lock) { - if (phase != Phase.READY && phase != Phase.LISTENING && phase != Phase.INITIALIZING) { - respond(id, null, error(Protocol.INVALID_REQUEST, "shutdown was already received.")); - return; - } - phase = Phase.SHUTTING_DOWN; - hooks = new ArrayList<>(shutdownHooks); - } - cancelAll("The backend is shutting down."); - executor.execute(() -> { - for (ShutdownHook hook : hooks) { - try { - hook.run(); - } catch (Throwable error) { - diagnostics().terminal("shutdown", error, System.nanoTime()); - } - } - Processes.killAll(); - respond(id, null, null); - }); - } - - private void invokeFunction(Object id, Object raw) { - Map invocation = raw instanceof Map ? Json.object(raw) : new LinkedHashMap<>(); - Object functionId = invocation.get("functionID"); - Object operationId = invocation.get("operationID"); - Object params = invocation.get("params"); - Map workspaceContext = workspaceContext(invocation.get("context")); - Handler handler; - synchronized (lock) { - handler = negotiated.functions() && functionId instanceof String ? functions.get(functionId) : null; - } - if (handler == null) { - respond(id, null, error(Protocol.INVALID_PARAMS, "Function " + functionId + " is not registered.")); - return; - } - if (params != null && !(params instanceof Map)) { - respond(id, null, error(Protocol.INVALID_PARAMS, "Function " + functionId + " params must be an object.")); - return; - } - String function = (String) functionId; - String operation = operationId instanceof String ? (String) operationId : null; - Map arguments = Json.object(params); - AtomicBoolean reporting = new AtomicBoolean(true); - CallContext.ProgressSink progress = (message, percentage) -> { - if (!reporting.get()) { - return; - } - Map report = new LinkedHashMap<>(); - report.put("operationID", operationId); - if (message != null) { - report.put("message", Protocol.boundedText(message)); - } - if (percentage != null && !percentage.isNaN() && !percentage.isInfinite()) { - report.put("percentage", Math.min(100L, Math.max(0L, Math.round(percentage)))); - } - Map notification = message(null, Protocol.FUNCTION_PROGRESS); - notification.put("params", report); - write(notification); - }; - run(id, function, operation, workspaceContext, context -> handler.handle(arguments, context), - Backend::functionResult, () -> reporting.set(false), progress); - } - - private void invokeBuild(Object id, String method, Map arguments, Handler handler) { - if (arguments.containsKey("modelInputs") && negotiated.buildVersion() < 6) { - respond(id, null, error(Protocol.INVALID_PARAMS, "Model inputs require build protocol 6.")); - return; - } - if (!Protocol.buildProgress(method)) { - run(id, null, null, null, context -> handler.handle(arguments, context), result -> buildResult(method, result), null, null, method); - return; - } - Object wireId = arguments.get("operationID"); - if (!(wireId instanceof String)) { - respond(id, null, error(Protocol.INVALID_PARAMS, "A build request needs its wire operationID.")); - return; - } - AtomicBoolean reporting = new AtomicBoolean(true); - CallContext.ProgressSink progress = new CallContext.ProgressSink() { - @Override - public void report(String message, Double percentage) { report(message, percentage, null); } - @Override - public void report(String text, Double percentage, String output) { - if (!reporting.get()) return; - Map report = singleton("operationID", wireId); - if (text != null) report.put("message", Protocol.boundedText(text, Protocol.MAX_BUILD_MESSAGE_BYTES)); - if (output != null) report.put("output", Protocol.boundedText(output, Protocol.MAX_BUILD_OUTPUT_BYTES)); - if (percentage != null && !percentage.isNaN() && !percentage.isInfinite()) { - report.put("percentage", Math.min(100L, Math.max(0L, Math.round(percentage)))); - } - Map notification = message(null, Protocol.BUILD_PROGRESS); - notification.put("params", report); - write(notification); - } - }; - run(id, null, (String) wireId, null, context -> handler.handle(arguments, context), - result -> buildResult(method, result), () -> reporting.set(false), progress, method); - } - - private interface Invocation { - Object invoke(CallContext context) throws Exception; - } - - private interface Shape { - Object apply(Object result); - } - - private void run(Object id, String functionId, String operationId, Invocation invoke, Shape shape, Runnable onSettled) { - run(id, functionId, operationId, null, invoke, shape, onSettled, null); - } - - /** Runs one handler with its own cancellation and answers exactly once. */ - private void run(Object id, String functionId, String operationId, Map workspaceContext, - Invocation invoke, Shape shape, Runnable onSettled, CallContext.ProgressSink progress) { - run(id, functionId, operationId, workspaceContext, invoke, shape, onSettled, progress, functionId == null ? "function-call" : functionId); - } - - private void run(Object id, String functionId, String operationId, Map workspaceContext, - Invocation invoke, Shape shape, Runnable onSettled, CallContext.ProgressSink progress, String diagnosticOperation) { - long started = System.nanoTime(); - String diagnosticOperationId = Diagnostics.requestOperationId(operationId, id); - Cancellation cancellation = new Cancellation(() -> diagnostics().degraded("notification", "cancellation_listener_failed")); - String key = requestKey(id); - synchronized (lock) { - incoming.put(key, new Call(cancellation, functionId)); - } - CallContext context = new CallContext(cancellation, this, functionId, diagnosticOperationId, progress, - new Host(channel, Collections.singletonList(cancellation)), workspaceContext); - executor.execute(() -> { - Object result = null; - Map error = null; - try { - Object value = invoke.invoke(context); - cancellation.throwIfCancelled(); - result = shape.apply(value); - } catch (Throwable failure) { - if (!cancellation.isCancelled()) { - new Diagnostics(this, diagnosticOperationId).terminal(diagnosticOperation, failure, started); - } - error = toResponseError(failure, cancellation); - } - if (error == null && !cancellation.isCancelled()) { - boolean quiet; - synchronized (lock) { quiet = context.quietSuccess() || quietSuccess.contains(diagnosticOperation); } - if (!quiet) new Diagnostics(this, diagnosticOperationId).terminal(diagnosticOperation, null, started); - } - try { - if (onSettled != null) { - onSettled.run(); - } - } finally { - synchronized (lock) { - incoming.remove(key); - } - // Work belongs to its call: tools still running when the handler - // returned end now. Other calls have their own cancellation. - cancellation.cancel("The call ended."); - // Answered whatever the clean-up did, so Lithe never waits for - // its timeout. - respond(id, result, error); - } - }); - } - - private Backend declareBuild(String method, Handler handler) { - if (handler == null) { - throw new IllegalArgumentException("A build handler must not be null."); - } - synchronized (lock) { - if (phase != Phase.IDLE) { - throw new PluginSdkError("sdk.build.lateDeclaration", "Declare build handlers before listen()."); - } - buildHandlers.put(method, handler); - } - return this; - } - - private static void checkDeclared(String method, Object handler) { - if (method == null || Protocol.isReservedMethod(method)) { - throw new PluginSdkError("sdk.method.reserved", method + " is managed by the SDK and Lithe."); - } - if (handler == null) { - throw new IllegalArgumentException("A handler must not be null."); - } - } - - private void checkNewFunction(String id, Handler handler) { - if (!Protocol.isFunctionId(id)) { - throw new PluginSdkError("sdk.function.invalidID", "Function ID \"" + id - + "\" must be dot-separated lowerCamelCase segments of at most 128 bytes."); - } - if (handler == null) { - throw new IllegalArgumentException("A function handler must not be null."); - } - if (functions.containsKey(id)) { - throw new PluginSdkError("sdk.function.duplicate", "Function " + id + " is already declared."); - } - if (functions.size() >= Protocol.MAX_FUNCTIONS) { - throw new PluginSdkError("sdk.function.limit", - "A backend serves at most " + Protocol.MAX_FUNCTIONS + " functions."); - } - } - - /** True until the {@code initialize} answer fixes the initial function list. */ - private boolean beforeAnswer() { - return phase == Phase.IDLE || phase == Phase.LISTENING || phase == Phase.INITIALIZING; - } - - private void requireFunctions() { - if (phase != Phase.READY || !negotiated.functions()) { - throw new PluginSdkError("sdk.functions.unavailable", "The host has not negotiated plugin functions."); - } - } - - private static PluginSdkError unknownFunction(String id) { - return new PluginSdkError("sdk.function.unknown", "Function " + id + " is not registered."); - } - - private CompletableFuture queueRegistration(Supplier> change) { - synchronized (lock) { - CompletableFuture next = registrations.thenComposeAsync(ignored -> { - try { - return change.get(); - } catch (RuntimeException error) { - return failed(error); - } - }, executor); - registrations = next.handle((result, error) -> null); - return next; - } - } - - private void checkOutgoing(String method) { - if (method == null || Protocol.isReservedMethod(method)) { - throw new PluginSdkError("sdk.method.reserved", method - + " is reserved. A backend never asks the host to run a domain operation or a function."); - } - if (phase != Phase.READY) { - throw new PluginSdkError("sdk.session.notReady", "The session is not initialized."); - } - } - - private CompletableFuture request(String method, Object params) { - return send(method, params).response; - } - - /** Writes a request; params JSON cannot encode throw before anything is registered. */ - private HostChannel.Sent send(String method, Object params) { - String id = "sdk-" + nextRequestId.getAndIncrement(); - CompletableFuture future = new CompletableFuture<>(); - Map message = message(id, method); - if (params != null) { - message.put("params", params); - } - byte[] frame = Framing.encode(message); - synchronized (lock) { - if (phase == Phase.EXITED) { - future.completeExceptionally(new PluginSdkError("sdk.session.closed", "The session ended.")); - return new HostChannel.Sent(id, future); - } - outgoing.put(id, new Pending(future, method)); - } - writeEncoded(frame); - return new HostChannel.Sent(id, future); - } - - private void settleOutgoing(Map message) { - Object id = message.get("id"); - Pending pending; - synchronized (lock) { - pending = id instanceof String ? outgoing.remove(id) : null; - } - if (pending == null) { - return; - } - Object error = message.get("error"); - // Completed on a handler thread: the reader thread never runs plugin code. - if (error instanceof Map) { - HostError rejection = HostError.fromResponse(pending.method, Json.object(error)); - executor.execute(() -> pending.future.completeExceptionally(rejection)); - } else { - Object result = message.get("result"); - executor.execute(() -> pending.future.complete(result)); - } - } - - private void cancelAll(String reason) { - List calls; - synchronized (lock) { - calls = new ArrayList<>(incoming.values()); - } - for (Call call : calls) { - call.cancellation.cancel(reason); - } - } - - private void finish(int code) { - List pending; - synchronized (lock) { - if (phase == Phase.EXITED) { - return; - } - phase = Phase.EXITED; - exitCode = code; - pending = new ArrayList<>(outgoing.values()); - outgoing.clear(); - } - channel.close(); - cancelAll("The session ended."); - Processes.killAll(); - for (Pending request : pending) { - request.future.completeExceptionally(new PluginSdkError("sdk.session.closed", "The session ended.")); - } - // Running handlers finish on their own threads; nothing new starts. - executor.shutdown(); - } - - private void respond(Object id, Object result, Map error) { - if (phase == Phase.EXITED) { - return; - } - Map message = message(id, null); - if (error != null) { - message.put("error", error); - } else { - message.put("result", result); - } - try { - writeEncoded(Framing.encode(message)); - } catch (Json.JsonException failure) { - // A result JSON cannot encode must not end the session. - diagnostics().terminal("result-encoding", failure, System.nanoTime()); - Map fallback = message(id, null); - fallback.put("error", toResponseError(failure, null)); - write(fallback); - } - } - - private void write(Map message) { - writeEncoded(Framing.encode(message)); - } - - private void writeEncoded(byte[] frame) { - synchronized (writeLock) { - OutputStream stream = output; - if (stream == null || phase == Phase.EXITED) { - return; - } - try { - stream.write(frame); - stream.flush(); - } catch (IOException error) { - // The host closed the pipe; the input side ends the session. - // The closed protocol pipe leaves the host owning the terminal process fact. - } - } - } - - /** - * The JSON-RPC error object for a handler failure. Only {@link PluginError} - * carries a plugin code; any other exception becomes a generic internal - * error so that stack traces and machine paths never reach the host's UI. - */ - static Map toResponseError(Throwable failure, Cancellation cancellation) { - Throwable error = unwrap(failure); - if (cancellation != null && cancellation.isCancelled() && error instanceof CancelledException) { - return error(Protocol.REQUEST_CANCELLED, "The request was cancelled."); - } - if (error instanceof PluginError) { - Map response = error(Protocol.REQUEST_FAILED, Protocol.boundedText(error.getMessage())); - response.put("data", singleton("code", ((PluginError) error).code())); - return response; - } - // Unexpected exceptions often embed absolute paths or internals; the - // caller logs only a fixed failure category to stderr. - return error(Protocol.INTERNAL_ERROR, "The plugin backend failed unexpectedly."); - } - - /** - * Stamps the canonical format on a build result, so a handler can return the - * plain document. A result in another format is a backend bug: Core would - * refuse it as {@code plugin.build.invalidOutput}, so it fails here with a log. - */ - static Object buildResult(String method, Object result) { - String expected = BUILD_FORMATS.get(method); - if (!(result instanceof Map)) { - throw new PluginSdkError("sdk.build.invalidResult", method + " must return a reply object."); - } - Map document = new LinkedHashMap<>(Json.object(result)); - if (expected != null) { - Object format = document.get("format"); - if (format != null && !expected.equals(format)) { - throw new PluginSdkError("sdk.build.invalidResult", method + " returned another format."); - } - Object version = document.get("version"); - if (version != null && !(version instanceof Number && ((Number) version).doubleValue() == 1)) { - throw new PluginSdkError("sdk.build.invalidResult", method + " returned a version other than 1."); - } - document.put("format", expected); - document.put("version", 1); - } - if (Protocol.BUILD_EXECUTE.equals(method) || Protocol.BUILD_TEST.equals(method)) { - Object exit = document.get("exitCode"); - Object output = document.get("output"); - if (!(exit instanceof Number) || ((Number) exit).doubleValue() < Integer.MIN_VALUE - || ((Number) exit).doubleValue() > Integer.MAX_VALUE - || ((Number) exit).doubleValue() != ((Number) exit).longValue() - || !(output instanceof String) || Protocol.utf8Length((String) output) > Protocol.MAX_BUILD_RESULT_BYTES) { - throw new PluginSdkError("sdk.build.invalidResult", method + " needs an int32 exitCode and bounded output."); - } - document.put("exitCode", ((Number) exit).longValue()); - } - if (Protocol.BUILD_PREPARE_DEBUG.equals(method)) { - if (!(document.get("program") instanceof String) || !(document.get("workingDirectory") instanceof String) - || !stringList(document.get("arguments")) || !stringMap(document.get("environment")) - || document.size() != 4) { - throw new PluginSdkError("sdk.build.invalidResult", "Native debug preparation needs program, arguments, workingDirectory and environment only."); - } - } - if (Protocol.BUILD_PREPARE_RUN.equals(method)) { - Map executable = Json.object(document.get("executable")); - if (!("toolchain".equals(executable.get("kind")) || "command".equals(executable.get("kind"))) - || !(executable.get("value") instanceof String) || !(document.get("workingDirectory") instanceof String) - || !stringList(document.get("arguments")) || !stringMap(document.get("environment"))) { - throw new PluginSdkError("sdk.build.invalidResult", method + " needs a portable launch plan."); - } - } - // Workspace containment and domain facts remain Core/provider responsibilities. - if (Protocol.utf8Length(Json.stringify(document)) > Protocol.MAX_BUILD_RESULT_BYTES) { - throw new PluginSdkError("sdk.build.invalidResult", method + " exceeds the build-result size limit."); - } - return document; - } - - private static boolean stringList(Object value) { - if (!(value instanceof List)) return false; - for (Object item : (List) value) if (!(item instanceof String)) return false; - return true; - } - - private static boolean stringMap(Object value) { - if (!(value instanceof Map)) return false; - for (Map.Entry item : ((Map) value).entrySet()) { - if (!(item.getKey() instanceof String) || !(item.getValue() instanceof String)) return false; - } - return true; - } - - /** - * A function result as the JSON value Core accepts. A value JSON cannot - * encode, or one over Core's 1 MiB limit, fails here as a backend bug with a - * log line, instead of breaking the response frame or being refused by Core. - */ - static Object functionResult(Object result) { - String encoded; - try { - encoded = Json.stringify(result); - } catch (Json.JsonException error) { - throw new PluginSdkError("sdk.function.invalidResult", "The result is not JSON: " + error.getMessage()); - } - if (encoded.getBytes(StandardCharsets.UTF_8).length > Protocol.MAX_RESULT_BYTES) { - throw new PluginSdkError("sdk.function.invalidResult", - "The result exceeds " + Protocol.MAX_RESULT_BYTES + " bytes."); - } - return result; - } - - private static boolean offers(Object entry, int version) { - if (!(entry instanceof Map)) { - return false; - } - Object versions = ((Map) entry).get("versions"); - if (!(versions instanceof List)) { - return false; - } - for (Object offered : (List) versions) { - if (offered instanceof Number && ((Number) offered).doubleValue() == version) { - return true; - } - } - return false; - } - - /** {@code capabilities.experimental}, or an empty map. */ - private static Map experimental(Object capabilities) { - Object experimental = capabilities instanceof Map ? ((Map) capabilities).get("experimental") : null; - return experimental instanceof Map ? Json.object(experimental) : Collections.emptyMap(); - } - - /** The JSON-RPC ID as a map key; numbers and strings never collide. */ - private static String requestKey(Object id) { - if (id instanceof Number) { - Number number = (Number) id; - return "number:" + (number.doubleValue() == number.longValue() ? Long.toString(number.longValue()) : number); - } - return (id instanceof String ? "string:" : "other:") + id; - } - - private static Map message(Object id, String method) { - Map message = new LinkedHashMap<>(); - message.put("jsonrpc", "2.0"); - if (id != null || method == null) { - message.put("id", id); - } - if (method != null) { - message.put("method", method); - } - return message; - } - - private static Map error(int code, String text) { - Map error = new LinkedHashMap<>(); - error.put("code", code); - error.put("message", text); - return error; - } - - private static Map singleton(String key, Object value) { - Map map = new LinkedHashMap<>(); - map.put(key, value); - return map; - } - - /** The failure inside {@code CompletableFuture}'s wrappers, from {@code join()} or {@code get()}. */ - static Throwable unwrap(Throwable error) { - Throwable current = error; - while ((current instanceof CompletionException || current instanceof ExecutionException) && current.getCause() != null) { - current = current.getCause(); - } - return current; - } - - private static CompletableFuture failed(Throwable error) { - CompletableFuture future = new CompletableFuture<>(); - future.completeExceptionally(error); - return future; - } - - /** The {@code { contextID, generation }} the host sent, or null. */ - private static Map workspaceContext(Object value) { - return Protocol.isContextReference(value) ? Host.contextReference(Json.object(value)) : null; - } - - /** The session's wire, for host services. */ - private final class Wire implements HostChannel.Transport { - @Override - public int version() { - return negotiated.functionsVersion(); - } - - @Override - public boolean ready() { - return phase == Phase.READY; - } - - @Override - public HostChannel.Sent send(String method, Object params) { - return Backend.this.send(method, params); - } - - @Override - public void notify(String method, Object params) { - Map notification = message(null, method); - notification.put("params", params); - write(notification); - } - - @Override - public void log(String message) { - Backend.this.diagnostics().degraded("notification", "subscription_queue_full"); - } - - @Override - public void log(String message, Throwable error) { - Backend.this.diagnostics().terminal("notification", error, System.nanoTime()); - } - - @Override - public void execute(Runnable task) { - executor.execute(task); - } - } - - /** One host request being handled. */ - private static final class Call { - final Cancellation cancellation; - final String functionId; - - Call(Cancellation cancellation, String functionId) { - this.cancellation = cancellation; - this.functionId = functionId; - } - } - - /** One request this backend sent to the host. */ - private static final class Pending { - final CompletableFuture future; - final String method; - - Pending(CompletableFuture future, String method) { - this.future = future; - this.method = method; - } - } - - /** Daemon threads, so a handler still running never keeps the process alive after exit. */ - private static final class ThreadNamer implements java.util.concurrent.ThreadFactory { - private final AtomicInteger next = new AtomicInteger(1); - - @Override - public Thread newThread(Runnable runnable) { - Thread thread = new Thread(runnable, "lithe-sdk-call-" + next.getAndIncrement()); - thread.setDaemon(true); - return thread; - } - } -} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CallContext.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CallContext.java deleted file mode 100644 index ceffda4..0000000 --- a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CallContext.java +++ /dev/null @@ -1,119 +0,0 @@ -package io.github.litheidea.plugin.sdk; - -import java.io.IOException; -import java.util.List; -import java.util.Map; - -/** - * What a handler gets besides its params: the call's cancellation, tools and - * host requests that end with the call, the backend's log, and progress for - * plugin functions or bounded build operations. - */ -public final class CallContext { - /** Sends one progress report; absent for model, dependency and discovery requests. */ - interface ProgressSink { - void report(String message, Double percentage); - default void report(String message, Double percentage, String output) { report(message, percentage); } - } - - private final java.util.concurrent.atomic.AtomicBoolean quietSuccess = new java.util.concurrent.atomic.AtomicBoolean(); - private final Cancellation cancellation; - private final Backend backend; - private final String functionId; - private final String operationId; - private final ProgressSink progress; - private final Host host; - private final Map workspaceContext; - - CallContext(Cancellation cancellation, Backend backend, String functionId, String operationId, ProgressSink progress, - Host host, Map workspaceContext) { - this.cancellation = cancellation; - this.backend = backend; - this.functionId = functionId; - this.operationId = operationId; - this.progress = progress; - this.host = host; - this.workspaceContext = workspaceContext; - } - - /** - * Cancelled when the host cancels the call, the backend shuts down, or the - * call ends; work a handler leaves running after it returned is stopped. - */ - public Cancellation cancellation() { - return cancellation; - } - - public boolean isCancelled() { - return cancellation.isCancelled(); - } - - /** Throws {@link CancelledException} once the call was cancelled. */ - public void throwIfCancelled() { - cancellation.throwIfCancelled(); - } - - /** - * Runs a tool that belongs to this call: cancelling the call or ending it - * stops the tool, and the backend shutting down ends it. - */ - public Processes.Result run(List command, Processes.Options options) throws IOException { - Processes.Options settings = options == null ? new Processes.Options() : options.copy(); - settings.listenerFailure(() -> diagnostics().degraded("notification", "output_listener_failed")); - Cancellation own = settings.cancellation(); - settings.cancellation(own == null ? cancellation : cancellation.combinedWith(own)); - return Processes.run(command, settings); - } - - /** Runs a tool that belongs to this call with default options. */ - public Processes.Result run(List command) throws IOException { - return run(command, null); - } - - public void suppressSuccessDiagnostics() { quietSuccess.set(true); } - boolean quietSuccess() { return quietSuccess.get(); } - - public Diagnostics diagnostics() { return new Diagnostics(backend, operationId); } - - /** - * Reports progress of a function or bounded build call. Function messages - * are cut to 1024 bytes, build messages to 4096; percentages are rounded to - * 0-100. Reports after cancellation or completion are dropped. - */ - public void progress(String message, Double percentage) { progress(message, percentage, null); } - - /** Build calls may additionally stream up to 64 KiB of output per report. */ - public void progress(String message, Double percentage, String output) { - if (progress != null && !cancellation.isCancelled()) progress.report(message, percentage, output); - } - - /** The function this call runs, or null for a build or LSP request. */ - public String functionId() { - return functionId; - } - - /** The wire operation ID of a function or bounded build call, otherwise null. */ - public String operationId() { - return operationId; - } - - /** - * Host services that belong to this call: requests still unanswered when - * the call is cancelled or ends fail with {@link CancelledException} and, - * from protocol 3, are cancelled on the wire. A subscription created here - * outlives the call until it is disposed. - */ - public Host host() { - return host; - } - - /** - * The {@code { contextID, generation }} of the workspace a function was - * invoked for (protocol 3), or null: for other calls, before protocol 3, - * and for an invocation outside a workspace. Pass it to the - * {@link Host} methods that name a context. - */ - public Map workspaceContext() { - return workspaceContext; - } -} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Cancellation.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Cancellation.java deleted file mode 100644 index d80cd7d..0000000 --- a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Cancellation.java +++ /dev/null @@ -1,112 +0,0 @@ -package io.github.litheidea.plugin.sdk; - -import java.util.ArrayList; -import java.util.List; - -/** - * Cancellation of one call, or of work a plugin manages itself. Listeners run - * once, on the thread that cancels; a listener added after cancellation runs - * immediately. A listener that throws is logged to stderr and does not keep - * the others, or the thread that cancelled, from running on. Cancelling never interrupts threads, because an interrupt - * closes NIO channels a handler may be writing state through; long work checks - * {@link #isCancelled()} or {@link #throwIfCancelled()} instead. - */ -public final class Cancellation { - private final Object lock = new Object(); - private final List listeners = new ArrayList<>(); - private String reason; - private final Runnable listenerFailure; - public Cancellation() { this(() -> {}); } - Cancellation(Runnable listenerFailure) { this.listenerFailure = listenerFailure; } - - /** Cancels with {@code reason}; later calls have no effect. */ - public void cancel(String reason) { - List pending; - synchronized (lock) { - if (this.reason != null) { - return; - } - this.reason = reason == null ? "The request was cancelled." : reason; - pending = new ArrayList<>(listeners); - listeners.clear(); - } - for (Runnable listener : pending) { - runIsolated(listener); - } - } - - public boolean isCancelled() { - synchronized (lock) { - return reason != null; - } - } - - /** Throws {@link CancelledException} once cancelled. */ - public void throwIfCancelled() { - String current; - synchronized (lock) { - current = reason; - } - if (current != null) { - throw new CancelledException(current); - } - } - - /** - * Runs {@code listener} on cancellation. The returned handle removes it, - * for work that finished first. - */ - public Registration onCancel(Runnable listener) { - synchronized (lock) { - if (reason == null) { - listeners.add(listener); - return () -> { - synchronized (lock) { - listeners.remove(listener); - } - }; - } - } - runIsolated(listener); - return () -> {}; - } - - /** - * A token cancelled when either this one or {@code other} is; for work that - * a plugin may also stop for its own reasons. - */ - public Cancellation combinedWith(Cancellation other) { - Cancellation combined = new Cancellation(listenerFailure); - Registration first = onCancel(() -> combined.cancel(reasonOrDefault())); - Registration second = other.onCancel(() -> combined.cancel(other.reasonOrDefault())); - combined.onCancel(() -> { - first.remove(); - second.remove(); - }); - return combined; - } - - private void runIsolated(Runnable listener) { - try { - listener.run(); - } catch (RuntimeException error) { - listenerFailure.run(); - } - } - - /** The reason it was cancelled with, or the default text before that. */ - String reason() { - return reasonOrDefault(); - } - - private String reasonOrDefault() { - synchronized (lock) { - return reason == null ? "The request was cancelled." : reason; - } - } - - /** Removes a cancellation listener. */ - public interface Registration { - void remove(); - } -} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CancelledException.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CancelledException.java deleted file mode 100644 index dd01676..0000000 --- a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CancelledException.java +++ /dev/null @@ -1,14 +0,0 @@ -package io.github.litheidea.plugin.sdk; - -/** - * Thrown when the call a piece of work belongs to was cancelled or ended. - * A handler normally lets it propagate; the SDK then answers the host with - * {@code RequestCancelled}. - */ -public class CancelledException extends RuntimeException { - private static final long serialVersionUID = 1L; - - public CancelledException(String message) { - super(message); - } -} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Diagnostics.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Diagnostics.java deleted file mode 100644 index 6912594..0000000 --- a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Diagnostics.java +++ /dev/null @@ -1,71 +0,0 @@ -package io.github.litheidea.plugin.sdk; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; - -/** Typed facts for the host's litheLogging 1 catalog; never accepts message or payload text. */ -public final class Diagnostics { - static final long MAX_INTEGER = 9007199254740991L; - static final Set OPERATIONS = new HashSet<>(Arrays.asList( - "initialize", "shutdown", "notification", "function-call", "result-encoding", - "lithe/build/model", "lithe/build/dependencies", "lithe/build/execute", "lithe/build/test", - "lithe/build/discoverTests", "lithe/build/prepareRun", "lithe/build/prepareDebug", - "lithe/vcs/status", "lithe/vcs/baseContent", "lithe/vcs/history", "lithe/vcs/fileHistory", - "lithe/vcs/annotate", "lithe/vcs/checkin", "lithe/vcs/rollback", "lithe/vcs/update", - "lithe/vcs/fileOperation", "lithe/vcs/resolve", "lithe/vcs/cleanup")); - private final Backend backend; - private final String operationId; - - Diagnostics(Backend backend, String operationId) { - this.backend = backend; - this.operationId = operationId; - } - - public void degraded(String operation, String code, Long count) { record("degraded", operation, code, count, null); } - public void recovered(String operation, String code, Long count) { record("recovered", operation, code, count, null); } - public void degraded(String operation, String code) { degraded(operation, code, null); } - public void recovered(String operation, String code) { recovered(operation, code, null); } - - static boolean token(String value, int maximum) { - return value != null && value.length() > 0 && value.length() <= maximum && value.matches("[A-Za-z0-9._:/\\-$]+"); - } - - static String requestOperationId(String operationId, Object requestId) { - if (token(operationId, 128)) return operationId; - String fallback = requestId instanceof String ? (String) requestId : null; - if (requestId instanceof Number) { - double number = ((Number) requestId).doubleValue(); - if (Double.isFinite(number) && Math.abs(number) <= MAX_INTEGER && number == Math.rint(number)) { - fallback = Long.toString(((Number) requestId).longValue()); - } - } - return token(fallback, 128) ? fallback : null; - } - - void terminal(String operation, Throwable failure, long started) { - String code = null; - if (failure != null) { - Throwable error = Backend.unwrap(failure); - code = error instanceof PluginError ? ((PluginError) error).code() : "internal_error"; - } - record(failure == null ? "operationFinished" : "operationFailed", operation, code, null, - Math.min(MAX_INTEGER, Math.max(0, (System.nanoTime() - started) / 1000000))); - } - - private void record(String kind, String operation, String code, Long count, Long duration) { - if (!backend.loggingOperation(operation)) throw new PluginSdkError("sdk.logging.invalidOperation", "Diagnostics need a registered operation."); - if (code != null && !token(code, 64)) throw new PluginSdkError("sdk.logging.invalidCode", "Diagnostics need a controlled code."); - if (count != null && (count < 0 || count > MAX_INTEGER)) throw new PluginSdkError("sdk.logging.invalidCount", "Diagnostics need a nonnegative safe count."); - Map params = new LinkedHashMap<>(); - params.put("kind", kind); - params.put("operation", operation.length() <= 64 ? operation : "function-call"); - if (code != null) params.put("code", code); - if (count != null) params.put("count", count); - if (duration != null) params.put("durationMs", duration); - if (token(operationId, 128)) params.put("operationId", operationId); - backend.logFact(params); - } -} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Framing.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Framing.java deleted file mode 100644 index 36f76f6..0000000 --- a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Framing.java +++ /dev/null @@ -1,138 +0,0 @@ -package io.github.litheidea.plugin.sdk; - -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * LSP base-protocol framing: {@code Content-Length} headers followed by a UTF-8 - * JSON body. Lithe talks to every plugin backend this way, so the SDK owns the - * framing and plugin code never writes to stdout itself. - */ -public final class Framing { - /** Largest header block accepted from the host. */ - static final int MAX_HEADER_BYTES = 8192; - - /** Largest body accepted from the host. Larger frames end the session. */ - public static final int MAX_FRAME_BYTES = 64 * 1024 * 1024; - - /** Stands for a body that is not JSON; compared by identity, so no host message can mimic it. */ - public static final Object MALFORMED = new Object() { - @Override - public String toString() { - return "MALFORMED"; - } - }; - - private static final byte[] HEADER_END = {'\r', '\n', '\r', '\n'}; - - private Framing() {} - - /** A framing error the session cannot recover from. */ - public static final class FramingException extends RuntimeException { - private static final long serialVersionUID = 1L; - - FramingException(String message) { - super(message); - } - } - - /** Encodes one JSON-RPC message as a complete frame. */ - public static byte[] encode(Object message) { - byte[] body = Json.stringify(message).getBytes(StandardCharsets.UTF_8); - byte[] header = ("Content-Length: " + body.length + "\r\n\r\n").getBytes(StandardCharsets.US_ASCII); - byte[] frame = Arrays.copyOf(header, header.length + body.length); - System.arraycopy(body, 0, frame, header.length, body.length); - return frame; - } - - /** Incrementally splits a byte stream into decoded JSON-RPC messages. */ - public static final class Decoder { - private byte[] buffer = new byte[8192]; - private int length; - - /** - * Appends {@code count} bytes of {@code chunk} and returns every complete - * message they finished. A body that is not JSON is returned as - * {@link #MALFORMED} so the caller can report it without losing the - * framing position. - */ - public List push(byte[] chunk, int offset, int count) { - ensureCapacity(length + count); - System.arraycopy(chunk, offset, buffer, length, count); - length += count; - List messages = new ArrayList<>(); - int start = 0; - for (;;) { - int headerEnd = indexOfHeaderEnd(start); - int available = length - start; - // The same bound whether the header arrived whole or in pieces. - if ((headerEnd >= 0 && headerEnd - start > MAX_HEADER_BYTES) - || (headerEnd < 0 && available > MAX_HEADER_BYTES)) { - throw new FramingException("The message header is too long."); - } - if (headerEnd < 0) { - break; - } - int bodyLength = contentLength(new String(buffer, start, headerEnd - start, StandardCharsets.US_ASCII)); - int bodyStart = headerEnd + HEADER_END.length; - if ((long) length < (long) bodyStart + bodyLength) { - break; - } - String body = new String(buffer, bodyStart, bodyLength, StandardCharsets.UTF_8); - start = bodyStart + bodyLength; - try { - messages.add(Json.parse(body)); - } catch (Json.JsonException error) { - messages.add(MALFORMED); - } - } - if (start > 0) { - System.arraycopy(buffer, start, buffer, 0, length - start); - length -= start; - } - return messages; - } - - private int indexOfHeaderEnd(int from) { - for (int index = from; index + HEADER_END.length <= length; index++) { - if (buffer[index] == '\r' && buffer[index + 1] == '\n' - && buffer[index + 2] == '\r' && buffer[index + 3] == '\n') { - return index; - } - } - return -1; - } - - private void ensureCapacity(int required) { - if (required > buffer.length) { - buffer = Arrays.copyOf(buffer, Math.max(required, buffer.length * 2)); - } - } - } - - private static int contentLength(String header) { - for (String line : header.split("\r\n")) { - int separator = line.indexOf(':'); - if (separator < 0) { - continue; - } - if (!line.substring(0, separator).trim().equalsIgnoreCase("content-length")) { - continue; - } - String value = line.substring(separator + 1).trim(); - if (!value.matches("[0-9]+")) { - break; - } - // More than ten digits exceeds the limit whatever they are. - long length = value.length() > 10 ? Long.MAX_VALUE : Long.parseLong(value); - if (length > MAX_FRAME_BYTES) { - throw new FramingException("A message of " + value + " bytes exceeds the " - + MAX_FRAME_BYTES + "-byte limit."); - } - return (int) length; - } - throw new FramingException("A message has no valid Content-Length header."); - } -} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Host.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Host.java deleted file mode 100644 index 5e67d63..0000000 --- a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Host.java +++ /dev/null @@ -1,520 +0,0 @@ -package io.github.litheidea.plugin.sdk; - -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CompletableFuture; -import java.util.function.BooleanSupplier; - -/** - * Host services ({@code lithe/host/*}) of plugin-function protocols 2 and 3: - * credentials from version 2; workspace contexts, files, documents, the - * editor, previews, the browser, messages, and capability discovery from - * version 3. Every method answers with a future and never blocks; failures - * the host reports arrive as {@link HostError}. - * - *

{@link Backend#host()} is usable once the session is ready. A handler's - * {@link CallContext#host()} belongs to its call: requests still unanswered - * when the call is cancelled or ends fail with {@link CancelledException} and, - * from version 3, are cancelled on the wire. At most 16 requests are on the - * wire at once; the rest wait their turn. - * - *

Contract: {@code contract/v1/README.md}, "Host services". - */ -public final class Host { - /** Receives a subscription's events, one at a time and in order. */ - @FunctionalInterface - public interface Listener { - void onEvent(Event event) throws Exception; - } - - /** One {@code lithe/host/subscriptions/notify}. */ - public static final class Event { - private final String subscriptionId; - private final long sequence; - private final boolean gap; - private final Object event; - - Event(String subscriptionId, long sequence, boolean gap, Object event) { - this.subscriptionId = subscriptionId; - this.sequence = sequence; - this.gap = gap; - this.event = event; - } - - public String subscriptionId() { - return subscriptionId; - } - - /** Starts at 1 and grows by one per event of the subscription. */ - public long sequence() { - return sequence; - } - - /** - * True when events before this one were lost, so state built from - * earlier events should be refreshed, for example by rescanning. - */ - public boolean gap() { - return gap; - } - - /** The event, usually an object. */ - public Object event() { - return event; - } - } - - /** A host subscription, such as a file watch or registered editor actions. */ - public static final class Subscription { - private final String id; - private final BooleanSupplier live; - private final HostChannel channel; - - Subscription(String id, BooleanSupplier live, HostChannel channel) { - this.id = id; - this.live = live; - this.channel = channel; - } - - public String id() { - return id; - } - - /** True once disposed here or the session ended. */ - public boolean isDisposed() { - return !live.getAsBoolean(); - } - - /** Stops routing events at once and asks the host to dispose the subscription. */ - public CompletableFuture dispose() { - return channel.dispose(id); - } - } - - private final HostChannel channel; - private final List scope; - private final Credentials credentials = new Credentials(); - private final Subscriptions subscriptions = new Subscriptions(); - private final Workspace workspace = new Workspace(); - private final Documents documents = new Documents(); - private final Editor editor = new Editor(); - private final Preview preview = new Preview(); - private final Browser browser = new Browser(); - private final Window window = new Window(); - - Host(HostChannel channel, List scope) { - this.channel = channel; - this.scope = Collections.unmodifiableList(new ArrayList<>(scope)); - } - - /** The negotiated plugin-function version, or 0 before or without one. */ - public int version() { - return channel.version(); - } - - /** - * The same services, with requests also cancelled by {@code cancellation}, - * for work a plugin may stop for its own reasons. - */ - public Host withCancellation(Cancellation cancellation) { - if (cancellation == null) { - throw new IllegalArgumentException("A cancellation must not be null."); - } - List combined = new ArrayList<>(scope); - combined.add(cancellation); - return new Host(channel, combined); - } - - /** - * Sends any {@code lithe/host/*} request, including methods a later host - * adds; {@link #supports} says whether the session may call it. - */ - public CompletableFuture request(String method, Object params) { - return channel.request(method, params, scope); - } - - /** - * Sends a request that answers {@code { subscriptionID }} and routes the - * subscription's events to {@code listener}. - */ - public CompletableFuture subscribe(String method, Object params, Listener listener) { - return channel.subscribe(method, params, listener, scope); - } - - /** - * {@code { protocolVersion, backendAuthority, services, limits }}, asked - * once per session; needs protocol 3. - */ - public CompletableFuture> capabilities() { - return channel.capabilities(); - } - - /** - * Whether this session may call {@code method}: from {@link #capabilities} - * on protocol 3, the credential methods on protocol 2. - */ - public CompletableFuture supports(String method) { - return channel.supports(method); - } - - public Credentials credentials() { - return credentials; - } - - public Subscriptions subscriptions() { - return subscriptions; - } - - public Workspace workspace() { - return workspace; - } - - public Documents documents() { - return documents; - } - - public Editor editor() { - return editor; - } - - public Preview preview() { - return preview; - } - - public Browser browser() { - return browser; - } - - public Terminal terminal() { - return new Terminal(); - } - - public Window window() { - return window; - } - - /** - * {@code { contextID, generation }} of a context reference or of a full - * context from {@code listContexts} or {@code getContext}, so either can be - * passed on. - * - * @throws PluginSdkError {@code sdk.host.invalidContext} for anything else - */ - public static Map contextReference(Map context) { - Object id = context == null ? null : context.get("contextID"); - Object generation = context == null ? null : context.get("generation"); - if (!(id instanceof String) || !Protocol.isCredentialKey((String) id) || !Protocol.isGeneration(generation)) { - throw new PluginSdkError("sdk.host.invalidContext", - "A context is { contextID, generation }: an ID of 1-128 ASCII letters, digits, \".\", \"_\", \":\" or \"-\", and a positive generation."); - } - Map reference = new LinkedHashMap<>(); - reference.put("contextID", id); - reference.put("generation", ((Number) generation).longValue()); - return Collections.unmodifiableMap(reference); - } - - /** Secrets in the operating system's credential store, scoped to the plugin (protocol 2). */ - public final class Credentials { - private Credentials() {} - - /** The stored secret, or null when nothing is stored under {@code key}. */ - public CompletableFuture get(String key) { - if (!Protocol.isCredentialKey(key)) { - return failed(invalidKey()); - } - return channel.request(Protocol.HOST_CREDENTIALS_GET, params("key", key), scope).thenApply(result -> { - if (result == null) { - return null; - } - Object secret = result instanceof Map ? ((Map) result).get("secret") : null; - if (!(secret instanceof String)) { - throw new PluginSdkError("sdk.host.invalidResult", "The host answered credentials/get without a secret."); - } - return (String) secret; - }); - } - - public CompletableFuture set(String key, String secret) { - if (!Protocol.isCredentialKey(key)) { - return failed(invalidKey()); - } - if (secret == null || secret.getBytes(StandardCharsets.UTF_8).length > Protocol.MAX_CREDENTIAL_SECRET_BYTES) { - return failed(new PluginSdkError("sdk.credentials.invalidSecret", "A secret is a string of at most 16 KiB.")); - } - Map params = params("key", key); - params.put("secret", secret); - return channel.request(Protocol.HOST_CREDENTIALS_SET, params, scope).thenApply(result -> null); - } - - /** Deletes the secret; also succeeds when nothing was stored. */ - public CompletableFuture delete(String key) { - if (!Protocol.isCredentialKey(key)) { - return failed(invalidKey()); - } - return channel.request(Protocol.HOST_CREDENTIALS_DELETE, params("key", key), scope).thenApply(result -> null); - } - } - - public final class Subscriptions { - private Subscriptions() {} - - /** Disposes a subscription by ID; also succeeds for an unknown or disposed one. */ - public CompletableFuture dispose(String subscriptionId) { - return channel.dispose(subscriptionId); - } - } - - /** - * Workspace contexts and files (protocol 3). Every method but - * {@link #listContexts} names a context: a reference from - * {@link CallContext#workspaceContext()}, or a context from - * {@link #listContexts}. - */ - public final class Workspace { - private Workspace() {} - - /** {@code { revision, contexts }}. */ - public CompletableFuture> listContexts() { - return object(Protocol.HOST_WORKSPACE_LIST_CONTEXTS, channel.request( - Protocol.HOST_WORKSPACE_LIST_CONTEXTS, new LinkedHashMap(), scope)); - } - - public CompletableFuture> getContext(Map context) { - return scoped(Protocol.HOST_WORKSPACE_GET_CONTEXT, context, null); - } - - /** {@code { folders }}. */ - public CompletableFuture> getFolders(Map context) { - return scoped(Protocol.HOST_WORKSPACE_GET_FOLDERS, context, null); - } - - /** {@code params}: {@code resource, cursor?, limit?}. */ - public CompletableFuture> readDirectory(Map context, Map params) { - return scoped(Protocol.HOST_WORKSPACE_READ_DIRECTORY, context, params); - } - - /** {@code params}: {@code resource}. */ - public CompletableFuture> stat(Map context, Map params) { - return scoped(Protocol.HOST_WORKSPACE_STAT, context, params); - } - - /** {@code params}: {@code resource, maximumBytes?}. */ - public CompletableFuture> readFile(Map context, Map params) { - return scoped(Protocol.HOST_WORKSPACE_READ_FILE, context, params); - } - - /** - * Watches {@code resource, recursive?}; events are - * {@code { rootID, changedPaths, requiresRescan }}. - */ - public CompletableFuture watch(Map context, Map params, Listener listener) { - Map message; - try { - message = withContext(context, params); - } catch (PluginSdkError error) { - return failed(error); - } - return channel.subscribe(Protocol.HOST_WORKSPACE_WATCH, message, listener, scope); - } - - /** {@code params}: root {@code resource, query, fileMask?, cursor?, limit?}. */ - public CompletableFuture> findFiles(Map context, Map params) { - return scoped(Protocol.HOST_WORKSPACE_FIND_FILES, context, params); - } - - /** {@code params}: root {@code resource, pattern}, and optional search options. */ - public CompletableFuture> findText(Map context, Map params) { - return scoped(Protocol.HOST_WORKSPACE_FIND_TEXT, context, params); - } - } - - /** Open documents, read from their live buffers (protocol 3). */ - public final class Documents { - private Documents() {} - - /** {@code { documents }}. */ - public CompletableFuture> list(Map context) { - return scoped(Protocol.HOST_DOCUMENTS_LIST, context, null); - } - - /** {@code params}: {@code documentID}; answers {@code { document, text }}. */ - public CompletableFuture> getSnapshot(Map context, Map params) { - return scoped(Protocol.HOST_DOCUMENTS_GET_SNAPSHOT, context, params); - } - } - - /** The text editor (protocol 3). */ - public final class Editor { - private Editor() {} - - /** The foreground text tab's document summary, or null. */ - public CompletableFuture> getActive(Map context) { - return scoped(Protocol.HOST_EDITOR_GET_ACTIVE, context, null); - } - - /** {@code params}: {@code documentID}. */ - public CompletableFuture> getSelections(Map context, Map params) { - return scoped(Protocol.HOST_EDITOR_GET_SELECTIONS, context, params); - } - - /** {@code params}: {@code documentID, expectedVersion, edits}. */ - public CompletableFuture> applyEdits(Map context, Map params) { - return scoped(Protocol.HOST_EDITOR_APPLY_EDITS, context, params); - } - - /** {@code params}: {@code documentID, expectedVersion, selections, replacements}. */ - public CompletableFuture> replaceSelections(Map context, Map params) { - return scoped(Protocol.HOST_EDITOR_REPLACE_SELECTIONS, context, params); - } - - /** {@code params}: {@code documentID, expectedVersion, at, text}. */ - public CompletableFuture> insertText(Map context, Map params) { - return scoped(Protocol.HOST_EDITOR_INSERT_TEXT, context, params); - } - - /** {@code params}: {@code resource, activation?, range?, tab?}. */ - public CompletableFuture> open(Map context, Map params) { - return scoped(Protocol.HOST_EDITOR_OPEN, context, params); - } - - /** {@code params}: {@code resource, activation?, range?, tab?}. */ - public CompletableFuture> reveal(Map context, Map params) { - return scoped(Protocol.HOST_EDITOR_REVEAL, context, params); - } - - /** - * Registers editor actions ({@code id, function, selector}) that invoke - * one of the backend's functions; disposing the subscription removes them. - */ - public CompletableFuture registerActions(Map context, Map params) { - Map message; - try { - message = withContext(context, params); - } catch (PluginSdkError error) { - return failed(error); - } - return channel.subscribe(Protocol.HOST_EDITOR_REGISTER_ACTIONS, message, null, scope); - } - } - - /** HTML previews (protocol 3). */ - public final class Preview { - private Preview() {} - - /** {@code params}: HTML {@code resource, presentation?, range?}. */ - public CompletableFuture> openHtml(Map context, Map params) { - return scoped(Protocol.HOST_PREVIEW_OPEN_HTML, context, params); - } - } - - /** The system browser (protocol 3). */ - public final class Browser { - private Browser() {} - - /** {@code params}: exactly one of an HTTP(S) {@code url} or an HTML {@code resource}. */ - public CompletableFuture> openExternal(Map context, Map params) { - return scoped(Protocol.HOST_BROWSER_OPEN_EXTERNAL, context, params); - } - } - - /** Native terminals private to the backend session and workspace (protocol 3). */ - public final class Terminal { - private Terminal() {} - /** Params: executable, arguments?, title?, cwd?, environment?, show?. */ - public CompletableFuture> create(Map context, Map params) { - return scoped(Protocol.HOST_TERMINAL_CREATE, context, params); - } - public CompletableFuture> show(Map context, Map params) { - return scoped(Protocol.HOST_TERMINAL_SHOW, context, params); - } - public CompletableFuture> close(Map context, Map params) { - return scoped(Protocol.HOST_TERMINAL_CLOSE, context, params); - } - /** Restarts the saved argv, restoring only the chosen plain display suffix. */ - public CompletableFuture> reopen(Map context, Map params) { - return scoped(Protocol.HOST_TERMINAL_REOPEN, context, params); - } - /** Forgets the handle and its retained display history. */ - public CompletableFuture> dispose(Map context, Map params) { - return scoped(Protocol.HOST_TERMINAL_DISPOSE, context, params); - } - /** Params: terminalID; disposing the subscription does not close the terminal. */ - public CompletableFuture onExit(Map context, Map params) { - Map message; - try { message = withContext(context, params); } - catch (PluginSdkError error) { return failed(error); } - return channel.subscribe(Protocol.HOST_TERMINAL_ON_EXIT, message, null, scope); - } - } - - /** - * Messages in the window (protocol 3). {@code params}: {@code text, - * actions?}; answers {@code { selectedIndex }}, null on dismissal. - */ - public final class Window { - private Window() {} - - public CompletableFuture> showInformation(Map context, Map params) { - return scoped(Protocol.HOST_WINDOW_SHOW_INFORMATION, context, params); - } - - public CompletableFuture> showWarning(Map context, Map params) { - return scoped(Protocol.HOST_WINDOW_SHOW_WARNING, context, params); - } - - public CompletableFuture> showError(Map context, Map params) { - return scoped(Protocol.HOST_WINDOW_SHOW_ERROR, context, params); - } - } - - /** A method whose params name a workspace context. */ - private CompletableFuture> scoped(String method, Map context, Map params) { - Map message; - try { - message = withContext(context, params); - } catch (PluginSdkError error) { - return failed(error); - } - return object(method, channel.request(method, message, scope)); - } - - private static Map withContext(Map context, Map params) { - Map message = params == null ? new LinkedHashMap() : new LinkedHashMap(params); - message.put("context", contextReference(context)); - return message; - } - - /** The result as an object, or null; anything else is a host bug. */ - private static CompletableFuture> object(String method, CompletableFuture response) { - return response.thenApply(result -> { - if (result == null) { - return null; - } - if (!(result instanceof Map)) { - throw new PluginSdkError("sdk.host.invalidResult", method + " answered with something other than an object."); - } - return Json.object(result); - }); - } - - private static Map params(String key, Object value) { - Map params = new LinkedHashMap<>(); - params.put(key, value); - return params; - } - - private static PluginSdkError invalidKey() { - return new PluginSdkError("sdk.credentials.invalidKey", - "A credential key is 1-128 ASCII letters, digits, \".\", \"_\", \":\" or \"-\"."); - } - - private static CompletableFuture failed(Throwable error) { - CompletableFuture future = new CompletableFuture<>(); - future.completeExceptionally(error); - return future; - } -} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostChannel.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostChannel.java deleted file mode 100644 index 274fbd4..0000000 --- a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostChannel.java +++ /dev/null @@ -1,504 +0,0 @@ -package io.github.litheidea.plugin.sdk; - -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionException; -import java.util.concurrent.RejectedExecutionException; - -/** - * The session's host-request state for plugin-function protocols 2 and 3. The - * backend owns the wire; this class owns what Core expects of a well-behaved - * client -- at most 16 unanswered host requests, cancellation through - * {@code $/cancelRequest} from version 3, and subscription events routed by - * ID, in order, off the reader thread. - * - *

Contract: {@code contract/v1/README.md}, "Host services (protocol - * version 2)" and the version 3 sections after it. - */ -final class HostChannel { - /** Events kept for a subscription whose creating request is still unanswered. */ - static final int MAX_EARLY_EVENTS = 128; - - /** The backend's wire. */ - interface Transport { - /** The negotiated plugin-function version, or 0 before or without one. */ - int version(); - - boolean ready(); - - /** Writes a request; its response settles when the host answers or the session ends. */ - Sent send(String method, Object params); - - void notify(String method, Object params); - - void log(String message); - - void log(String message, Throwable error); - - /** Runs plugin code off the reader thread. */ - void execute(Runnable task); - } - - /** A request on the wire. */ - static final class Sent { - final String id; - final CompletableFuture response; - - Sent(String id, CompletableFuture response) { - this.id = id; - this.response = response; - } - } - - private enum State { QUEUED, SENDING, SENT } - - /** One host request; settles for its caller once. */ - private static final class Entry { - final String method; - final Object params; - final CompletableFuture future = new CompletableFuture<>(); - final List registrations = new ArrayList<>(); - State state = State.QUEUED; - boolean settled; - /** Cancelled while being written: {@code $/cancelRequest} follows the write. */ - boolean cancelAfterWrite; - String id; - - Entry(String method, Object params) { - this.method = method; - this.params = params; - } - } - - /** A live subscription. */ - private static final class Route { - final String id; - final Host.Listener listener; - final ArrayDeque pending = new ArrayDeque<>(); - volatile boolean live = true; - long lastSequence; - boolean draining; - - Route(String id, Host.Listener listener) { - this.id = id; - this.listener = listener; - } - - boolean isLive() { - return live; - } - } - - private static final class Early { - final String subscriptionId; - final long sequence; - final Object event; - - Early(String subscriptionId, long sequence, Object event) { - this.subscriptionId = subscriptionId; - this.sequence = sequence; - this.event = event; - } - } - - private final Transport transport; - private final Object lock = new Object(); - private final ArrayDeque queue = new ArrayDeque<>(); - private final Map routes = new HashMap<>(); - private final List early = new ArrayList<>(); - private int inFlight; - /** Subscribing requests not yet answered; early events wait only while there are some. */ - private int subscribing; - private CompletableFuture> capabilities; - private boolean closed; - - HostChannel(Transport transport) { - this.transport = transport; - } - - int version() { - return transport.version(); - } - - /** - * Sends {@code method} once a slot is free. Cancelling any of - * {@code scope} rejects the caller at once with {@link CancelledException}; - * a request already sent is cancelled on the wire from version 3, and never - * sent again, because a cancelled mutation may already have taken effect. - */ - CompletableFuture request(String method, Object params, List scope) { - if (method == null || !method.startsWith(Protocol.HOST_PREFIX)) { - return failed(new PluginSdkError("sdk.host.method", - method + " is not a host method; host requests are lithe/host/*.")); - } - if (!open()) { - return failed(notReady()); - } - if (transport.version() < Protocol.HOST_SERVICES_VERSION) { - // The answer Core would give, without the round trip. - return failed(unavailable(method, - "The host did not negotiate plugin-function protocol 2 or later, which offers host services.")); - } - for (Cancellation cancellation : scope) { - try { - cancellation.throwIfCancelled(); - } catch (CancelledException error) { - return failed(error); - } - } - Entry entry = new Entry(method, params); - synchronized (lock) { - if (closed || !transport.ready()) { - return failed(notReady()); - } - queue.add(entry); - } - for (Cancellation cancellation : scope) { - Cancellation.Registration registration = cancellation.onCancel(() -> cancel(entry, cancellation)); - boolean settled; - synchronized (lock) { - settled = entry.settled; - if (!settled) { - entry.registrations.add(registration); - } - } - if (settled) { - registration.remove(); - } - } - drain(); - return entry.future; - } - - /** - * Sends a request whose result is {@code { subscriptionID }} and routes - * that subscription's events to {@code listener}, one at a time and in the - * order the host sent them. - */ - CompletableFuture subscribe(String method, Object params, Host.Listener listener, - List scope) { - synchronized (lock) { - subscribing++; - } - return request(method, params, scope).handle((result, error) -> { - try { - if (error != null) { - throw new CompletionException(Backend.unwrap(error)); - } - Object id = result instanceof Map ? ((Map) result).get("subscriptionID") : null; - if (!(id instanceof String) || !Protocol.isCredentialKey((String) id)) { - throw new PluginSdkError("sdk.host.invalidResult", method + " answered without a subscriptionID."); - } - String subscriptionId = (String) id; - Route route = new Route(subscriptionId, listener); - synchronized (lock) { - if (closed) { - throw new PluginSdkError("sdk.session.closed", "The session ended."); - } - routes.put(subscriptionId, route); - // Events the host sent before this answer was read. - for (Iterator events = early.iterator(); events.hasNext();) { - Early event = events.next(); - if (event.subscriptionId.equals(subscriptionId)) { - events.remove(); - emit(route, event.sequence, event.event); - } - } - } - return new Host.Subscription(subscriptionId, route::isLive, this); - } finally { - synchronized (lock) { - subscribing--; - if (subscribing == 0) { - early.clear(); - } - } - } - }); - } - - /** Stops routing a subscription's events at once and asks the host to dispose it. */ - CompletableFuture dispose(String subscriptionId) { - synchronized (lock) { - Route route = routes.remove(subscriptionId); - if (route != null) { - route.live = false; - route.pending.clear(); - } - if (closed || !transport.ready()) { - return CompletableFuture.completedFuture(null); - } - } - Map params = new LinkedHashMap<>(); - params.put("subscriptionID", subscriptionId); - return request(Protocol.HOST_SUBSCRIPTIONS_DISPOSE, params, Collections.emptyList()) - .thenApply(result -> null); - } - - /** Routes one {@code lithe/host/subscriptions/notify}. */ - void deliver(Map params) { - Object id = params.get("subscriptionID"); - if (!(id instanceof String)) { - return; - } - Object number = params.get("sequence"); - long sequence = number instanceof Number ? ((Number) number).longValue() : 0; - synchronized (lock) { - Route route = routes.get(id); - if (route != null) { - emit(route, sequence, params.get("event")); - } else if (subscribing > 0) { - if (early.size() < MAX_EARLY_EVENTS) { - early.add(new Early((String) id, sequence, params.get("event"))); - } else { - transport.log("Dropped an early subscription event: queue_full"); - } - } - // Otherwise the subscription was disposed; nothing follows a disposal. - } - } - - /** The cached {@code getCapabilities} answer; Core answers it itself, from version 3. */ - CompletableFuture> capabilities() { - if (transport.version() < Protocol.CONTEXT_VERSION) { - return failed(unavailable(Protocol.HOST_GET_CAPABILITIES, - "Capability discovery needs plugin-function protocol 3.")); - } - CompletableFuture> answer; - synchronized (lock) { - if (capabilities != null) { - return capabilities.thenApply(result -> result); - } - answer = new CompletableFuture<>(); - capabilities = answer; - } - request(Protocol.HOST_GET_CAPABILITIES, null, Collections.emptyList()).whenComplete((result, error) -> { - if (error == null && result instanceof Map) { - answer.complete(Collections.unmodifiableMap(Json.object(result))); - return; - } - synchronized (lock) { - if (capabilities == answer) { - capabilities = null; - } - } - answer.completeExceptionally(error != null ? Backend.unwrap(error) - : new PluginSdkError("sdk.host.invalidResult", "getCapabilities answered without an object.")); - }); - return answer.thenApply(result -> result); - } - - /** - * Whether this session may call {@code method}. From version 3 the answer - * comes from {@code getCapabilities}; version 2 has no discovery, so it - * reports the methods version 2 defines, and a missing grant still fails - * the request. - */ - CompletableFuture supports(String method) { - if (transport.version() >= Protocol.CONTEXT_VERSION) { - return capabilities().thenApply(answer -> { - Object services = answer.get("services"); - if (!(services instanceof Map)) { - return false; - } - for (Object service : ((Map) services).values()) { - Object methods = service instanceof Map ? ((Map) service).get("methods") : null; - if (methods instanceof List && ((List) methods).contains(method)) { - return true; - } - } - return false; - }); - } - return CompletableFuture.completedFuture(transport.version() >= Protocol.HOST_SERVICES_VERSION - && (Protocol.HOST_CREDENTIALS_GET.equals(method) - || Protocol.HOST_CREDENTIALS_SET.equals(method) - || Protocol.HOST_CREDENTIALS_DELETE.equals(method))); - } - - /** Ends the channel with the session: queued requests fail, subscriptions end. */ - void close() { - List queued; - synchronized (lock) { - closed = true; - queued = new ArrayList<>(queue); - queue.clear(); - for (Route route : routes.values()) { - route.live = false; - route.pending.clear(); - } - routes.clear(); - early.clear(); - capabilities = null; - } - for (Entry entry : queued) { - settle(entry, null, new PluginSdkError("sdk.session.closed", "The session ended.")); - } - } - - private void drain() { - List starting = new ArrayList<>(); - synchronized (lock) { - while (!closed && inFlight < Protocol.MAX_PENDING_HOST_REQUESTS && !queue.isEmpty()) { - Entry entry = queue.poll(); - entry.state = State.SENDING; - inFlight++; - starting.add(entry); - } - } - for (Entry entry : starting) { - start(entry); - } - } - - /** Writes outside the lock, so a full pipe never blocks the reader thread's routing. */ - private void start(Entry entry) { - Sent sent; - try { - sent = transport.send(entry.method, entry.params); - } catch (RuntimeException error) { - // Params JSON cannot encode never reached the wire. - synchronized (lock) { - inFlight--; - } - settle(entry, null, error); - drain(); - return; - } - boolean cancelNow; - synchronized (lock) { - entry.id = sent.id; - entry.state = State.SENT; - cancelNow = entry.cancelAfterWrite; - } - if (cancelNow) { - transport.notify(Protocol.CANCEL_REQUEST, Collections.singletonMap("id", sent.id)); - } - sent.response.whenComplete((result, error) -> { - synchronized (lock) { - // The slot frees when Core answers, also after a cancellation: - // from version 3 Core answers it at once, before version 3 the - // host still finishes the request. - inFlight--; - } - settle(entry, result, error == null ? null : Backend.unwrap(error)); - drain(); - }); - } - - private void cancel(Entry entry, Cancellation cancellation) { - String id = null; - synchronized (lock) { - if (entry.settled) { - return; - } - if (entry.state == State.QUEUED) { - queue.remove(entry); - } else if (transport.version() >= Protocol.CONTEXT_VERSION) { - if (entry.state == State.SENDING) { - entry.cancelAfterWrite = true; - } else { - id = entry.id; - } - } - } - if (id != null) { - transport.notify(Protocol.CANCEL_REQUEST, Collections.singletonMap("id", id)); - } - settle(entry, null, new CancelledException(cancellation.reason())); - } - - /** Completes the caller's future once, on a handler thread. */ - private void settle(Entry entry, Object result, Throwable error) { - List registrations; - synchronized (lock) { - if (entry.settled) { - return; - } - entry.settled = true; - registrations = new ArrayList<>(entry.registrations); - entry.registrations.clear(); - } - for (Cancellation.Registration registration : registrations) { - registration.remove(); - } - Runnable complete = () -> { - if (error != null) { - entry.future.completeExceptionally(error); - } else { - entry.future.complete(result); - } - }; - try { - transport.execute(complete); - } catch (RejectedExecutionException ended) { - complete.run(); - } - } - - /** Queues one event; called with the lock held. */ - private void emit(Route route, long sequence, Object event) { - boolean gap = sequence != route.lastSequence + 1; - route.lastSequence = sequence; - route.pending.add(new Host.Event(route.id, sequence, gap, event)); - if (route.draining) { - return; - } - route.draining = true; - try { - transport.execute(() -> run(route)); - } catch (RejectedExecutionException ended) { - route.draining = false; - route.pending.clear(); - } - } - - /** Hands a subscription's events to its listener one at a time. */ - private void run(Route route) { - while (true) { - Host.Event event; - synchronized (lock) { - event = route.live ? route.pending.poll() : null; - if (event == null) { - route.draining = false; - route.pending.clear(); - return; - } - } - try { - if (route.listener != null) { - route.listener.onEvent(event); - } - } catch (Throwable error) { - transport.log("A subscription listener failed:", error); - } - } - } - - private boolean open() { - synchronized (lock) { - return !closed && transport.ready(); - } - } - - private static PluginSdkError notReady() { - return new PluginSdkError("sdk.session.notReady", "The session is not initialized."); - } - - private static HostError unavailable(String method, String message) { - return new HostError("plugin.host.unavailable", message, Protocol.METHOD_NOT_FOUND, null, method); - } - - private static CompletableFuture failed(Throwable error) { - CompletableFuture future = new CompletableFuture<>(); - future.completeExceptionally(error); - return future; - } -} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostError.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostError.java deleted file mode 100644 index dbd452c..0000000 --- a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostError.java +++ /dev/null @@ -1,96 +0,0 @@ -package io.github.litheidea.plugin.sdk; - -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; - -/** - * The host refused or failed a request this backend sent. {@link #code()} is - * the stable {@code error.data.code}, such as {@code plugin.host.contextExpired}; - * {@link #rpcCode()} the JSON-RPC number; {@link #details()} the object a - * version 3 host may add, such as {@code { option }} or - * {@code { retryAfterMilliseconds }}. - */ -public final class HostError extends PluginSdkError { - private static final long serialVersionUID = 1L; - - /** - * Stable host failure codes of plugin-function protocol 3 and their - * JSON-RPC numbers. A later host adds codes after {@code -32021}. - */ - public static final Map CODES; - private static final Map BY_RPC_CODE; - - static { - Map codes = new LinkedHashMap<>(); - codes.put("plugin.host.unavailable", -32601); - codes.put("plugin.host.invalidParams", -32602); - codes.put("plugin.host.failed", -32603); - codes.put("plugin.host.cancelled", -32800); - codes.put("plugin.host.permissionDenied", -32010); - codes.put("plugin.host.contextExpired", -32011); - codes.put("plugin.host.authorityUnsupported", -32012); - codes.put("plugin.host.versionConflict", -32013); - codes.put("plugin.host.limitExceeded", -32014); - codes.put("plugin.host.timeout", -32015); - codes.put("plugin.host.notFound", -32016); - codes.put("plugin.host.readOnly", -32017); - codes.put("plugin.host.unsupportedOption", -32018); - codes.put("plugin.host.preconditionFailed", -32019); - codes.put("plugin.host.busy", -32020); - codes.put("plugin.host.rateLimited", -32021); - CODES = Collections.unmodifiableMap(codes); - Map byNumber = new HashMap<>(); - for (Map.Entry entry : codes.entrySet()) { - byNumber.put(entry.getValue(), entry.getKey()); - } - BY_RPC_CODE = Collections.unmodifiableMap(byNumber); - } - - private final transient Map details; - private final String method; - - public HostError(String code, String message, Integer rpcCode, Map details, String method) { - super(code, message, rpcCode); - this.details = details == null ? null : Collections.unmodifiableMap(new LinkedHashMap<>(details)); - this.method = method; - } - - /** The failure's {@code error.data.details}, or null when the host sent none. */ - public Map details() { - return details; - } - - /** The request that failed. */ - public String method() { - return method; - } - - /** - * The failure for a JSON-RPC error answer. A host method without a known - * code is a host failure: from version 3 a number names one code, and an - * unknown number is {@code plugin.host.failed}. - */ - static HostError fromResponse(String method, Map error) { - Object data = error.get("data"); - Map fields = data instanceof Map ? Json.object(data) : Collections.emptyMap(); - Object rpcCode = error.get("code"); - Integer number = rpcCode instanceof Number && ((Number) rpcCode).doubleValue() == ((Number) rpcCode).intValue() - ? ((Number) rpcCode).intValue() - : null; - String code = Json.string(fields, "code"); - if (code == null) { - if (method.startsWith(Protocol.HOST_PREFIX)) { - String known = number == null ? null : BY_RPC_CODE.get(number); - code = known == null ? "plugin.host.failed" : known; - } else { - code = "sdk.host.error"; - } - } - Object details = fields.get("details"); - String text = Json.string(error, "message"); - return new HostError(code, text == null ? method + " failed." : text, number, - details instanceof Map ? Json.object(details) : null, method); - } -} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Json.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Json.java deleted file mode 100644 index 64ff3f5..0000000 --- a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Json.java +++ /dev/null @@ -1,426 +0,0 @@ -package io.github.litheidea.plugin.sdk; - -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -/** - * Minimal JSON reader and writer for protocol messages and stored state. - * - *

The SDK carries its own codec so that a plugin can shade it next to any - * JSON library without version conflicts. Values map to plain Java types: - * objects to {@code Map} (insertion-ordered), arrays to - * {@code List}, strings to {@code String}, booleans to - * {@code Boolean}, {@code null} to {@code null}, integers to {@code Long} (or - * {@code BigInteger} beyond its range), and other numbers to {@code Double}. - */ -public final class Json { - /** Deeper input is refused instead of overflowing the reader's stack. */ - private static final int MAX_DEPTH = 512; - - private Json() {} - - /** A value that is not JSON, or one JSON cannot represent. */ - public static final class JsonException extends RuntimeException { - private static final long serialVersionUID = 1L; - - public JsonException(String message) { - super(message); - } - } - - /** Parses one JSON document; trailing content other than whitespace is an error. */ - public static Object parse(String text) { - Reader reader = new Reader(text); - reader.skipWhitespace(); - Object value = reader.value(0); - reader.skipWhitespace(); - if (reader.position != text.length()) { - throw reader.error("Unexpected content after the value"); - } - return value; - } - - /** - * Encodes {@code value}. Maps need string keys; numbers must be finite. - * Arrays of objects and any {@link Collection} encode as JSON arrays. - */ - public static String stringify(Object value) { - StringBuilder output = new StringBuilder(); - write(output, value, 0); - return output.toString(); - } - - /** {@code value} as an object, or an empty map when it is {@code null}. */ - @SuppressWarnings("unchecked") - public static Map object(Object value) { - if (value == null) { - return new LinkedHashMap<>(); - } - if (value instanceof Map) { - return (Map) value; - } - throw new JsonException("Expected a JSON object."); - } - - /** The string at {@code key}, or {@code null} when it is missing or not a string. */ - public static String string(Map object, String key) { - Object value = object.get(key); - return value instanceof String ? (String) value : null; - } - - private static void write(StringBuilder output, Object value, int depth) { - if (depth > MAX_DEPTH) { - throw new JsonException("The value is nested too deeply, or contains itself."); - } - if (value == null) { - output.append("null"); - } else if (value instanceof String || value instanceof Character) { - quote(output, value.toString()); - } else if (value instanceof Boolean) { - output.append(value.toString()); - } else if (value instanceof Double || value instanceof Float) { - output.append(decimal(((Number) value).doubleValue())); - } else if (value instanceof Long || value instanceof Integer || value instanceof Short - || value instanceof Byte || value instanceof BigInteger) { - output.append(value.toString()); - } else if (value instanceof BigDecimal) { - output.append(((BigDecimal) value).toString()); - } else if (value instanceof Map) { - output.append('{'); - boolean first = true; - for (Map.Entry entry : ((Map) value).entrySet()) { - if (!(entry.getKey() instanceof String)) { - throw new JsonException("Object keys must be strings."); - } - if (!first) { - output.append(','); - } - first = false; - quote(output, (String) entry.getKey()); - output.append(':'); - write(output, entry.getValue(), depth + 1); - } - output.append('}'); - } else if (value instanceof Collection) { - writeArray(output, ((Collection) value).toArray(), depth); - } else if (value instanceof Object[]) { - writeArray(output, (Object[]) value, depth); - } else { - throw new JsonException("A " + value.getClass().getName() + " is not a JSON value."); - } - } - - private static void writeArray(StringBuilder output, Object[] values, int depth) { - output.append('['); - for (int index = 0; index < values.length; index++) { - if (index > 0) { - output.append(','); - } - write(output, values[index], depth + 1); - } - output.append(']'); - } - - private static String decimal(double value) { - if (Double.isNaN(value) || Double.isInfinite(value)) { - throw new JsonException("JSON has no representation for " + value + "."); - } - // Integral values print without a fraction, as JavaScript prints them. - if (value == Math.rint(value) && Math.abs(value) < 1e15) { - return Long.toString((long) value); - } - return Double.toString(value); - } - - private static void quote(StringBuilder output, String text) { - output.append('"'); - for (int index = 0; index < text.length(); index++) { - char character = text.charAt(index); - switch (character) { - case '"': - output.append("\\\""); - break; - case '\\': - output.append("\\\\"); - break; - case '\n': - output.append("\\n"); - break; - case '\r': - output.append("\\r"); - break; - case '\t': - output.append("\\t"); - break; - case '\b': - output.append("\\b"); - break; - case '\f': - output.append("\\f"); - break; - default: - if (character < 0x20 || isLoneSurrogate(text, index)) { - // A lone surrogate has no UTF-8 encoding; escaping it - // keeps the frame valid, as JSON.stringify does. - output.append(String.format("\\u%04x", (int) character)); - } else { - output.append(character); - } - } - } - output.append('"'); - } - - private static boolean isLoneSurrogate(String text, int index) { - char character = text.charAt(index); - if (Character.isHighSurrogate(character)) { - return index + 1 >= text.length() || !Character.isLowSurrogate(text.charAt(index + 1)); - } - if (Character.isLowSurrogate(character)) { - return index == 0 || !Character.isHighSurrogate(text.charAt(index - 1)); - } - return false; - } - - private static final class Reader { - private final String text; - private int position; - - Reader(String text) { - this.text = text; - } - - Object value(int depth) { - if (depth > MAX_DEPTH) { - throw error("The document is nested too deeply"); - } - if (position >= text.length()) { - throw error("Unexpected end of input"); - } - char character = text.charAt(position); - switch (character) { - case '{': - return object(depth); - case '[': - return array(depth); - case '"': - return string(); - case 't': - return literal("true", Boolean.TRUE); - case 'f': - return literal("false", Boolean.FALSE); - case 'n': - return literal("null", null); - default: - if (character == '-' || (character >= '0' && character <= '9')) { - return number(); - } - throw error("Unexpected character"); - } - } - - private Map object(int depth) { - Map result = new LinkedHashMap<>(); - position++; - skipWhitespace(); - if (peek() == '}') { - position++; - return result; - } - for (;;) { - skipWhitespace(); - if (peek() != '"') { - throw error("Expected a property name"); - } - String key = string(); - skipWhitespace(); - expect(':'); - skipWhitespace(); - result.put(key, value(depth + 1)); - skipWhitespace(); - char next = peek(); - position++; - if (next == '}') { - return result; - } - if (next != ',') { - throw error("Expected ',' or '}'"); - } - } - } - - private List array(int depth) { - List result = new ArrayList<>(); - position++; - skipWhitespace(); - if (peek() == ']') { - position++; - return result; - } - for (;;) { - skipWhitespace(); - result.add(value(depth + 1)); - skipWhitespace(); - char next = peek(); - position++; - if (next == ']') { - return result; - } - if (next != ',') { - throw error("Expected ',' or ']'"); - } - } - } - - private String string() { - position++; - StringBuilder result = new StringBuilder(); - for (;;) { - if (position >= text.length()) { - throw error("Unterminated string"); - } - char character = text.charAt(position++); - if (character == '"') { - return result.toString(); - } - if (character < 0x20) { - throw error("Control character in string"); - } - if (character != '\\') { - result.append(character); - continue; - } - if (position >= text.length()) { - throw error("Unterminated escape"); - } - char escape = text.charAt(position++); - switch (escape) { - case '"': - case '\\': - case '/': - result.append(escape); - break; - case 'b': - result.append('\b'); - break; - case 'f': - result.append('\f'); - break; - case 'n': - result.append('\n'); - break; - case 'r': - result.append('\r'); - break; - case 't': - result.append('\t'); - break; - case 'u': - if (position + 4 > text.length()) { - throw error("Incomplete unicode escape"); - } - int code = 0; - for (int index = 0; index < 4; index++) { - int digit = Character.digit(text.charAt(position++), 16); - if (digit < 0) { - throw error("Invalid unicode escape"); - } - code = code * 16 + digit; - } - result.append((char) code); - break; - default: - throw error("Invalid escape"); - } - } - } - - private Object number() { - int start = position; - if (peek() == '-') { - position++; - } - if (peek() == '0') { - position++; - } else if (isDigit(peek())) { - digits(); - } else { - throw error("Invalid number"); - } - boolean integral = true; - if (peek() == '.') { - integral = false; - position++; - if (!isDigit(peek())) { - throw error("Invalid number"); - } - digits(); - } - if (peek() == 'e' || peek() == 'E') { - integral = false; - position++; - if (peek() == '+' || peek() == '-') { - position++; - } - if (!isDigit(peek())) { - throw error("Invalid number"); - } - digits(); - } - String literal = text.substring(start, position); - if (integral) { - BigInteger value = new BigInteger(literal); - return value.bitLength() < 64 ? (Object) value.longValue() : value; - } - return Double.parseDouble(literal); - } - - private void digits() { - while (isDigit(peek())) { - position++; - } - } - - private Object literal(String word, Object value) { - if (!text.startsWith(word, position)) { - throw error("Unexpected literal"); - } - position += word.length(); - return value; - } - - private void expect(char character) { - if (peek() != character) { - throw error("Expected '" + character + "'"); - } - position++; - } - - private char peek() { - return position < text.length() ? text.charAt(position) : '\0'; - } - - void skipWhitespace() { - while (position < text.length()) { - char character = text.charAt(position); - if (character != ' ' && character != '\t' && character != '\n' && character != '\r') { - return; - } - position++; - } - } - - JsonException error(String message) { - return new JsonException(message + " at offset " + position + "."); - } - - private static boolean isDigit(char character) { - return character >= '0' && character <= '9'; - } - } -} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginError.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginError.java deleted file mode 100644 index c7e83b3..0000000 --- a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginError.java +++ /dev/null @@ -1,38 +0,0 @@ -package io.github.litheidea.plugin.sdk; - -/** - * A failure a handler reports on purpose. Core ends the call with the stable - * {@code plugin.function.failed} code and forwards {@link #code()} as - * {@code pluginErrorCode}, so the plugin's own UI can tell its failures apart. - * Lithe never branches on it. - * - *

The message is shown to the user as written (Core keeps its first 1024 - * bytes), so it must not contain stack traces or machine paths. - */ -public class PluginError extends RuntimeException { - private static final long serialVersionUID = 1L; - - private final String code; - - /** - * @param code identifier of at most 64 bytes, such as {@code maven.snapshotLocked} - * @param message user-facing text - */ - public PluginError(String code, String message) { - this(code, message, null); - } - - /** As {@link #PluginError(String, String)}; {@code cause} stays in memory, outside automatic diagnostics. */ - public PluginError(String code, String message, Throwable cause) { - super(message, cause); - if (!Protocol.isPluginErrorCode(code)) { - throw new IllegalArgumentException("Plugin error code \"" + code - + "\" must start with a letter, use letters, digits, \".\", \"_\" or \"-\", and be at most 64 bytes."); - } - this.code = code; - } - - public String code() { - return code; - } -} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginSdkError.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginSdkError.java deleted file mode 100644 index 043ba52..0000000 --- a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginSdkError.java +++ /dev/null @@ -1,32 +0,0 @@ -package io.github.litheidea.plugin.sdk; - -/** - * An SDK usage error raised to the plugin author, or a failure the host - * reported for a request this backend sent. {@link #rpcCode()} carries the - * host's JSON-RPC error code in the latter case. - */ -public class PluginSdkError extends RuntimeException { - private static final long serialVersionUID = 1L; - - private final String code; - private final Integer rpcCode; - - public PluginSdkError(String code, String message) { - this(code, message, null); - } - - public PluginSdkError(String code, String message, Integer rpcCode) { - super(message); - this.code = code; - this.rpcCode = rpcCode; - } - - public String code() { - return code; - } - - /** The host's JSON-RPC error code, or {@code null} for a local usage error. */ - public Integer rpcCode() { - return rpcCode; - } -} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Processes.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Processes.java deleted file mode 100644 index 6764cca..0000000 --- a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Processes.java +++ /dev/null @@ -1,629 +0,0 @@ -package io.github.litheidea.plugin.sdk; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.CharsetDecoder; -import java.nio.charset.CodingErrorAction; -import java.nio.charset.StandardCharsets; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; -import java.util.function.Consumer; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -/** - * Child processes a backend starts for one call. - * - *

Lithe's host offers no process capability in protocol version 1, so a - * backend runs its tools itself; this helper makes sure that the call ending, - * cancelling it, or the backend shutting down also ends the tools it started. - * - *

Process trees: on macOS and Linux every tool leads its own process group, - * as in the Node SDK, on every Java version. Java has no API for that, so the - * tool starts through the system {@code perl}, which calls {@code setpgrp} and - * then replaces itself with the tool, keeping its PID. A stop signals the whole - * group, and once the tool exits on its own the members it left behind, such - * as a background worker, are killed too; descendants that leave the group - * with {@code setsid} are out of reach. Windows, and a system without - * {@code perl}, fall back to {@code ProcessHandle} on Java 9 and newer, found - * by reflection so the SDK still loads on Java 8; it reaches only the - * descendants still attached to the tool. Lithe starts every backend inside - * its own process scope ({@code LITHE_PLUGIN_BACKEND_SCOPE}) and ends whatever - * is left of it when the session ends; that remains the final boundary. - */ -public final class Processes { - /** - * Variables Lithe sets on the backend so it can find and end every process - * the backend started, even one that left its parent. A tool always - * inherits them, also when the plugin replaces the environment. - */ - static final String[] HOST_MARKERS = {"LITHE_PROCESS_SCOPE", "LITHE_PLUGIN_BACKEND_SCOPE"}; - - /** Every tool started through {@link #run} that has not exited or been stopped. */ - private static final Set RUNNING = Collections.newSetFromMap(new ConcurrentHashMap<>()); - - private static final ScheduledExecutorService TIMERS = Executors.newSingleThreadScheduledExecutor(runnable -> { - Thread thread = new Thread(runnable, "lithe-sdk-process-timer"); - thread.setDaemon(true); - return thread; - }); - - private static final ProcessTree TREE = ProcessTree.load(); - - private static final ProcessGroups GROUPS = ProcessGroups.load(); - - private Processes() {} - - /** Options of one {@link #run}; every setter returns this object. */ - public static final class Options { - private Path directory; - private Map environment; - private Cancellation cancellation; - private int maxOutputBytes = 1 << 20; - private long killGraceMillis = 2000; - private Consumer onStdout; - private Consumer onStderr; - private Runnable listenerFailure = () -> {}; - - /** Working directory; defaults to the backend's. */ - public Options directory(Path value) { - directory = value; - return this; - } - - /** Replaces the environment; the host's process markers are carried over regardless. */ - public Options environment(Map value) { - environment = value; - return this; - } - - /** Cancelling it stops the tool and makes {@link #run} throw {@link CancelledException}. */ - public Options cancellation(Cancellation value) { - cancellation = value; - return this; - } - - /** Captured bytes per stream; default 1 MiB. Listeners still see everything. */ - public Options maxOutputBytes(int value) { - maxOutputBytes = value; - return this; - } - - /** Delay between the polite and the forced stop; default 2000. */ - public Options killGraceMillis(long value) { - killGraceMillis = value; - return this; - } - - /** Receives stdout as it arrives, decoded as UTF-8 without splitting characters. */ - public Options onStdout(Consumer value) { - onStdout = value; - return this; - } - - /** Receives stderr as it arrives, decoded as UTF-8 without splitting characters. */ - public Options onStderr(Consumer value) { - onStderr = value; - return this; - } - - Options listenerFailure(Runnable value) { listenerFailure = value; return this; } - - Cancellation cancellation() { - return cancellation; - } - - Options copy() { - Options copy = new Options(); - copy.directory = directory; - copy.environment = environment; - copy.cancellation = cancellation; - copy.maxOutputBytes = maxOutputBytes; - copy.killGraceMillis = killGraceMillis; - copy.onStdout = onStdout; - copy.onStderr = onStderr; - copy.listenerFailure = listenerFailure; - return copy; - } - } - - /** Exit status and captured output of a tool. */ - public static final class Result { - private final int exitCode; - private final String stdout; - private final String stderr; - private final boolean truncated; - - Result(int exitCode, String stdout, String stderr, boolean truncated) { - this.exitCode = exitCode; - this.stdout = stdout; - this.stderr = stderr; - this.truncated = truncated; - } - - /** The exit code; on POSIX a tool ended by signal N reports 128 + N. */ - public int exitCode() { - return exitCode; - } - - public String stdout() { - return stdout; - } - - public String stderr() { - return stderr; - } - - /** True when either stream exceeded {@code maxOutputBytes}. */ - public boolean truncated() { - return truncated; - } - } - - /** - * Runs {@code command} without a shell and returns its exit status and - * captured output. A non-zero exit returns normally; the caller decides - * what it means for its tool. Cancellation stops the tool and throws - * {@link CancelledException} once it ended. - */ - public static Result run(List command, Options options) throws IOException { - Options settings = options == null ? new Options() : options; - Cancellation cancellation = settings.cancellation; - if (cancellation != null) { - cancellation.throwIfCancelled(); - } - if (command.isEmpty()) { - throw new IllegalArgumentException("A command needs an executable."); - } - ProcessBuilder builder = new ProcessBuilder(new ArrayList<>(command)); - if (settings.directory != null) { - builder.directory(settings.directory.toFile()); - } - if (settings.environment != null) { - Map environment = builder.environment(); - environment.clear(); - environment.putAll(settings.environment); - for (String name : HOST_MARKERS) { - String value = System.getenv(name); - if (value == null) { - environment.remove(name); - } else { - environment.put(name, value); - } - } - } - boolean grouped = GROUPS.available(); - if (grouped) { - builder.command(GROUPS.launcher(command, builder.environment())); - } - Process process = builder.start(); - // Tools get no input; an open pipe would let one wait on it forever. - process.getOutputStream().close(); - Running entry = new Running(process, grouped ? GROUPS.leader(process) : 0); - RUNNING.add(entry); - Capture stdout = new Capture(process.getInputStream(), settings.maxOutputBytes, settings.onStdout, "stdout", settings.listenerFailure); - Capture stderr = new Capture(process.getErrorStream(), settings.maxOutputBytes, settings.onStderr, "stderr", settings.listenerFailure); - Cancellation.Registration registration = cancellation == null - ? () -> {} - : cancellation.onCancel(() -> entry.stop(settings.killGraceMillis)); - int exitCode; - try { - exitCode = waitFor(process, entry); - registration.remove(); - // The tool ended on its own; what it left running, such as a - // background worker, ends with it. A stopped tool stays registered - // until its forced stop, which reaches the same members. - entry.endLeftovers(); - // A descendant out of reach can keep the inherited pipes open after - // the tool exited; the output then ends at the grace period. - stdout.join(settings.killGraceMillis); - stderr.join(settings.killGraceMillis); - } finally { - registration.remove(); - if (!entry.stopping()) { - RUNNING.remove(entry); - } - } - if (cancellation != null) { - cancellation.throwIfCancelled(); - } - String errors = stderr.text(); - if (grouped && exitCode == ProcessGroups.EXEC_FAILED && errors.startsWith(ProcessGroups.EXEC_FAILURE)) { - // The launcher could not start the tool; report it as ProcessBuilder would. - throw new IOException("Cannot run program \"" + command.get(0) + "\": " - + errors.substring(ProcessGroups.EXEC_FAILURE.length()).trim()); - } - return new Result(exitCode, stdout.text(), errors, stdout.truncated() || stderr.truncated()); - } - - /** Runs {@code command} with default options. */ - public static Result run(List command) throws IOException { - return run(command, null); - } - - /** - * Forcibly ends every tool still running. The backend calls it on shutdown, - * on {@code exit}, and when the host closes stdin, so no tool outlives the - * session that started it. - */ - public static void killAll() { - for (Running entry : new ArrayList<>(RUNNING)) { - entry.forceStop(); - } - RUNNING.clear(); - } - - /** Number of tools still running or being stopped, for tests and diagnostics. */ - public static int runningCount() { - return RUNNING.size(); - } - - private static int waitFor(Process process, Running entry) { - boolean interrupted = false; - try { - for (;;) { - try { - return process.waitFor(); - } catch (InterruptedException error) { - // The tool still belongs to this call; end it before giving - // the interrupt back to the caller. - interrupted = true; - entry.forceStop(); - } - } - } finally { - if (interrupted) { - Thread.currentThread().interrupt(); - } - } - } - - /** One started tool and its stop state. */ - private static final class Running { - private final Process process; - /** The tool's process group, or 0 when it has none of its own. */ - private final long group; - private final Object lock = new Object(); - private boolean stopping; - private List tree = Collections.emptyList(); - private ScheduledFuture forceTimer; - - Running(Process process, long group) { - this.process = process; - this.group = group; - } - - /** Kills what the tool left after exiting on its own, unless a stop owns that. */ - void endLeftovers() { - synchronized (lock) { - if (stopping) { - return; - } - } - if (group > 0) { - // While any member lives the group ID cannot be reused, so this - // reaches only what this tool started; an empty group is ignored. - GROUPS.signal(group, true); - } else { - // Windows keeps the parent link of an exited tool, so its - // descendants are still found there. - TREE.destroy(TREE.descendants(process), true); - } - } - - boolean stopping() { - synchronized (lock) { - return stopping; - } - } - - /** Asks the tree to stop, then forces it after {@code graceMillis}. */ - void stop(long graceMillis) { - synchronized (lock) { - if (stopping) { - return; - } - stopping = true; - if (group > 0) { - GROUPS.signal(group, false); - } else { - // Descendants are listed before the tool is signalled: once - // it exits they are reparented and no longer reachable from it. - tree = TREE.descendants(process); - TREE.destroy(tree, false); - } - // Also covers a tool that has not formed its group yet. - process.destroy(); - forceTimer = TIMERS.schedule(this::forceStop, graceMillis, TimeUnit.MILLISECONDS); - } - } - - void forceStop() { - List known; - synchronized (lock) { - stopping = true; - if (forceTimer != null) { - forceTimer.cancel(false); - } - known = new ArrayList<>(tree); - if (group <= 0) { - known.addAll(TREE.descendants(process)); - } - } - if (group > 0) { - GROUPS.signal(group, true); - } - TREE.destroy(known, true); - process.destroyForcibly(); - RUNNING.remove(this); - } - } - - /** Reads one output stream on its own thread, keeping at most {@code limit} bytes. */ - private static final class Capture { - private final ByteArrayOutputStream kept = new ByteArrayOutputStream(); - private final InputStream input; - private final int limit; - private final Consumer listener; - private final Runnable listenerFailure; - private final CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder() - .onMalformedInput(CodingErrorAction.REPLACE) - .onUnmappableCharacter(CodingErrorAction.REPLACE); - private final Thread thread; - private volatile boolean truncated; - - Capture(InputStream input, int limit, Consumer listener, String name, Runnable listenerFailure) { - this.listenerFailure = listenerFailure; - this.input = input; - this.limit = limit; - this.listener = listener; - thread = new Thread(this::read, "lithe-sdk-" + name); - thread.setDaemon(true); - thread.start(); - } - - private void read() { - byte[] chunk = new byte[8192]; - // Holds a multi-byte character split across reads until it is whole. - ByteBuffer pending = ByteBuffer.allocate(chunk.length + 8); - try { - int count; - while ((count = input.read(chunk)) >= 0) { - synchronized (kept) { - int room = Math.max(0, limit - kept.size()); - kept.write(chunk, 0, Math.min(room, count)); - if (count > room) { - truncated = true; - } - } - if (listener != null) { - pending.put(chunk, 0, count); - pending.flip(); - deliver(pending, false); - pending.compact(); - } - } - if (listener != null) { - pending.flip(); - deliver(pending, true); - } - } catch (IOException error) { - // The stream was closed after the grace period; what was read is kept. - } - } - - private void deliver(ByteBuffer bytes, boolean end) { - CharBuffer characters = CharBuffer.allocate(bytes.remaining() + 1); - decoder.decode(bytes, characters, end); - if (end) { - decoder.flush(characters); - } - characters.flip(); - if (characters.hasRemaining()) { - try { - listener.accept(characters.toString()); - } catch (RuntimeException error) { - listenerFailure.run(); - } - } - } - - void join(long millis) { - try { - thread.join(Math.max(1, millis)); - if (thread.isAlive()) { - input.close(); - thread.join(millis); - } - } catch (InterruptedException error) { - Thread.currentThread().interrupt(); - } catch (IOException error) { - // Closing an output pipe that already failed changes nothing. - } - } - - String text() { - synchronized (kept) { - return new String(kept.toByteArray(), StandardCharsets.UTF_8); - } - } - - boolean truncated() { - return truncated; - } - } - - /** - * A process group per tool on macOS and Linux. The launcher is - * {@code perl -e SCRIPT -- command...}: it calls - * {@code setpgrp(0, 0)} and replaces itself with the tool, so the PID Java - * reports is the tool's and also its group ID. {@code PERL5OPT} would make - * perl load modules before the script runs, so it is withheld from perl and - * handed back to the tool. Signals go through {@code /bin/kill}, which - * Java 8 needs for a negative PID. - */ - private static final class ProcessGroups { - /** Exit code and stderr prefix of a launcher that could not start the tool. */ - static final int EXEC_FAILED = 127; - static final String EXEC_FAILURE = "lithe-sdk-exec-failed: "; - - private static final String SCRIPT = "my $has = shift; my $opt = shift;" - + " $ENV{PERL5OPT} = $opt if $has;" - + " setpgrp(0, 0);" - + " exec { $ARGV[0] } @ARGV;" - + " print STDERR '" + EXEC_FAILURE + "', \"$!\\n\"; exit " + EXEC_FAILED + ";"; - - /** A signal that has not run after this long is abandoned; the host scope remains. */ - private static final long SIGNAL_TIMEOUT_MILLIS = 2000; - - private final String perl; - private final String kill; - private final Method pid; - - private ProcessGroups(String perl, String kill, Method pid) { - this.perl = perl; - this.kill = kill; - this.pid = pid; - } - - static ProcessGroups load() { - if (System.getProperty("os.name", "").startsWith("Windows")) { - return new ProcessGroups(null, null, null); - } - Method pid; - try { - pid = Process.class.getMethod("pid"); - } catch (NoSuchMethodException error) { - // Java 8 keeps the PID in a private field of UNIXProcess. - pid = null; - } - return new ProcessGroups(executable("/usr/bin/perl", "/bin/perl"), - executable("/bin/kill", "/usr/bin/kill"), pid); - } - - private static String executable(String... candidates) { - for (String candidate : candidates) { - if (new File(candidate).canExecute()) { - return candidate; - } - } - return null; - } - - boolean available() { - return perl != null && kill != null; - } - - List launcher(List command, Map environment) { - String option = environment.remove("PERL5OPT"); - List launcher = new ArrayList<>(Arrays.asList(perl, "-e", SCRIPT, "--", - option == null ? "0" : "1", option == null ? "" : option)); - launcher.addAll(command); - return launcher; - } - - /** The tool's PID, which is its group ID; 0 when it cannot be read. */ - long leader(Process process) { - try { - if (pid != null) { - return ((Number) pid.invoke(process)).longValue(); - } - Field field = process.getClass().getDeclaredField("pid"); - field.setAccessible(true); - return field.getInt(process); - } catch (ReflectiveOperationException | RuntimeException error) { - return 0; - } - } - - /** Signals every member of {@code group}; an empty group is ignored. */ - void signal(long group, boolean forcibly) { - ProcessBuilder builder = new ProcessBuilder(kill, "-s", forcibly ? "KILL" : "TERM", "--", "-" + group); - File discard = new File("/dev/null"); - builder.redirectOutput(discard).redirectError(discard); - try { - Process signal = builder.start(); - signal.getOutputStream().close(); - if (!signal.waitFor(SIGNAL_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) { - signal.destroyForcibly(); - } - } catch (IOException error) { - // The host's process scope ends what this could not reach. - } catch (InterruptedException error) { - Thread.currentThread().interrupt(); - } - } - } - - /** - * {@code ProcessHandle} through reflection: present from Java 9, absent on - * Java 8, where only the direct child can be stopped. - */ - private static final class ProcessTree { - private final Method descendants; - private final Method destroy; - private final Method destroyForcibly; - - private ProcessTree(Method descendants, Method destroy, Method destroyForcibly) { - this.descendants = descendants; - this.destroy = destroy; - this.destroyForcibly = destroyForcibly; - } - - static ProcessTree load() { - try { - Class handle = Class.forName("java.lang.ProcessHandle"); - return new ProcessTree( - Process.class.getMethod("descendants"), - handle.getMethod("destroy"), - handle.getMethod("destroyForcibly")); - } catch (ReflectiveOperationException error) { - return new ProcessTree(null, null, null); - } - } - - List descendants(Process process) { - if (descendants == null) { - return Collections.emptyList(); - } - try { - @SuppressWarnings("unchecked") - Stream stream = (Stream) descendants.invoke(process); - return stream.collect(Collectors.toList()); - } catch (ReflectiveOperationException | RuntimeException error) { - return Collections.emptyList(); - } - } - - void destroy(List handles, boolean forcibly) { - Method method = forcibly ? destroyForcibly : destroy; - if (method == null) { - return; - } - for (Object handle : handles) { - try { - method.invoke(handle); - } catch (ReflectiveOperationException | RuntimeException error) { - // The process already exited, or the platform refused; the - // host's process scope ends what is left. - } - } - } - } -} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java deleted file mode 100644 index c4e2ff8..0000000 --- a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java +++ /dev/null @@ -1,230 +0,0 @@ -package io.github.litheidea.plugin.sdk; - -import java.nio.charset.StandardCharsets; -import java.util.Map; -import java.util.regex.Pattern; - -/** - * Wire constants and validation shared with Lithe's Rust Core - * ({@code rust/lithe-core/src/lsp/interface/plugin_function.rs} in the Lithe - * repository) and the Node.js - * SDK. The SDK checks the same rules locally so a plugin author sees a mistake - * when registering a handler instead of as a refused session at runtime. - */ -public final class Protocol { - /** Protocol versions this SDK can answer: the highest of each. */ - public static final int FUNCTIONS_VERSION = 3; - public static final int BUILD_VERSION = 6; - - /** First plugin-function version with host services (credentials). */ - public static final int HOST_SERVICES_VERSION = 2; - /** First plugin-function version with workspace contexts, discovery, and host notifications. */ - public static final int CONTEXT_VERSION = 3; - - public static final String INITIALIZE = "initialize"; - public static final String INITIALIZED = "initialized"; - public static final String SHUTDOWN = "shutdown"; - public static final String EXIT = "exit"; - public static final String CANCEL_REQUEST = "$/cancelRequest"; - public static final String FUNCTION_INVOKE = "lithe/function/invoke"; - public static final String FUNCTION_REGISTER = "lithe/function/register"; - public static final String FUNCTION_UNREGISTER = "lithe/function/unregister"; - public static final String FUNCTION_PROGRESS = "lithe/function/progress"; - public static final String BUILD_MODEL = "lithe/build/model"; - public static final String BUILD_DEPENDENCIES = "lithe/build/dependencies"; - public static final String BUILD_EXECUTE = "lithe/build/execute"; - public static final String BUILD_TEST = "lithe/build/test"; - public static final String BUILD_DISCOVER_TESTS = "lithe/build/discoverTests"; - public static final String BUILD_PREPARE_DEBUG = "lithe/build/prepareDebug"; - public static final String BUILD_PREPARE_RUN = "lithe/build/prepareRun"; - public static final String BUILD_PROGRESS = "lithe/build/progress"; - - /** - * Backend-to-host requests of plugin-function protocols 2 and 3. From - * version 3 the host adds methods without a new version; - * {@link Host#request} sends any {@code lithe/host/*} method, and - * {@code getCapabilities} says which ones the session may call. - */ - public static final String HOST_TERMINAL_CREATE = "lithe/host/terminal/create"; - public static final String HOST_TERMINAL_SHOW = "lithe/host/terminal/show"; - public static final String HOST_TERMINAL_CLOSE = "lithe/host/terminal/close"; - public static final String HOST_TERMINAL_REOPEN = "lithe/host/terminal/reopen"; - public static final String HOST_TERMINAL_DISPOSE = "lithe/host/terminal/dispose"; - public static final String HOST_TERMINAL_ON_EXIT = "lithe/host/terminal/onExit"; - public static final String HOST_PREFIX = "lithe/host/"; - public static final String HOST_CREDENTIALS_GET = "lithe/host/credentials/get"; - public static final String HOST_CREDENTIALS_SET = "lithe/host/credentials/set"; - public static final String HOST_CREDENTIALS_DELETE = "lithe/host/credentials/delete"; - public static final String HOST_GET_CAPABILITIES = "lithe/host/getCapabilities"; - public static final String HOST_SUBSCRIPTIONS_DISPOSE = "lithe/host/subscriptions/dispose"; - public static final String HOST_WORKSPACE_LIST_CONTEXTS = "lithe/host/workspace/listContexts"; - public static final String HOST_WORKSPACE_GET_CONTEXT = "lithe/host/workspace/getContext"; - public static final String HOST_WORKSPACE_GET_FOLDERS = "lithe/host/workspace/getFolders"; - public static final String HOST_WORKSPACE_READ_DIRECTORY = "lithe/host/workspace/readDirectory"; - public static final String HOST_WORKSPACE_STAT = "lithe/host/workspace/stat"; - public static final String HOST_WORKSPACE_READ_FILE = "lithe/host/workspace/readFile"; - public static final String HOST_WORKSPACE_WATCH = "lithe/host/workspace/watch"; - public static final String HOST_WORKSPACE_FIND_FILES = "lithe/host/workspace/findFiles"; - public static final String HOST_WORKSPACE_FIND_TEXT = "lithe/host/workspace/findText"; - public static final String HOST_DOCUMENTS_LIST = "lithe/host/documents/list"; - public static final String HOST_DOCUMENTS_GET_SNAPSHOT = "lithe/host/documents/getSnapshot"; - public static final String HOST_EDITOR_REGISTER_ACTIONS = "lithe/host/editor/registerActions"; - public static final String HOST_EDITOR_GET_ACTIVE = "lithe/host/editor/getActive"; - public static final String HOST_EDITOR_GET_SELECTIONS = "lithe/host/editor/getSelections"; - public static final String HOST_EDITOR_APPLY_EDITS = "lithe/host/editor/applyEdits"; - public static final String HOST_EDITOR_REPLACE_SELECTIONS = "lithe/host/editor/replaceSelections"; - public static final String HOST_EDITOR_INSERT_TEXT = "lithe/host/editor/insertText"; - public static final String HOST_EDITOR_OPEN = "lithe/host/editor/open"; - public static final String HOST_EDITOR_REVEAL = "lithe/host/editor/reveal"; - public static final String HOST_PREVIEW_OPEN_HTML = "lithe/host/preview/openHTML"; - public static final String HOST_BROWSER_OPEN_EXTERNAL = "lithe/host/browser/openExternal"; - public static final String HOST_WINDOW_SHOW_INFORMATION = "lithe/host/window/showInformation"; - public static final String HOST_WINDOW_SHOW_WARNING = "lithe/host/window/showWarning"; - public static final String HOST_WINDOW_SHOW_ERROR = "lithe/host/window/showError"; - - /** Host-to-backend notifications of plugin-function protocol 3. */ - public static final String HOST_DID_CHANGE_CONTEXTS = "lithe/host/workspace/didChangeContexts"; - public static final String HOST_SUBSCRIPTION_NOTIFY = "lithe/host/subscriptions/notify"; - public static final String HOST_COMMAND_DID_RUN = "lithe/host/commands/didRun"; - - /** JSON-RPC and LSP error codes the SDK answers with. */ - public static final int PARSE_ERROR = -32700; - public static final int INVALID_REQUEST = -32600; - public static final int METHOD_NOT_FOUND = -32601; - public static final int INVALID_PARAMS = -32602; - public static final int INTERNAL_ERROR = -32603; - public static final int SERVER_NOT_INITIALIZED = -32002; - public static final int REQUEST_FAILED = -32000; - public static final int REQUEST_CANCELLED = -32800; - - public static final int MAX_FUNCTIONS = 256; - public static final int MAX_FUNCTION_ID_BYTES = 128; - public static final int MAX_PLUGIN_ERROR_CODE_BYTES = 64; - public static final int MAX_MESSAGE_BYTES = 1024; - public static final int MAX_RESULT_BYTES = 1 << 20; - public static final int MAX_BUILD_RESULT_BYTES = 32 * 1024 * 1024; - public static final int MAX_BUILD_MESSAGE_BYTES = 4096; - public static final int MAX_BUILD_OUTPUT_BYTES = 65536; - /** Unanswered host requests Core allows a session; the SDK queues the rest. */ - public static final int MAX_PENDING_HOST_REQUESTS = 16; - public static final int MAX_CREDENTIAL_SECRET_BYTES = 16 * 1024; - - /** Minimum negotiated version; unknown methods can never pass admission. */ - static int buildMethodVersion(String method) { - if (BUILD_MODEL.equals(method) || BUILD_DEPENDENCIES.equals(method)) return 1; - if (BUILD_EXECUTE.equals(method)) return 2; - if (BUILD_TEST.equals(method) || BUILD_DISCOVER_TESTS.equals(method)) return 3; - if (BUILD_PREPARE_DEBUG.equals(method)) return 5; - if (BUILD_PREPARE_RUN.equals(method)) return 4; - return Integer.MAX_VALUE; - } - - static boolean buildProgress(String method) { - return BUILD_EXECUTE.equals(method) || BUILD_TEST.equals(method) || BUILD_PREPARE_RUN.equals(method) || BUILD_PREPARE_DEBUG.equals(method); - } - - private static final Pattern FUNCTION_SEGMENT = Pattern.compile("[a-z][A-Za-z0-9]*"); - private static final Pattern PLUGIN_ERROR_CODE = Pattern.compile("[A-Za-z][A-Za-z0-9._-]*"); - private static final Pattern KEY = Pattern.compile("[A-Za-z0-9._:-]{1,128}"); - private static final Pattern COMMAND_ID = Pattern.compile("[a-z0-9.-]{1,128}"); - private static final long MAX_SAFE_INTEGER = 9007199254740991L; - - private Protocol() {} - - /** Dot-separated lowerCamelCase segments, for example {@code snapshot.refresh}. */ - public static boolean isFunctionId(String value) { - if (value == null || value.isEmpty() || utf8Length(value) > MAX_FUNCTION_ID_BYTES) { - return false; - } - for (String segment : value.split("\\.", -1)) { - if (!FUNCTION_SEGMENT.matcher(segment).matches()) { - return false; - } - } - return true; - } - - /** The plugin error code alphabet Core forwards as {@code pluginErrorCode}. */ - public static boolean isPluginErrorCode(String value) { - return value != null - && utf8Length(value) <= MAX_PLUGIN_ERROR_CODE_BYTES - && PLUGIN_ERROR_CODE.matcher(value).matches(); - } - - /** - * The key alphabet of protocols 2 and 3: 1-128 ASCII letters, digits, - * {@code .}, {@code _}, {@code :}, or {@code -}. Credential keys, context - * IDs, and subscription IDs use it. - */ - public static boolean isCredentialKey(String value) { - return value != null && KEY.matcher(value).matches(); - } - - /** {@code { contextID, generation }}, exactly, naming one generation of one workspace context. */ - public static boolean isContextReference(Object value) { - if (!(value instanceof Map) || ((Map) value).size() != 2) { - return false; - } - Map reference = (Map) value; - Object id = reference.get("contextID"); - return id instanceof String && isCredentialKey((String) id) && isGeneration(reference.get("generation")); - } - - /** A command ID from the plugin's manifest: 1-128 of {@code [a-z0-9.-]}. */ - public static boolean isCommandId(String value) { - return value != null && COMMAND_ID.matcher(value).matches(); - } - - /** A positive integer JSON can carry exactly. */ - static boolean isGeneration(Object value) { - if (value instanceof Long || value instanceof Integer || value instanceof Short || value instanceof Byte) { - long number = ((Number) value).longValue(); - return number >= 1 && number <= MAX_SAFE_INTEGER; - } - if (value instanceof Double || value instanceof Float) { - double number = ((Number) value).doubleValue(); - return number >= 1 && number <= MAX_SAFE_INTEGER && number == Math.rint(number); - } - return false; - } - - /** Cuts {@code value} to {@link #MAX_MESSAGE_BYTES} UTF-8 bytes without splitting a character. */ - public static String boundedText(String value) { - return boundedText(value, MAX_MESSAGE_BYTES); - } - - /** Cuts {@code value} to {@code limit} UTF-8 bytes without splitting a character. */ - public static String boundedText(String value, int limit) { - String text = value == null ? "" : value; - int used = 0; - int index = 0; - while (index < text.length()) { - int codePoint = text.codePointAt(index); - int size = codePoint < 0x80 ? 1 : codePoint < 0x800 ? 2 : codePoint < 0x10000 ? 3 : 4; - if (used + size > limit) { - return text.substring(0, index); - } - used += size; - index += Character.charCount(codePoint); - } - return text; - } - - /** - * Methods reserved for the SDK. A plugin cannot install its own handler for - * these, or send them to the host: the lifecycle belongs to the host's - * session management, and {@code lithe/*} belongs to Lithe's typed contracts. - */ - public static boolean isReservedMethod(String method) { - return method.equals(INITIALIZE) - || method.equals(INITIALIZED) - || method.equals(SHUTDOWN) - || method.equals(EXIT) - || method.equals(CANCEL_REQUEST) - || method.startsWith("lithe/"); - } - - static int utf8Length(String value) { - return value.getBytes(StandardCharsets.UTF_8).length; - } -} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/StateStore.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/StateStore.java deleted file mode 100644 index 24761e2..0000000 --- a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/StateStore.java +++ /dev/null @@ -1,198 +0,0 @@ -package io.github.litheidea.plugin.sdk; - -import java.io.IOException; -import java.net.URISyntaxException; -import java.net.URL; -import java.nio.ByteBuffer; -import java.nio.channels.FileChannel; -import java.nio.charset.StandardCharsets; -import java.nio.file.AtomicMoveNotSupportedException; -import java.nio.file.FileAlreadyExistsException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.StandardCopyOption; -import java.nio.file.StandardOpenOption; -import java.nio.file.attribute.PosixFilePermissions; -import java.security.CodeSource; -import java.security.SecureRandom; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.regex.Pattern; - -/** - * Durable plugin state, in a directory the host gives the backend. - * - *

The host passes writable directories through the {@code ${stateDir}} and - * {@code ${workspaceStateDir}} launch variables; the installed package and the - * host's installation are read-only, because signatures and delta updates are - * computed over their exact bytes. Values are JSON; each key is one file - * replaced atomically, so a crash leaves either the old or the new value, - * never half of one. The envelope matches the Node.js SDK's, so either SDK - * reads what the other wrote. - */ -public final class StateStore { - /** Version of the envelope each value is stored in. */ - private static final int STORE_FORMAT = 1; - private static final Pattern KEY = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._-]{0,127}"); - private static final SecureRandom RANDOM = new SecureRandom(); - - private final Path root; - - private StateStore(Path root) { - this.root = root; - } - - /** - * Opens a store in {@code directory}, creating the directory. Refuses a - * directory inside the plugin package, found as the nearest directory with - * a {@code plugin.json} above the JAR this class was loaded from. - * - * @param directory absolute path, normally the value of {@code ${workspaceStateDir}} - */ - public static StateStore open(Path directory) throws IOException { - return open(directory, findPackageDirectory()); - } - - /** - * Opens a store in {@code directory}, refusing one inside - * {@code packageDirectory}; null skips that check. - */ - public static StateStore open(Path directory, Path packageDirectory) throws IOException { - if (directory == null || !directory.isAbsolute()) { - throw new PluginSdkError("sdk.state.invalidDirectory", - "The state directory must be an absolute path passed by the host."); - } - // Checked before creating anything, so a refused path leaves the package untouched. - Path resolved = canonical(directory); - if (packageDirectory != null && resolved.startsWith(canonical(packageDirectory))) { - throw new PluginSdkError("sdk.state.readOnlyPackage", - "The state directory is inside the plugin package, which is read-only. Use ${stateDir} or ${workspaceStateDir}."); - } - Files.createDirectories(resolved); - return new StateStore(resolved); - } - - /** The resolved directory, for a backend that keeps its own files next to the store. */ - public Path directory() { - return root; - } - - /** The stored value, or {@code fallback} when the key is missing or unreadable. */ - public Object read(String key, Object fallback) { - Path path = path(key); - if (!Files.isRegularFile(path)) { - return fallback; - } - try { - Object envelope = Json.parse(new String(Files.readAllBytes(path), StandardCharsets.UTF_8)); - if (!(envelope instanceof Map)) { - return fallback; - } - Map fields = (Map) envelope; - Object format = fields.get("litheStateStore"); - if (!(format instanceof Number) || ((Number) format).doubleValue() != STORE_FORMAT - || !fields.containsKey("value")) { - return fallback; - } - return fields.get("value"); - } catch (IOException | RuntimeException error) { - return fallback; - } - } - - /** Stores {@code value}, which must be JSON-encodable, replacing the previous one. */ - public void write(String key, Object value) throws IOException { - Path path = path(key); - Map envelope = new LinkedHashMap<>(); - envelope.put("litheStateStore", STORE_FORMAT); - envelope.put("value", value); - byte[] body; - try { - body = Json.stringify(envelope).getBytes(StandardCharsets.UTF_8); - } catch (Json.JsonException error) { - // Refused before touching the file, so the stored value stays. - throw new PluginSdkError("sdk.state.invalidValue", "The value for " + key + " is not JSON-encodable."); - } - Path temporary = root.resolve(key + ".json." + Long.toHexString(RANDOM.nextLong()) + ".tmp"); - try { - createPrivate(temporary); - try (FileChannel channel = FileChannel.open(temporary, StandardOpenOption.WRITE)) { - ByteBuffer buffer = ByteBuffer.wrap(body); - while (buffer.hasRemaining()) { - channel.write(buffer); - } - channel.force(true); - } - try { - Files.move(temporary, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); - } catch (AtomicMoveNotSupportedException error) { - Files.move(temporary, path, StandardCopyOption.REPLACE_EXISTING); - } - } catch (IOException | RuntimeException error) { - Files.deleteIfExists(temporary); - throw error; - } - } - - /** Removes the key; a missing key is not an error. */ - public void delete(String key) throws IOException { - Files.deleteIfExists(path(key)); - } - - private Path path(String key) { - if (key == null || !KEY.matcher(key).matches() || key.endsWith(".tmp")) { - throw new PluginSdkError("sdk.state.invalidKey", "State key \"" + key - + "\" must be 1-128 letters, digits, \".\", \"_\" or \"-\", start with a letter or digit, and not end with \".tmp\"."); - } - return root.resolve(key + ".json"); - } - - /** Creates an empty file only the user can read, where the platform supports it. */ - private static void createPrivate(Path file) throws IOException { - try { - Files.createFile(file, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------"))); - } catch (UnsupportedOperationException error) { - Files.createFile(file); - } catch (FileAlreadyExistsException error) { - throw new IOException("A temporary state file already exists: " + file.getFileName(), error); - } - } - - /** Resolves symbolic links of the longest existing prefix of {@code path}. */ - static Path canonical(Path path) throws IOException { - Path absolute = path.toAbsolutePath().normalize(); - Path existing = absolute; - while (existing != null && !Files.exists(existing)) { - existing = existing.getParent(); - } - if (existing == null) { - return absolute; - } - return existing.toRealPath().resolve(existing.relativize(absolute)); - } - - /** The nearest directory with a {@code plugin.json} above the JAR this class came from. */ - static Path findPackageDirectory() { - try { - CodeSource source = StateStore.class.getProtectionDomain().getCodeSource(); - URL location = source == null ? null : source.getLocation(); - if (location == null) { - return null; - } - Path current = Paths.get(location.toURI()).toAbsolutePath(); - if (Files.isRegularFile(current)) { - current = current.getParent(); - } - while (current != null) { - if (Files.isRegularFile(current.resolve("plugin.json"))) { - return current; - } - current = current.getParent(); - } - return null; - } catch (URISyntaxException | RuntimeException error) { - return null; - } - } -}