From a212025efa4f3cfb665a109518471be952f1dba4 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sun, 15 Nov 2026 13:26:22 +0800 Subject: [PATCH] =?UTF-8?q?ci(rust-core):=20=E5=8F=AA=E8=BF=90=E8=A1=8C?= =?UTF-8?q?=E5=8F=97=E5=BD=B1=E5=93=8D=20crate=20=E7=9A=84=20Rust=20Core?= =?UTF-8?q?=20CI=20=E4=B8=8E=E5=B9=B3=E5=8F=B0=E6=B5=8B=E8=AF=95=E6=94=BE?= =?UTF-8?q?=E7=BD=AE=E8=A7=84=E8=8C=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 .github/workflows/rust-core.yml:Select crates 选出改动的 crate 及其所有反向依赖;Linux 对选中的 crate 跑 fmt、日志事件目录、注释规范、 clippy(全部 feature 与 Windows 目标)和测试;macOS/Windows 只测试声明了 该主机的 crate,Draft PR 不跑,Linux 通过后才跑;Rust Core gate 汇总结果, 不设路径过滤,便于设为必过检查。只缓存下载的依赖。 - 新增 scripts/rust-core/affected-crates.mjs:读取 cargo metadata,按改动 文件和 [package.metadata.lithe-ci] 的 hosts / test-features 生成各主机的 cargo 参数。 - 新增 scripts/rust-core/verify-platform-tests.mjs:解析 cfg、cfg_attr、 mod 声明和 #![cfg],测试在所属 crate 的每台 CI 主机上都被编译掉或忽略时失败。 - lithe-platform、lithe-platform-tests 声明 macOS 与 Windows,lithe-remote 声明 macOS 并以 server feature 测试。 - 注释规范脚本可只对指定 crate 运行 Rustdoc,文本检查仍覆盖全部 crate。 - 新增 CONTRIBUTING.md:平台差异写成数据、平台测试放在哪里、主机声明和 CI 选择规则;README 与 scripts/rust-core/README.md 同步。 --- .github/workflows/rust-core.yml | 166 +++++++ CONTRIBUTING.md | 115 +++++ README.md | 20 +- rust/crates/platform-tests/Cargo.toml | 5 + rust/crates/platform/Cargo.toml | 5 + rust/crates/remote/Cargo.toml | 8 + scripts/rust-core/README.md | 37 +- scripts/rust-core/affected-crates.mjs | 229 +++++++++ scripts/rust-core/affected-crates.test.mjs | 131 +++++ scripts/rust-core/verify-platform-tests.mjs | 470 ++++++++++++++++++ .../rust-core/verify-platform-tests.test.mjs | 152 ++++++ .../rust-core/verify-rust-core-comments.sh | 18 +- 12 files changed, 1348 insertions(+), 8 deletions(-) create mode 100644 .github/workflows/rust-core.yml create mode 100644 CONTRIBUTING.md create mode 100644 scripts/rust-core/affected-crates.mjs create mode 100644 scripts/rust-core/affected-crates.test.mjs create mode 100644 scripts/rust-core/verify-platform-tests.mjs create mode 100644 scripts/rust-core/verify-platform-tests.test.mjs diff --git a/.github/workflows/rust-core.yml b/.github/workflows/rust-core.yml new file mode 100644 index 00000000..b2d23695 --- /dev/null +++ b/.github/workflows/rust-core.yml @@ -0,0 +1,166 @@ +name: Rust Core + +# Builds, lints and tests only the Rust Core crates a pull request can affect: +# the crates whose files changed and every crate that depends on them, as +# chosen by scripts/rust-core/affected-crates.mjs. Linux checks every selected +# crate. macOS and Windows run the tests of the selected crates that declare +# those hosts, once the pull request is ready for review and Linux passed. +# +# There is no path filter: a change that affects no crate still reports the +# "Rust Core gate" check, which branch rules can require. +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: rust-core-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +env: + CARGO_TERM_COLOR: always + # CI compiles each crate once: incremental state and full debug information + # would only cost time and disk space. + CARGO_INCREMENTAL: 0 + CARGO_PROFILE_DEV_DEBUG: line-tables-only + +jobs: + select: + name: Select crates + runs-on: ubuntu-latest + timeout-minutes: 10 + outputs: + rust: ${{ steps.select.outputs.rust }} + packages: ${{ steps.select.outputs.packages }} + test-args: ${{ steps.select.outputs.test-args }} + crate-directories: ${{ steps.select.outputs.crate-directories }} + hosts: ${{ steps.select.outputs.hosts }} + steps: + - uses: actions/checkout@v7 + with: + # A pull request checks out its merge commit, whose first parent is + # the branch it merges into. + fetch-depth: 2 + - uses: actions/setup-node@v6 + with: + node-version: 22 + - uses: dtolnay/rust-toolchain@stable + + - name: Test the CI scripts + run: node --test scripts/rust-core/*.test.mjs + - name: Check that every test runs on a host CI tests its crate on + run: node scripts/rust-core/verify-platform-tests.mjs + - name: Select crates + id: select + env: + # A manual run checks every crate. + SCOPE: ${{ github.event_name == 'pull_request' && '--base HEAD^1' || '--all' }} + run: | + read -ra scope <<< "$SCOPE" + node scripts/rust-core/affected-crates.mjs --github "${scope[@]}" + + linux: + name: Linux + needs: select + if: needs.select.outputs.rust == 'true' + runs-on: ubuntu-latest + timeout-minutes: 60 + env: + # One build directory for the lints, Rustdoc and the tests. + CARGO_TARGET_DIR: ${{ github.workspace }}/rust/target + PACKAGES: ${{ needs.select.outputs.packages }} + TEST_ARGS: ${{ needs.select.outputs.test-args }} + CRATE_DIRECTORIES: ${{ needs.select.outputs.crate-directories }} + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v6 + with: + node-version: 22 + - uses: dtolnay/rust-toolchain@stable + with: + components: clippy, rustfmt + targets: x86_64-pc-windows-msvc + # Only downloaded crates are cached: build output would not fit the + # repository cache quota next to the SDK end-to-end cache. + - uses: actions/cache@v6 + with: + path: | + ~/.cargo/registry/index + ~/.cargo/registry/cache + ~/.cargo/git/db + key: rust-core-cargo-${{ hashFiles('rust/Cargo.lock', 'scripts/rust-core/comment-lexer/Cargo.lock') }} + restore-keys: rust-core-cargo- + + - name: Check formatting + run: cargo fmt --manifest-path rust/Cargo.toml --all -- --check + - name: Check the log event catalog + run: node scripts/logging/generate-log-events.mjs --check + - name: Check comments + run: | + read -ra directories <<< "$CRATE_DIRECTORIES" + scripts/rust-core/verify-rust-core-comments.sh "${directories[@]}" + - name: Lint + run: | + read -ra packages <<< "$PACKAGES" + cargo clippy --locked --manifest-path rust/Cargo.toml "${packages[@]}" --all-targets --all-features -- -D warnings + # Code behind cfg(windows) compiles only for Windows. Checking it here + # finds its errors without a Windows runner; default features only, + # because the remote server feature targets Unix hosts. + - name: Lint for Windows + run: | + read -ra packages <<< "$PACKAGES" + cargo clippy --locked --manifest-path rust/Cargo.toml "${packages[@]}" --all-targets --target x86_64-pc-windows-msvc -- -D warnings + - name: Test + run: | + read -ra arguments <<< "$TEST_ARGS" + cargo test --locked --manifest-path rust/Cargo.toml "${arguments[@]}" + + hosts: + name: ${{ matrix.name }} + needs: [select, linux] + # Draft pull requests run Linux only, like the desktop repository. + if: needs.select.outputs.hosts != '[]' && (github.event_name != 'pull_request' || !github.event.pull_request.draft) + strategy: + fail-fast: false + matrix: + include: ${{ fromJSON(needs.select.outputs.hosts) }} + runs-on: ${{ matrix.runner }} + timeout-minutes: 45 + defaults: + run: + shell: bash + env: + TEST_ARGS: ${{ matrix.test-args }} + steps: + - uses: actions/checkout@v7 + - uses: dtolnay/rust-toolchain@stable + + - name: Test + run: | + read -ra arguments <<< "$TEST_ARGS" + cargo test --locked --manifest-path rust/Cargo.toml "${arguments[@]}" + + gate: + name: Rust Core gate + needs: [select, linux, hosts] + if: always() + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + # A job that had nothing to check is skipped; any other result fails. + - name: Require every job to pass or be skipped + env: + NEEDS: ${{ toJSON(needs) }} + run: | + jq -r 'to_entries[] | "\(.key): \(.value.result)"' <<< "$NEEDS" + failed="$(jq -r '[to_entries[] | select(.value.result != "success" and .value.result != "skipped") | .key] | join(", ")' <<< "$NEEDS")" + if [[ -n "$failed" ]]; then + echo "::error::Rust Core jobs did not pass: $failed" + exit 1 + fi diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..36ae6779 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,115 @@ +# 参与 Rust Core 开发 + +本页规定平台相关代码怎么写、平台测试放在哪里,以及 CI 怎样只运行受影响的 crate。插件契约和 SDK 的规则见 [`shared/plugins/README.md`](shared/plugins/README.md)。 + +## 平台差异写成数据 + +- 路径比较、Windows 保留文件名、路径斜杠、Unix 权限位、batch 参数转义这类平台规则放在 [`lithe-platform`](rust/crates/platform),以 `Platform { Unix, Windows }` 参数表达。生产代码用 `Platform::HOST` 取本机规则。 +- `cfg` 只用在必须调用操作系统接口的地方,例如 Windows job object、Unix 进程组、权限位系统调用。 +- 规则写成数据后,任何主机都能分别传入 `Platform::Unix` 和 `Platform::Windows` 测试两套规则,不需要真的有那台系统。 + +## 平台测试放在哪里 + +按下面的顺序判断,命中第一条就停: + +1. **能写成 `Platform` 参数的规则**:在规则所在的 crate 里对两个平台各测一次,不加 `cfg`。这类测试在所有主机上都运行。 +2. **结果取决于真实操作系统的行为**(进程树、job object、权限位、batch 启动、可执行文件查找等):放进 [`rust/crates/platform-tests/tests/platform/`](rust/crates/platform-tests/tests/platform) 里对应主题的模块。需要被启动的程序时,给 `lithe-platform-fixture` 增加一种模式。不要把这类测试写在被测 crate 里,也不要在其他 crate 里加 `#[cfg(windows)]`、`#[cfg(target_os = "macos")]` 之类的测试。 +3. **只借用 Unix 才有的夹具**(符号链接、权限位)来验证本 crate 自己的逻辑,并且 Linux 上会运行的 `#[cfg(unix)]` 测试:可以留在本 crate。如果 Windows 上应有另一种结果,那个结果按第 2 条写进 `lithe-platform-tests`。 +4. **测试里的 `cfg!`** 只能把夹具改成本机格式,例如 Windows 绝对路径要带盘符;不能用它为不同系统选择不同的预期结果。预期随系统变化的断言属于第 2 条。 +5. **例外**:crate 的集成测试必须启动本包的可执行文件时,因为 `CARGO_BIN_EXE_*` 只对同一个包可见,测试无法搬走。这种 crate 在自己的 `Cargo.toml` 声明主机。目前只有 [`lithe-remote`](rust/crates/remote):它的服务端运行在 Linux 和 macOS 主机上。新增例外要在 PR 里说明为什么不能放进 `lithe-platform-tests`。 + +[`scripts/rust-core/verify-platform-tests.mjs`](scripts/rust-core/verify-platform-tests.mjs) 检查的是:有没有测试在所属 crate 的每台 CI 主机上都被 `cfg` 编译掉,或者被 `cfg_attr(…, ignore)` 忽略。这样的测试在 CI 里永远不会运行,检查会失败。CI 的 `Select crates` 作业每次都运行这项检查。加 `--list` 会列出所有只在部分主机上运行的测试。第 3、4 条要看测试的意图,脚本判断不了,由评审把关。 + +## 声明 CI 主机 + +```toml +[package.metadata.lithe-ci] +hosts = ["macos", "windows"] # 除 Linux 外,还要在这些主机上运行测试 +test-features = ["server"] # 测试需要的 feature,在每台主机上都启用 +``` + +`hosts` 只接受 `macos` 和 `windows`;每个 crate 都会在 Linux 上测试,不必声明。目前声明主机的 crate 有 `lithe-platform`、`lithe-platform-tests` 和 `lithe-remote`。声明主机后,每个影响到该 crate 的 PR 都会多占用 macOS 或 Windows runner,所以只能用于上一节允许的情况。 + +## CI 怎样只运行受影响的 crate + +[`.github/workflows/rust-core.yml`](.github/workflows/rust-core.yml) 由四个作业组成: + +- **Select crates**:先运行 CI 脚本的测试和上面的放置检查,再由 [`affected-crates.mjs`](scripts/rust-core/affected-crates.mjs) 根据 PR 改动的文件选出 crate。选中的是文件所在的 crate,加上所有直接或间接依赖它的 crate(各种依赖都算,包括 dev-dependency)。另外几类文件的处理是: + - 会选中全部 crate:`rust/` 下不属于某个 crate 的文件(workspace 清单、`Cargo.lock`、`fixtures/`、`contracts/`、`logging/`)、`shared/plugins/contract/`、`scripts/rust-core/`、`scripts/logging/`,以及工作流文件本身。 + - `shared/plugins/sdk/e2e/` 只选中 `lithe-core`。 + - 文档、SDK 等其他文件不选中任何 crate。 +- **Linux**:对选中的 crate 依次运行格式检查(全部 crate,耗时很短)、日志事件目录检查、注释规范(文本检查覆盖全部 crate,Rustdoc 只构建选中的 crate)、启用全部 feature 的 clippy、针对 `x86_64-pc-windows-msvc` 的 clippy(只用默认 feature),最后是启用 `test-features` 的测试。 +- **macOS / Windows**:只测试选中、并且声明了对应主机的 crate。Draft PR 不运行这一步;PR 标记为 ready 并且 Linux 通过之后才运行。 +- **Rust Core gate**:汇总上面三个作业。作业被跳过算通过,其余结果都算失败。工作流不设路径过滤,所以每个 PR 都会报告这个检查,分支规则可以把它设为必过。 + +手动运行工作流(workflow_dispatch)会检查全部 crate。CI 只缓存下载的依赖,不缓存构建产物。 + +## 本地命令 + +```sh +node scripts/rust-core/affected-crates.mjs # 相对 origin/main 的改动,CI 会运行哪些 crate +node scripts/rust-core/verify-platform-tests.mjs --list # 放置检查,并列出只在部分主机运行的测试 +node --test scripts/rust-core/*.test.mjs # CI 脚本自己的测试 +cargo test --manifest-path rust/Cargo.toml -p lithe-platform -p lithe-platform-tests # 在 macOS 或 Windows 上运行平台测试 +``` + +手边没有 Windows 时,至少运行一次 `cargo clippy --manifest-path rust/Cargo.toml --workspace --all-targets --target x86_64-pc-windows-msvc -- -D warnings`,确认 Windows 代码能编译。 + +--- + +# Contributing to Rust Core (English) + +This page sets how platform code is written, where platform tests go, and how CI runs only the crates a change affects. The plugin contract and SDK rules live in [`shared/plugins/README.md`](shared/plugins/README.md). + +## Platform differences are data + +- Platform rules, such as path comparison, reserved Windows file names, path separators, Unix permission bits and batch argument quoting, live in [`lithe-platform`](rust/crates/platform) and take a `Platform { Unix, Windows }` argument. Production code passes `Platform::HOST`. +- `cfg` is only for calls into the operating system, such as Windows job objects, Unix process groups and permission system calls. +- Because the rules are data, any host tests both sets by passing `Platform::Unix` and `Platform::Windows`. + +## Where platform tests go + +Take the first rule that applies: + +1. **A rule that takes a `Platform`**: test it for both platforms in the crate that owns it, without `cfg`. Every host runs these tests. +2. **A result that depends on the real operating system** (process trees, job objects, permission bits, batch launches, executable lookup and the like): add it to the module for that subject under [`rust/crates/platform-tests/tests/platform/`](rust/crates/platform-tests/tests/platform). When a test needs a program to start, add a mode to `lithe-platform-fixture`. Do not write such tests in the crate under test, and do not add `#[cfg(windows)]`, `#[cfg(target_os = "macos")]` or similar tests to any other crate. +3. **A `#[cfg(unix)]` test that only borrows a Unix fixture** (a symbolic link, permission bits) to check the crate's own logic, and that runs on Linux: it may stay in its crate. If Windows should behave differently, that result goes into `lithe-platform-tests` under rule 2. +4. **`cfg!` in a test** may only convert a fixture to the host's form, for example give a Windows absolute path its drive. It must not choose a different expected result per system; such assertions fall under rule 2. +5. **Exception**: when a crate's integration tests must start the crate's own executable, they cannot move, because `CARGO_BIN_EXE_*` is visible only within the package. Such a crate declares its hosts in its own `Cargo.toml`. Today only [`lithe-remote`](rust/crates/remote) does, because its server runs on Linux and macOS hosts. A new exception explains in its pull request why the tests cannot go into `lithe-platform-tests`. + +[`scripts/rust-core/verify-platform-tests.mjs`](scripts/rust-core/verify-platform-tests.mjs) fails when a test is compiled out by `cfg`, or ignored by `cfg_attr(…, ignore)`, on every CI host of its crate, because CI would never run it. The `Select crates` job runs it on every change. `--list` also prints every test that runs on only some hosts. Rules 3 and 4 are about a test's intent, which the script cannot judge; review enforces them. + +## Declaring CI hosts + +```toml +[package.metadata.lithe-ci] +hosts = ["macos", "windows"] # hosts that also run the crate's tests, besides Linux +test-features = ["server"] # features the tests need, enabled on every host +``` + +`hosts` accepts `macos` and `windows`; every crate is tested on Linux without declaring it. Today `lithe-platform`, `lithe-platform-tests` and `lithe-remote` declare hosts. A declaration makes every pull request that affects the crate use a macOS or Windows runner, so it is only for the cases the previous section allows. + +## How CI runs only the affected crates + +[`.github/workflows/rust-core.yml`](.github/workflows/rust-core.yml) has four jobs: + +- **Select crates** tests the CI scripts, runs the placement check above, and lets [`affected-crates.mjs`](scripts/rust-core/affected-crates.mjs) choose crates from the files the pull request changes: the crate each file belongs to, plus every crate that depends on it directly or indirectly, through any kind of dependency, dev-dependencies included. Other files are handled as follows: + - These select every crate: files under `rust/` outside any crate (the workspace manifest, `Cargo.lock`, `fixtures/`, `contracts/`, `logging/`), `shared/plugins/contract/`, `scripts/rust-core/`, `scripts/logging/` and the workflow itself. + - `shared/plugins/sdk/e2e/` selects `lithe-core` only. + - Documentation, the SDKs and other files select no crate. +- **Linux** runs, for the selected crates: the formatting check (every crate; it is quick), the log event catalog check, the comment rules (the textual checks cover every crate, Rustdoc builds the selected ones), clippy with every feature, clippy for `x86_64-pc-windows-msvc` with default features, and the tests with their `test-features`. +- **macOS / Windows** test the selected crates that declare that host. Draft pull requests skip them; they run once the pull request is ready for review and Linux passed. +- **Rust Core gate** sums up the three jobs above. A skipped job passes; any other result fails. The workflow has no path filter, so every pull request reports this check and branch rules can require it. + +A manual run (workflow_dispatch) checks every crate. CI caches downloaded dependencies only, not build output. + +## Local commands + +```sh +node scripts/rust-core/affected-crates.mjs # which crates CI runs for the changes since origin/main +node scripts/rust-core/verify-platform-tests.mjs --list # the placement check, listing tests that run on some hosts only +node --test scripts/rust-core/*.test.mjs # the CI scripts' own tests +cargo test --manifest-path rust/Cargo.toml -p lithe-platform -p lithe-platform-tests # platform tests on macOS or Windows +``` + +Without a Windows host, at least run `cargo clippy --manifest-path rust/Cargo.toml --workspace --all-targets --target x86_64-pc-windows-msvc -- -D warnings` to confirm the Windows code compiles. diff --git a/README.md b/README.md index 79f121ec..03c5a4a4 100644 --- a/README.md +++ b/README.md @@ -9,15 +9,18 @@ Lithe 的跨平台应用内核,以及插件契约、插件开发资料和官 | [`rust/fixtures/`](rust/fixtures) | Core 命令的测试数据,Core 测试和桌面端测试共用 | | [`rust/logging/`](rust/logging) | 日志事件目录 | | [`shared/plugins/`](shared/plugins) | 插件契约 `contract/v1/`、开发指南 `guides/`、参考 `reference/`、官方 SDK `sdk/{node,java,rust}` 和它们的端到端测试 | -| [`scripts/rust-core/`](scripts/rust-core) | Rust Core 注释规范检查(模块文档、英文注释、`unsafe` 安全说明、导出项 Rustdoc) | +| [`scripts/rust-core/`](scripts/rust-core) | Rust Core 的 CI 脚本:选择受影响的 crate、平台测试放置检查、注释规范检查(模块文档、英文注释、`unsafe` 安全说明、导出项 Rustdoc) | | [`scripts/logging/`](scripts/logging) | 日志事件目录生成器,从 `rust/logging/events/` 生成 `rust/crates/diagnostics/src/catalog_generated.rs` | **插件开发者**从 [`shared/plugins/README.md`](shared/plugins/README.md) 开始,不需要克隆 Lithe 应用仓库。 +**修改 Core** 前先读 [`CONTRIBUTING.md`](CONTRIBUTING.md):平台差异怎么写、平台测试放在哪里、CI 怎样只运行受影响的 crate。 ## 常用命令 ```sh cargo test --manifest-path rust/Cargo.toml --workspace # Core 测试 +node scripts/rust-core/affected-crates.mjs # 当前改动 CI 会运行哪些 crate +node scripts/rust-core/verify-platform-tests.mjs # 每个测试都在所属 crate 的 CI 主机上运行 scripts/rust-core/verify-rust-core-comments.sh # 注释规范 node scripts/logging/generate-log-events.mjs --check # 日志事件目录与生成表一致 node shared/plugins/scripts/verify-docs.mjs # 契约 $id 与文档链接 @@ -41,9 +44,22 @@ Lithe's cross-platform application core, and the single source of the plugin con | [`rust/fixtures/`](rust/fixtures) | Test data for Core commands, shared by the Core and desktop tests | | [`rust/logging/`](rust/logging) | The logging event catalog | | [`shared/plugins/`](shared/plugins) | The plugin contract `contract/v1/`, guides `guides/`, reference `reference/`, the official SDKs `sdk/{node,java,rust}` and their end-to-end tests | -| [`scripts/rust-core/`](scripts/rust-core) | The Rust Core comment rules check (module docs, English comments, `unsafe` safety sections, Rustdoc on exported items) | +| [`scripts/rust-core/`](scripts/rust-core) | The Rust Core CI scripts: affected crate selection, the platform test placement check, and the comment rules check (module docs, English comments, `unsafe` safety sections, Rustdoc on exported items) | | [`scripts/logging/`](scripts/logging) | The logging event catalog generator, which turns `rust/logging/events/` into `rust/crates/diagnostics/src/catalog_generated.rs` | **Plugin authors** start at [`shared/plugins/README.md`](shared/plugins/README.md) and never need to clone the Lithe application repository. +**Before changing Core**, read [`CONTRIBUTING.md`](CONTRIBUTING.md): how platform differences are written, where platform tests go, and how CI runs only the affected crates. + +## Common commands + +```sh +cargo test --manifest-path rust/Cargo.toml --workspace # Core tests +node scripts/rust-core/affected-crates.mjs # which crates CI runs for the current changes +node scripts/rust-core/verify-platform-tests.mjs # every test runs on a CI host of its crate +scripts/rust-core/verify-rust-core-comments.sh # comment rules +node scripts/logging/generate-log-events.mjs --check # log event catalog matches the generated table +node shared/plugins/scripts/verify-docs.mjs # contract $id values and documentation links +node shared/plugins/scripts/sdk-e2e.mjs # end-to-end tests of the three SDKs against this Core +``` A pull request that changes `shared/plugins/contract/v1/`, `rust/crates/plugin-model/src/capabilities.rs` or `rust/crates/plugin-rpc/src/` updates the [protocol changelog](shared/plugins/reference/protocol-changelog.md) in the same pull request. diff --git a/rust/crates/platform-tests/Cargo.toml b/rust/crates/platform-tests/Cargo.toml index 3b444b2b..e530e868 100644 --- a/rust/crates/platform-tests/Cargo.toml +++ b/rust/crates/platform-tests/Cargo.toml @@ -6,6 +6,11 @@ license = "Apache-2.0" publish = false description = "Tests that need a real Windows or Unix host, and the fixture program they start" +# The crate exists to run on each host: CI tests it on macOS and Windows as +# well as Linux (scripts/rust-core/affected-crates.mjs). +[package.metadata.lithe-ci] +hosts = ["macos", "windows"] + [dev-dependencies] lithe-git-host = { path = "../git-host" } lithe-lsp-transport = { path = "../lsp-transport" } diff --git a/rust/crates/platform/Cargo.toml b/rust/crates/platform/Cargo.toml index 6e088df3..4be74e50 100644 --- a/rust/crates/platform/Cargo.toml +++ b/rust/crates/platform/Cargo.toml @@ -6,3 +6,8 @@ license = "Apache-2.0" description = "Host platform rules as data: path comparison, Windows file names, Unix permissions and console-less processes" [dependencies] + +# Its tests check `Platform::HOST` against the host they run on, so CI also +# runs them on macOS and Windows (scripts/rust-core/affected-crates.mjs). +[package.metadata.lithe-ci] +hosts = ["macos", "windows"] diff --git a/rust/crates/remote/Cargo.toml b/rust/crates/remote/Cargo.toml index 620bcb95..b06223a2 100644 --- a/rust/crates/remote/Cargo.toml +++ b/rust/crates/remote/Cargo.toml @@ -14,6 +14,14 @@ client = ["dep:sha2"] # target musl so the same static executable works in minimal containers. server = ["dep:libc", "dep:sha2", "dep:trash"] +# The server runs on Linux and macOS hosts, and its integration tests start +# the server binary of this package, so they cannot move to +# lithe-platform-tests. CI runs them with the server feature on Linux and on +# macOS (scripts/rust-core/affected-crates.mjs). +[package.metadata.lithe-ci] +hosts = ["macos"] +test-features = ["server"] + [dependencies] base64 = "0.22" serde = { version = "1", features = ["derive"] } diff --git a/scripts/rust-core/README.md b/scripts/rust-core/README.md index d77c4da0..280cc99a 100644 --- a/scripts/rust-core/README.md +++ b/scripts/rust-core/README.md @@ -1,9 +1,36 @@ -# Verify Rust Core comments before compiling tests +# Rust Core CI scripts -Run `scripts/rust-core/verify-rust-core-comments.sh` from any directory. It checks -module documentation, English comments, unsafe API safety sections, exported -Rustdoc, and intra-doc links in every crate under `rust/crates/`. Every crate -must pass `missing_docs`; there is no exemption list. +The [Rust Core workflow](../../.github/workflows/rust-core.yml) runs these +scripts; [`CONTRIBUTING.md`](../../CONTRIBUTING.md) explains the rules behind +them. Test the Node.js scripts with `node --test scripts/rust-core/*.test.mjs`. + +## Affected crates + +`node scripts/rust-core/affected-crates.mjs [--base ] [--all] [--github]` +prints the crates that the changes since the merge base of `` (default +`origin/main`) and the working tree can affect, and the arguments each CI host +tests them with. It reads `cargo metadata --no-deps`, so it needs no network. +`--all` selects every crate; `--github` also writes the selection to +`$GITHUB_OUTPUT`. A crate that must also be tested on macOS or Windows declares +those hosts, and the features its tests need, under +`[package.metadata.lithe-ci]`. + +## Platform test placement + +`node scripts/rust-core/verify-platform-tests.mjs [--list]` reads the source of +every target a test build compiles, follows module declarations, and fails when +a test is compiled out by `cfg`, or ignored by `cfg_attr(…, ignore)`, on every +host CI tests its crate on. `--list` also prints every test that runs on only +some hosts. Options it cannot decide, such as features, count as enabled. + +## Comment rules + +Run `scripts/rust-core/verify-rust-core-comments.sh [crate-directory ...]` from +any directory. It checks module documentation, English comments, unsafe API +safety sections, exported Rustdoc, and intra-doc links. The textual checks +always cover every crate under `rust/crates/`; Rustdoc builds the crates whose +directories are given, or every crate without arguments. Every crate must pass +`missing_docs`; there is no exemption list. The small `comment-lexer` helper uses pinned `rustc_lexer` tokens to distinguish comments from ordinary, raw, and byte string literals. It does not parse source diff --git a/scripts/rust-core/affected-crates.mjs b/scripts/rust-core/affected-crates.mjs new file mode 100644 index 00000000..9f84a00e --- /dev/null +++ b/scripts/rust-core/affected-crates.mjs @@ -0,0 +1,229 @@ +#!/usr/bin/env node +// Chooses what Rust Core CI builds and tests for a change: the crates whose +// files changed, every crate that depends on them, and, among those, the +// crates whose tests must also run on a real macOS or Windows host. +// +// Linux runs every selected crate. A crate whose behaviour differs per +// operating system declares the other hosts in its Cargo.toml: +// +// [package.metadata.lithe-ci] +// hosts = ["macos", "windows"] +// test-features = ["server"] # features its tests need, on every host +// +// Usage: +// node scripts/rust-core/affected-crates.mjs [--base ] [--all] [--github] +// +// Without --all, the changed files are those since the merge base of +// (default origin/main) and HEAD, including uncommitted and untracked files. +// --github also appends the selection to $GITHUB_OUTPUT. + +import { execFileSync } from 'node:child_process'; +import { appendFileSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +export const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..'); + +/** Hosts that run declared crates' tests besides Linux, with their GitHub runners. */ +export const HOSTS = { + macos: { name: 'macOS', runner: 'macos-latest' }, + windows: { name: 'Windows', runner: 'windows-latest' }, +}; + +/** + * Paths outside crate directories that can change the build or tests of any + * crate. `rust/` holds the workspace manifest, the lock file, and the + * fixtures, contracts and log catalog that several crates read. + */ +export const EVERY_CRATE = [ + 'rust/', + 'shared/plugins/contract/', + 'scripts/rust-core/', + 'scripts/logging/', + '.github/workflows/rust-core.yml', +]; + +/** Paths outside crate directories that only one crate builds. */ +export const READ_BY = [ + // The plugin-sdk-e2e feature of lithe-core compiles these tests, and the + // lints enable every feature. + { prefix: 'shared/plugins/sdk/e2e/', crate: 'lithe-core' }, +]; + +/** The workspace members of `cargo metadata --no-deps` output. */ +export function workspaceCrates(metadata, root = ROOT) { + const members = metadata.packages.filter((pkg) => metadata.workspace_members.includes(pkg.id)); + const nameByDirectory = new Map(members.map((pkg) => [path.dirname(pkg.manifest_path), pkg.name])); + return members.map((pkg) => { + const ci = pkg.metadata?.['lithe-ci'] ?? {}; + const hosts = ci.hosts ?? []; + for (const host of hosts) { + if (!Object.hasOwn(HOSTS, host)) { + throw new Error(`${pkg.name}: unknown lithe-ci host "${host}"`); + } + } + return { + name: pkg.name, + directory: path.relative(root, path.dirname(pkg.manifest_path)).split(path.sep).join('/'), + // Every dependency kind counts: a dev-dependency change can break tests. + dependencies: [ + ...new Set( + pkg.dependencies.flatMap((dependency) => + nameByDirectory.has(dependency.path) ? [nameByDirectory.get(dependency.path)] : [], + ), + ), + ], + hosts, + testFeatures: ci['test-features'] ?? [], + // Source files that start a compiled target; benches and examples + // never run in a test build. + roots: (pkg.targets ?? []) + .filter((target) => !target.kind.some((kind) => ['bench', 'example', 'custom-build'].includes(kind))) + .map((target) => path.relative(root, target.src_path).split(path.sep).join('/')), + }; + }); +} + +/** + * Names of the crates that a change to `files`, repository-relative paths + * with forward slashes, can affect. `null` stands for every file. + */ +export function selectCrates(crates, files) { + const every = new Set(crates.map((crate) => crate.name)); + if (files === null) { + return every; + } + const selected = new Set(); + for (const file of files) { + const owner = crates.find((crate) => file.startsWith(`${crate.directory}/`)); + if (owner) { + selected.add(owner.name); + } else if (EVERY_CRATE.some((prefix) => file.startsWith(prefix))) { + return every; + } else { + for (const { prefix, crate } of READ_BY) { + if (file.startsWith(prefix) && every.has(crate)) { + selected.add(crate); + } + } + } + } + const dependents = new Map(); + for (const crate of crates) { + for (const dependency of crate.dependencies) { + dependents.set(dependency, [...(dependents.get(dependency) ?? []), crate.name]); + } + } + const pending = [...selected]; + while (pending.length > 0) { + for (const dependent of dependents.get(pending.pop()) ?? []) { + if (!selected.has(dependent)) { + selected.add(dependent); + pending.push(dependent); + } + } + } + return selected; +} + +/** Cargo arguments that test `crates`, or the whole workspace. */ +function testArguments(crates, wholeWorkspace) { + const packages = wholeWorkspace ? ['--workspace'] : crates.flatMap((crate) => ['-p', crate.name]); + const features = crates.flatMap((crate) => + crate.testFeatures.map((feature) => `${crate.name}/${feature}`), + ); + return [...packages, ...(features.length > 0 ? ['--features', features.join(',')] : [])].join(' '); +} + +/** What each CI job runs for the crates in `selected`. */ +export function plan(crates, selected) { + const chosen = crates.filter((crate) => selected.has(crate.name)); + const whole = chosen.length === crates.length; + return { + rust: chosen.length > 0, + packages: whole ? '--workspace' : chosen.flatMap((crate) => ['-p', crate.name]).join(' '), + testArgs: chosen.length > 0 ? testArguments(chosen, whole) : '', + // The comment check covers every crate when it receives none. + crateDirectories: whole ? '' : chosen.map((crate) => path.posix.basename(crate.directory)).join(' '), + hosts: Object.entries(HOSTS).flatMap(([os, host]) => { + const declared = chosen.filter((crate) => crate.hosts.includes(os)); + return declared.length > 0 + ? [{ os, name: host.name, runner: host.runner, 'test-args': testArguments(declared, false) }] + : []; + }), + }; +} + +function git(...args) { + return execFileSync('git', args, { cwd: ROOT, encoding: 'utf8' }); +} + +/** Files changed since the merge base of `base` and HEAD, also those not yet committed. */ +export function changedFiles(base) { + const mergeBase = git('merge-base', base, 'HEAD').trim(); + // Without rename detection a moved file also reports the path it left. + const tracked = git('diff', '--name-only', '--no-renames', mergeBase).split('\n'); + const untracked = git('ls-files', '--others', '--exclude-standard').split('\n'); + return [...new Set([...tracked, ...untracked].filter(Boolean))]; +} + +/** `cargo metadata --no-deps` output for the Rust Core workspace. */ +export function readMetadata() { + const output = execFileSync( + 'cargo', + ['metadata', '--no-deps', '--format-version', '1', '--manifest-path', path.join(ROOT, 'rust', 'Cargo.toml')], + { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 }, + ); + return JSON.parse(output); +} + +function parseArguments(args) { + const options = { base: 'origin/main', all: false, github: false }; + for (let index = 0; index < args.length; index += 1) { + const argument = args[index]; + if (argument === '--all') { + options.all = true; + } else if (argument === '--github') { + options.github = true; + } else if (argument === '--base' && index + 1 < args.length) { + index += 1; + options.base = args[index]; + } else { + throw new Error(`unknown argument: ${argument}`); + } + } + return options; +} + +function main() { + const options = parseArguments(process.argv.slice(2)); + const crates = workspaceCrates(readMetadata()); + const files = options.all ? null : changedFiles(options.base); + const result = plan(crates, selectCrates(crates, files)); + console.log(`changed files: ${files === null ? 'all' : files.length}`); + console.log(`linux: ${result.rust ? result.testArgs : 'nothing to build'}`); + for (const host of result.hosts) { + console.log(`${host.os}: ${host['test-args']}`); + } + if (options.github) { + const output = process.env.GITHUB_OUTPUT; + if (!output) { + throw new Error('GITHUB_OUTPUT is not set'); + } + appendFileSync( + output, + [ + `rust=${result.rust}`, + `packages=${result.packages}`, + `test-args=${result.testArgs}`, + `crate-directories=${result.crateDirectories}`, + `hosts=${JSON.stringify(result.hosts)}`, + '', + ].join('\n'), + ); + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) { + main(); +} diff --git a/scripts/rust-core/affected-crates.test.mjs b/scripts/rust-core/affected-crates.test.mjs new file mode 100644 index 00000000..9d49a72f --- /dev/null +++ b/scripts/rust-core/affected-crates.test.mjs @@ -0,0 +1,131 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { plan, selectCrates, workspaceCrates } from './affected-crates.mjs'; + +const ROOT = '/repo'; + +function member(name, directory, { dependencies = [], ci } = {}) { + return { + id: `${name} 0.1.0`, + name, + manifest_path: `${ROOT}/rust/crates/${directory}/Cargo.toml`, + dependencies: dependencies.map((dependency) => + dependency.startsWith('registry:') + ? { name: dependency.slice('registry:'.length) } + : { name: dependency, path: `${ROOT}/rust/crates/${dependency.replace('lithe-', '')}` }, + ), + metadata: ci ? { 'lithe-ci': ci } : null, + }; +} + +function metadata(...packages) { + return { packages, workspace_members: packages.map((pkg) => pkg.id) }; +} + +// platform <- git-host <- core, platform <- platform-tests (dev), lone. +const crates = workspaceCrates( + metadata( + member('lithe-platform', 'platform', { ci: { hosts: ['macos', 'windows'] } }), + member('lithe-platform-tests', 'platform-tests', { + dependencies: ['lithe-platform', 'lithe-git-host'], + ci: { hosts: ['macos', 'windows'] }, + }), + member('lithe-git-host', 'git-host', { dependencies: ['lithe-platform', 'registry:libc'] }), + member('lithe-core', 'core', { dependencies: ['lithe-git-host'] }), + member('lithe-remote', 'remote', { ci: { hosts: ['macos'], 'test-features': ['server'] } }), + member('lithe-lone', 'lone'), + ), + ROOT, +); + +const names = (set) => [...set].sort(); + +test('workspace crates keep only dependencies on other members', () => { + const gitHost = crates.find((crate) => crate.name === 'lithe-git-host'); + assert.equal(gitHost.directory, 'rust/crates/git-host'); + assert.deepEqual(gitHost.dependencies, ['lithe-platform']); + assert.deepEqual(gitHost.hosts, []); +}); + +test('an unknown host is rejected', () => { + assert.throws( + () => workspaceCrates(metadata(member('lithe-x', 'x', { ci: { hosts: ['linux'] } })), ROOT), + /unknown lithe-ci host "linux"/, + ); +}); + +test('a changed crate selects itself and every crate depending on it', () => { + assert.deepEqual(names(selectCrates(crates, ['rust/crates/git-host/src/lib.rs'])), [ + 'lithe-core', + 'lithe-git-host', + 'lithe-platform-tests', + ]); + assert.deepEqual(names(selectCrates(crates, ['rust/crates/lone/README.md'])), ['lithe-lone']); +}); + +test('a crate directory is not mistaken for another with the same prefix', () => { + assert.deepEqual(names(selectCrates(crates, ['rust/crates/platform-tests/src/lib.rs'])), [ + 'lithe-platform-tests', + ]); +}); + +test('workspace files, contract fixtures and the checks select every crate', () => { + for (const file of [ + 'rust/Cargo.lock', + 'rust/fixtures/git/case.json', + 'rust/crates/removed/src/lib.rs', + 'shared/plugins/contract/v1/README.md', + 'scripts/rust-core/verify-rust-core-comments.sh', + '.github/workflows/rust-core.yml', + ]) { + assert.equal(selectCrates(crates, [file]).size, crates.length, file); + } + assert.equal(selectCrates(crates, null).size, crates.length); +}); + +test('files no crate builds select nothing, and e2e tests select lithe-core', () => { + assert.equal(selectCrates(crates, ['README.md', 'shared/plugins/sdk/node/index.mjs']).size, 0); + assert.deepEqual(names(selectCrates(crates, ['shared/plugins/sdk/e2e/plugin_sdk/mod.rs'])), [ + 'lithe-core', + ]); +}); + +test('the plan tests declared crates on their hosts with their features', () => { + const result = plan(crates, selectCrates(crates, ['rust/crates/platform/src/lib.rs', 'rust/crates/remote/src/lib.rs'])); + assert.equal(result.rust, true); + assert.equal( + result.packages, + '-p lithe-platform -p lithe-platform-tests -p lithe-git-host -p lithe-core -p lithe-remote', + ); + assert.equal( + result.testArgs, + '-p lithe-platform -p lithe-platform-tests -p lithe-git-host -p lithe-core -p lithe-remote --features lithe-remote/server', + ); + assert.equal(result.crateDirectories, 'platform platform-tests git-host core remote'); + assert.deepEqual(result.hosts, [ + { + os: 'macos', + name: 'macOS', + runner: 'macos-latest', + 'test-args': '-p lithe-platform -p lithe-platform-tests -p lithe-remote --features lithe-remote/server', + }, + { + os: 'windows', + name: 'Windows', + runner: 'windows-latest', + 'test-args': '-p lithe-platform -p lithe-platform-tests', + }, + ]); +}); + +test('the plan names the workspace when every crate is selected', () => { + const result = plan(crates, selectCrates(crates, null)); + assert.equal(result.packages, '--workspace'); + assert.equal(result.testArgs, '--workspace --features lithe-remote/server'); + assert.equal(result.crateDirectories, ''); +}); + +test('the plan builds nothing when no crate is selected', () => { + const result = plan(crates, new Set()); + assert.deepEqual(result, { rust: false, packages: '', testArgs: '', crateDirectories: '', hosts: [] }); +}); diff --git a/scripts/rust-core/verify-platform-tests.mjs b/scripts/rust-core/verify-platform-tests.mjs new file mode 100644 index 00000000..09598515 --- /dev/null +++ b/scripts/rust-core/verify-platform-tests.mjs @@ -0,0 +1,470 @@ +#!/usr/bin/env node +// Fails when a Rust Core test runs on none of the hosts CI runs its crate on. +// +// CI tests every crate on Linux and a crate on macOS or Windows only when it +// declares that host under [package.metadata.lithe-ci] (see +// affected-crates.mjs). A test that `cfg` compiles out, or `cfg_attr` ignores, +// on each of those hosts would never run. Tests that need a real macOS or +// Windows host belong in lithe-platform-tests, which CI runs on every host; +// CONTRIBUTING.md explains where each kind of test goes. +// +// Usage: +// node scripts/rust-core/verify-platform-tests.mjs [--list] +// +// --list also prints every test that some host compiles out or ignores. + +import { readFileSync, existsSync } from 'node:fs'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { ROOT, readMetadata, workspaceCrates } from './affected-crates.mjs'; + +/** + * The configuration each CI host compiles tests with. Options it does not + * list, such as features, are unknown: a test behind them may run. + */ +export const HOST_CONFIGURATIONS = { + linux: { + flags: { unix: true, windows: false, test: true }, + values: { target_os: 'linux', target_family: 'unix', target_vendor: 'unknown', target_env: 'gnu' }, + }, + macos: { + flags: { unix: true, windows: false, test: true }, + values: { target_os: 'macos', target_family: 'unix', target_vendor: 'apple', target_env: '' }, + }, + windows: { + flags: { unix: false, windows: true, test: true }, + values: { target_os: 'windows', target_family: 'windows', target_vendor: 'pc', target_env: 'msvc' }, + }, +}; + +const IDENTIFIER = /[A-Za-z0-9_\u0080-\uffff]/; +const RAW_STRING = /^[bc]?r(#*)"/; + +/** + * Splits Rust source into identifiers, literals, lifetimes and punctuation, + * dropping whitespace and comments. `::` is one token; every other + * punctuation character is its own. + */ +export function tokenize(source) { + const tokens = []; + let line = 1; + let index = 0; + const advance = (end) => { + for (let position = index; position < end; position += 1) { + if (source[position] === '\n') { + line += 1; + } + } + index = end; + }; + const emit = (kind, end, value) => { + tokens.push({ kind, text: source.slice(index, end), value, line }); + advance(end); + }; + // The end of a quoted literal whose body starts at `start`. + const quoted = (start, quote) => { + let position = start; + while (position < source.length && source[position] !== quote) { + position += source[position] === '\\' ? 2 : 1; + } + return position + 1; + }; + while (index < source.length) { + const character = source[index]; + const next = source[index + 1]; + if (/\s/.test(character)) { + advance(index + 1); + } else if (character === '/' && next === '/') { + const end = source.indexOf('\n', index); + advance(end === -1 ? source.length : end); + } else if (character === '/' && next === '*') { + let depth = 1; + let position = index + 2; + while (position < source.length && depth > 0) { + if (source.startsWith('/*', position)) { + depth += 1; + position += 2; + } else if (source.startsWith('*/', position)) { + depth -= 1; + position += 2; + } else { + position += 1; + } + } + advance(position); + } else if (/[bcr]/.test(character) && RAW_STRING.test(source.slice(index, index + 260))) { + // Raw string: r"…", r#"…"#, br"…", cr"…". + const opening = RAW_STRING.exec(source.slice(index, index + 260)); + const body = index + opening[0].length; + const closing = `"${opening[1]}`; + const end = source.indexOf(closing, body); + const stop = end === -1 ? source.length : end; + emit('literal', stop + closing.length, source.slice(body, stop)); + } else if (character === '"' || (/[bc]/.test(character) && next === '"')) { + const body = character === '"' ? index + 1 : index + 2; + const end = quoted(body, '"'); + emit('literal', end, source.slice(body, end - 1)); + } else if (character === "'" || (character === 'b' && next === "'")) { + const quote = character === 'b' ? index + 1 : index; + if (source[quote + 1] === '\\') { + emit('literal', quoted(quote + 1, "'")); + } else { + const width = source.codePointAt(quote + 1) > 0xffff ? 2 : 1; + if (source[quote + 1 + width] === "'") { + emit('literal', quote + 2 + width); + } else { + let end = quote + 1; + while (end < source.length && IDENTIFIER.test(source[end])) { + end += 1; + } + emit('lifetime', end); + } + } + } else if (character === 'r' && next === '#' && IDENTIFIER.test(source[index + 2] ?? '')) { + let end = index + 2; + while (end < source.length && IDENTIFIER.test(source[end])) { + end += 1; + } + tokens.push({ kind: 'identifier', text: source.slice(index + 2, end), line }); + advance(end); + } else if (IDENTIFIER.test(character)) { + const number = /[0-9]/.test(character); + let end = index + 1; + while ( + end < source.length && + (IDENTIFIER.test(source[end]) || (number && source[end] === '.' && /[0-9]/.test(source[end + 1] ?? ''))) + ) { + end += 1; + } + emit(number ? 'literal' : 'identifier', end); + } else if (character === ':' && next === ':') { + emit('punctuation', index + 2); + } else { + emit('punctuation', index + 1); + } + } + return tokens; +} + +const CLOSERS = { '(': ')', '[': ']', '{': '}' }; + +/** The index after the group that opens at `open`. */ +function skipGroup(tokens, open) { + const stack = []; + for (let index = open; index < tokens.length; index += 1) { + const { kind, text } = tokens[index]; + if (kind !== 'punctuation') { + continue; + } + if (CLOSERS[text]) { + stack.push(CLOSERS[text]); + } else if (text === stack[stack.length - 1]) { + stack.pop(); + if (stack.length === 0) { + return index + 1; + } + } + } + return tokens.length; +} + +/** `tokens` split at commas outside any group, without empty parts. */ +function splitArguments(tokens) { + const parts = [[]]; + for (let index = 0; index < tokens.length; ) { + const { kind, text } = tokens[index]; + if (kind === 'punctuation' && CLOSERS[text]) { + const end = skipGroup(tokens, index); + parts[parts.length - 1].push(...tokens.slice(index, end)); + index = end; + } else { + if (kind === 'punctuation' && text === ',') { + parts.push([]); + } else { + parts[parts.length - 1].push(tokens[index]); + } + index += 1; + } + } + return parts.filter((part) => part.length > 0); +} + +/** A `cfg` predicate: `{ all | any: [...] }`, `{ not: predicate }` or an option. */ +export function parsePredicate(tokens) { + const [head, ...rest] = tokens; + if (!head || head.kind !== 'identifier') { + // A macro fragment such as `$condition`: its value is unknown. + return { option: '' }; + } + if (rest[0]?.text === '(') { + const items = splitArguments(rest.slice(1, skipGroup(rest, 0) - 1)).map(parsePredicate); + if (head.text === 'not') { + return { not: items[0] }; + } + return { [head.text === 'all' ? 'all' : 'any']: items }; + } + if (rest[0]?.text === '=') { + return { option: head.text, value: rest[1]?.value ?? rest[1]?.text }; + } + return { option: head.text }; +} + +/** Whether `predicate` holds on `host`: true, false, or null when unknown. */ +export function evaluate(predicate, host) { + if (predicate.all || predicate.any) { + const values = (predicate.all ?? predicate.any).map((item) => evaluate(item, host)); + const decisive = Boolean(predicate.any); + if (values.includes(decisive)) { + return decisive; + } + return values.includes(null) ? null : !decisive; + } + if (predicate.not) { + const value = evaluate(predicate.not, host); + return value === null ? null : !value; + } + if (predicate.value === undefined) { + return Object.hasOwn(host.flags, predicate.option) ? host.flags[predicate.option] : null; + } + return Object.hasOwn(host.values, predicate.option) ? host.values[predicate.option] === predicate.value : null; +} + +/** An attribute's path, and its parenthesised tokens or `= value`. */ +function parseAttribute(tokens, line) { + const names = []; + let index = 0; + while (index < tokens.length && (tokens[index].kind === 'identifier' || tokens[index].text === '::')) { + if (tokens[index].kind === 'identifier') { + names.push(tokens[index].text); + } + index += 1; + } + const attribute = { path: names.join('::'), line }; + if (tokens[index]?.text === '(') { + attribute.arguments = tokens.slice(index + 1, skipGroup(tokens, index) - 1); + } else if (tokens[index]?.text === '=') { + attribute.value = tokens[index + 1]?.value; + } + return attribute; +} + +/** + * `attributes` with every `cfg_attr` replaced by the attributes it applies, + * each carrying the predicate that applies it as `when`. + */ +function expandAttributes(attributes, when = null) { + return attributes.flatMap((attribute) => { + if (attribute.path !== 'cfg_attr' || !attribute.arguments) { + return [{ ...attribute, when }]; + } + const [predicate, ...applied] = splitArguments(attribute.arguments); + const condition = parsePredicate(predicate); + return expandAttributes( + applied.map((tokens) => parseAttribute(tokens, attribute.line)), + when ? { all: [when, condition] } : condition, + ); + }); +} + +const isTestAttribute = (attribute) => attribute.path === 'test' || attribute.path.endsWith('::test'); + +/** The `cfg` predicates that unconditionally apply to an item. */ +const conditionsOf = (attributes) => + attributes + .filter((attribute) => attribute.path === 'cfg' && !attribute.when && attribute.arguments) + .map((attribute) => parsePredicate(attribute.arguments)); + +/** + * The tests in one source file and the module files it declares. `scope` + * holds the conditions the file compiles under and the directory its child + * modules live in. + */ +export function scanSource(source, { file, conditions = [], directory }) { + const tokens = tokenize(source); + const tests = []; + const modules = []; + const scopes = [{ conditions, directory, inline: false }]; + let pending = []; + for (let index = 0; index < tokens.length; ) { + const token = tokens[index]; + const scope = scopes[scopes.length - 1]; + const following = tokens[index + 1]?.text; + if (token.text === '#' && (following === '[' || (following === '!' && tokens[index + 2]?.text === '['))) { + const open = following === '[' ? index + 1 : index + 2; + const end = skipGroup(tokens, open); + const attribute = parseAttribute(tokens.slice(open + 1, end - 1), token.line); + if (following === '!') { + // An inner attribute applies to the module that encloses it. + scope.conditions = [...scope.conditions, ...conditionsOf([attribute])]; + } else { + pending.push(attribute); + } + index = end; + continue; + } + const attributes = expandAttributes(pending); + pending = []; + if (token.text === '{') { + scopes.push({ ...scope }); + index += 1; + continue; + } + if (token.text === '}') { + scopes.pop(); + index += 1; + continue; + } + let keyword = index; + if (tokens[keyword].text === 'pub') { + keyword = tokens[keyword + 1]?.text === '(' ? skipGroup(tokens, keyword + 1) : keyword + 1; + } + if (tokens[keyword]?.text === 'mod' && tokens[keyword + 1]?.kind === 'identifier') { + const name = tokens[keyword + 1].text; + const terminator = tokens[keyword + 2]?.text; + const nested = [...scope.conditions, ...conditionsOf(attributes)]; + if (terminator === '{') { + scopes.push({ conditions: nested, directory: path.join(scope.directory, name), inline: true }); + index = keyword + 3; + continue; + } + if (terminator === ';') { + const custom = attributes.find((attribute) => attribute.path === 'path' && !attribute.when)?.value; + const candidates = custom + ? // Outside inline modules a path is relative to the declaring file. + [path.join(scope.inline ? scope.directory : path.dirname(file), custom)] + : [path.join(scope.directory, `${name}.rs`), path.join(scope.directory, name, 'mod.rs')]; + modules.push({ name, line: token.line, candidates, conditions: nested }); + index = keyword + 3; + continue; + } + } + if (attributes.some(isTestAttribute)) { + let name = index; + while (name < tokens.length && tokens[name].text !== 'fn') { + name += 1; + } + const always = attributes.some((attribute) => isTestAttribute(attribute) && !attribute.when); + tests.push({ + file, + line: tokens[name + 1]?.line ?? token.line, + name: tokens[name + 1]?.text ?? '?', + conditions: [ + ...scope.conditions, + ...conditionsOf(attributes), + // A test that only `cfg_attr` marks is a test where its predicate holds. + ...(always + ? [] + : [{ any: attributes.filter(isTestAttribute).map((attribute) => attribute.when) }]), + ], + ignoredWhen: attributes + .filter((attribute) => attribute.path === 'ignore' && attribute.when) + .map((attribute) => attribute.when), + }); + } + index += 1; + } + return { tests, modules }; +} + +/** The tests of every target that a test build of `crate` compiles. */ +export function crateTests(crate, root = ROOT) { + const tests = []; + const problems = []; + const visited = new Set(); + const visit = (file, conditions, directory) => { + if (visited.has(file)) { + return; + } + visited.add(file); + const relative = path.relative(root, file).split(path.sep).join('/'); + const result = scanSource(readFileSync(file, 'utf8'), { file: relative, conditions, directory }); + tests.push(...result.tests); + for (const module of result.modules) { + const candidates = module.candidates.map((candidate) => path.resolve(root, candidate)); + const found = candidates.find((candidate) => existsSync(candidate)); + if (!found) { + problems.push(`${relative}:${module.line}: cannot find the file of module \`${module.name}\``); + continue; + } + const ownsDirectory = path.basename(found) === 'mod.rs'; + visit( + found, + module.conditions, + ownsDirectory + ? path.dirname(found) + : path.join(path.dirname(found), path.basename(found, '.rs')), + ); + } + }; + for (const target of crate.roots) { + // A crate root is a mod-rs file: its modules sit beside it. + visit(path.resolve(root, target), [], path.dirname(path.resolve(root, target))); + } + return { tests, problems }; +} + +/** The hosts CI tests `crate` on. */ +export const ciHosts = (crate) => ['linux', ...crate.hosts]; + +/** + * Where `test` runs: hosts on which it compiles and is not ignored. A host + * on which that is unknown counts as running it. + */ +export function runningHosts(test, hosts) { + return hosts.filter((host) => { + const configuration = HOST_CONFIGURATIONS[host]; + return ( + test.conditions.every((condition) => evaluate(condition, configuration) !== false) && + !test.ignoredWhen.some((condition) => evaluate(condition, configuration) === true) + ); + }); +} + +/** Problems that keep `crates` from running each of their tests in CI. */ +export function verify(crates, root = ROOT) { + const problems = []; + const gated = []; + for (const crate of crates) { + const { tests, problems: unreadable } = crateTests(crate, root); + problems.push(...unreadable.map((problem) => `${crate.name}: ${problem}`)); + const hosts = ciHosts(crate); + for (const test of tests) { + const everywhere = runningHosts(test, Object.keys(HOST_CONFIGURATIONS)); + if (everywhere.length < Object.keys(HOST_CONFIGURATIONS).length) { + gated.push(`${crate.name}: ${test.file}:${test.line} ${test.name} runs on ${everywhere.join(', ') || 'no host'}`); + } + if (runningHosts(test, hosts).length === 0) { + problems.push( + `${crate.name}: ${test.file}:${test.line} \`${test.name}\` runs on none of the hosts CI tests this crate on (${hosts.join(', ')})`, + ); + } + } + } + return { problems, gated }; +} + +function main() { + const list = process.argv.includes('--list'); + const crates = workspaceCrates(readMetadata()); + const { problems, gated } = verify(crates); + if (list) { + console.log(gated.length > 0 ? gated.join('\n') : 'no test depends on its host'); + } + if (problems.length > 0) { + console.error( + [ + 'Tests that CI never runs:', + ...problems.map((problem) => ` ${problem}`), + 'Move a test that needs macOS or Windows to rust/crates/platform-tests,', + 'or declare the host in the crate: see CONTRIBUTING.md, "Platform tests".', + ].join('\n'), + ); + process.exitCode = 1; + return; + } + console.log(`platform tests: every test of ${crates.length} crates runs on a host CI tests it on`); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) { + main(); +} diff --git a/scripts/rust-core/verify-platform-tests.test.mjs b/scripts/rust-core/verify-platform-tests.test.mjs new file mode 100644 index 00000000..53376aac --- /dev/null +++ b/scripts/rust-core/verify-platform-tests.test.mjs @@ -0,0 +1,152 @@ +import assert from 'node:assert/strict'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import test from 'node:test'; +import { + HOST_CONFIGURATIONS, + crateTests, + evaluate, + parsePredicate, + runningHosts, + scanSource, + tokenize, + verify, +} from './verify-platform-tests.mjs'; + +const predicate = (source) => parsePredicate(tokenize(source)); +const on = (source) => + Object.fromEntries(Object.entries(HOST_CONFIGURATIONS).map(([host, cfg]) => [host, evaluate(predicate(source), cfg)])); +const scan = (source) => scanSource(source, { file: 'src/lib.rs', directory: '/crate/src' }); +const where = (source) => scan(source).tests.map((found) => [found.name, runningHosts(found, ['linux', 'macos', 'windows'])]); + +test('comments, strings and lifetimes hide nothing and invent nothing', () => { + const source = String.raw` + // #[test] fn commented() {} + /* nested /* #[test] */ fn commented_too() {} */ + const BRACES: &str = "}{ #[test]"; + const RAW: &str = r#"" } #[test] "#; + fn borrow<'a>(text: &'a str) -> char { let _ = b'}'; '{' } + fn r#match() {} + #[test] + fn real() {} + `; + assert.deepEqual(where(source), [['real', ['linux', 'macos', 'windows']]]); + const kinds = tokenize("'a 'b' '\\n' b'x'").map((token) => token.kind); + assert.deepEqual(kinds, ['lifetime', 'literal', 'literal', 'literal']); +}); + +test('predicates are true, false or unknown on each host', () => { + assert.deepEqual(on('unix'), { linux: true, macos: true, windows: false }); + assert.deepEqual(on('target_os = "macos"'), { linux: false, macos: true, windows: false }); + assert.deepEqual(on('not(windows)'), { linux: true, macos: true, windows: false }); + assert.deepEqual(on('all(test, target_family = "windows")'), { linux: false, macos: false, windows: true }); + assert.deepEqual(on('feature = "server"'), { linux: null, macos: null, windows: null }); + assert.deepEqual(on('any(windows, feature = "server")'), { linux: null, macos: null, windows: true }); + assert.deepEqual(on('all(unix, feature = "server")'), { linux: null, macos: null, windows: false }); +}); + +test('cfg on tests, modules and files decides where a test runs', () => { + const source = ` + #![cfg(unix)] + #[test] fn on_unix() {} + #[cfg(windows)] + pub(crate) mod windows { + #[tokio::test(flavor = "current_thread")] + async fn never() {} + } + mod plain { + #[cfg(target_os = "macos")] #[test] fn on_macos() {} + #[cfg(feature = "server")] #[test] fn behind_a_feature() {} + } + `; + assert.deepEqual(where(source), [ + ['on_unix', ['linux', 'macos']], + ['never', []], + ['on_macos', ['macos']], + ['behind_a_feature', ['linux', 'macos']], + ]); +}); + +test('cfg_attr can make a function a test or ignore it on some hosts', () => { + const source = ` + #[cfg_attr(windows, test)] fn tested_on_windows() {} + #[test] #[cfg_attr(not(windows), ignore = "needs a job object")] fn ignored_elsewhere() {} + #[test] #[cfg_attr(feature = "slow", ignore)] fn maybe_ignored() {} + #[cfg_attr(unix, allow(dead_code))] fn helper() {} + `; + assert.deepEqual(where(source), [ + ['tested_on_windows', ['windows']], + ['ignored_elsewhere', ['windows']], + ['maybe_ignored', ['linux', 'macos', 'windows']], + ]); +}); + +test('module declarations name the files a crate compiles', () => { + const { modules } = scan(` + #[cfg(windows)] mod windows; + #[path = "support/shared.rs"] mod shared; + mod outer { mod inner; } + `); + assert.deepEqual( + modules.map(({ name, candidates }) => [name, candidates]), + [ + ['windows', ['/crate/src/windows.rs', '/crate/src/windows/mod.rs']], + ['shared', ['src/support/shared.rs']], + ['inner', ['/crate/src/outer/inner.rs', '/crate/src/outer/inner/mod.rs']], + ], + ); + assert.equal(evaluate(modules[0].conditions[0], HOST_CONFIGURATIONS.linux), false); +}); + +/** A crate in a new temporary directory, removed after the test. */ +function temporaryCrate(t, files) { + const root = mkdtempSync(path.join(os.tmpdir(), 'lithe-platform-tests-')); + t.after(() => rmSync(root, { recursive: true, force: true })); + for (const [file, source] of Object.entries(files)) { + mkdirSync(path.dirname(path.join(root, file)), { recursive: true }); + writeFileSync(path.join(root, file), source); + } + return root; +} + +test('a crate is scanned through every module file its targets reach', (t) => { + const root = temporaryCrate(t, { + 'crate/src/lib.rs': '#[cfg(windows)] mod windows;\nmod host;\n#[cfg(test)] mod tests;\nmod missing;\n', + 'crate/src/windows.rs': 'mod job;\n', + 'crate/src/windows/job.rs': '#[test] fn job_object() {}\n', + 'crate/src/host.rs': '#[cfg(unix)]\nmod unix { #[test] fn unix_host() {} }\n', + 'crate/src/tests/mod.rs': 'mod cases;\n', + 'crate/src/tests/cases.rs': '#[test] fn anywhere() {}\n', + 'crate/tests/api.rs': '#[test] fn integration() {}\n', + }); + const { tests, problems } = crateTests( + { name: 'lithe-crate', hosts: [], roots: ['crate/src/lib.rs', 'crate/tests/api.rs'] }, + root, + ); + assert.deepEqual( + tests.map((found) => [found.file, found.name, runningHosts(found, ['linux', 'windows'])]), + [ + ['crate/src/windows/job.rs', 'job_object', ['windows']], + ['crate/src/host.rs', 'unix_host', ['linux']], + ['crate/src/tests/cases.rs', 'anywhere', ['linux', 'windows']], + ['crate/tests/api.rs', 'integration', ['linux', 'windows']], + ], + ); + assert.deepEqual(problems, ['crate/src/lib.rs:4: cannot find the file of module `missing`']); +}); + +test('a test must run on a host CI tests its crate on', (t) => { + const root = temporaryCrate(t, { + 'linux-only/src/lib.rs': '#[cfg(windows)] #[test] fn on_windows() {}\n#[cfg(unix)] #[test] fn on_unix() {}\n', + 'declared/src/lib.rs': '#[cfg(windows)] #[test] fn on_windows() {}\n', + 'ignored/src/lib.rs': '#[test] #[cfg_attr(unix, ignore)] fn not_on_unix() {}\n', + }); + const crate = (name, hosts = []) => ({ name, hosts, roots: [`${name}/src/lib.rs`] }); + const { problems, gated } = verify([crate('linux-only'), crate('declared', ['windows']), crate('ignored')], root); + assert.deepEqual(problems, [ + 'linux-only: linux-only/src/lib.rs:1 `on_windows` runs on none of the hosts CI tests this crate on (linux)', + 'ignored: ignored/src/lib.rs:1 `not_on_unix` runs on none of the hosts CI tests this crate on (linux)', + ]); + assert.equal(gated.length, 4); +}); diff --git a/scripts/rust-core/verify-rust-core-comments.sh b/scripts/rust-core/verify-rust-core-comments.sh index aa1f7b63..fcbcb47e 100755 --- a/scripts/rust-core/verify-rust-core-comments.sh +++ b/scripts/rust-core/verify-rust-core-comments.sh @@ -1,4 +1,9 @@ #!/usr/bin/env bash +# Usage: verify-rust-core-comments.sh [crate-directory ...] +# +# The textual checks always cover every crate. Rustdoc builds each crate, so +# CI passes the directories under rust/crates of the crates a change can +# affect; without arguments every crate is built. set -euo pipefail SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" @@ -14,6 +19,17 @@ SOURCE_DIRS=() for manifest in "${crate_manifests[@]}"; do SOURCE_DIRS+=("$ROOT_DIR/${manifest%Cargo.toml}src") done +rustdoc_manifests=("${crate_manifests[@]}") +if (( $# > 0 )); then + rustdoc_manifests=() + for directory in "$@"; do + if [[ ! -f "rust/crates/$directory/Cargo.toml" ]]; then + printf '%s\n' "rust/crates/$directory is not a Rust Core crate" >&2 + exit 2 + fi + rustdoc_manifests+=("rust/crates/$directory/Cargo.toml") + done +fi rust_files=() production_files=() @@ -110,7 +126,7 @@ fi # Let Rust understand visibility instead of treating pub items in private # modules as exported APIs. This covers public functions, types, variants, and # fields without requiring documentation for every internal helper. -for manifest in "${crate_manifests[@]}"; do +for manifest in "${rustdoc_manifests[@]}"; do cargo rustdoc --quiet \ --manifest-path "$manifest" \ --lib -- \