diff --git a/.gitattributes b/.gitattributes index 25b2af5..7542ac2 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,42 @@ -*.wave linguist-language=Wave \ No newline at end of file +# Repository text is LF regardless of each contributor's core.autocrlf. +* text=auto eol=lf +*.rs text eol=lf +*.py text eol=lf +meson.build text eol=lf +meson.options text eol=lf +*.sh text eol=lf +*.ps1 text eol=lf +*.toml text eol=lf +*.json text eol=lf +*.yaml text eol=lf +*.yml text eol=lf +*.md text eol=lf +*.txt text eol=lf +*.ws text eol=lf +*.lock text eol=lf +*.wave text eol=lf linguist-language=Wave +*.cmd text eol=crlf +*.bat text eol=crlf +*.png binary +*.jpg binary +*.jpeg binary +*.gif binary +*.webp binary +*.ico binary +*.pdf binary +*.zip binary +*.gz binary +*.xz binary +*.bz2 binary +*.tar binary +*.7z binary +*.exe binary +*.dll binary +*.so binary +*.a binary +*.o binary +*.lib binary +*.wasm binary +*.woff binary +*.woff2 binary +*.bin binary diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 391f3cd..494c503 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,3 +1,7 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 name: CI on: @@ -22,6 +26,16 @@ jobs: runs-on: ubuntu-24.04 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + fetch-depth: 0 + ref: ${{ github.event.pull_request.head.sha || github.sha }} + - name: Verify DCO on contribution commits + if: github.event_name == 'pull_request' + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + GITHUB_TOKEN: ${{ github.token }} + run: python3 tools/check_dco.py --base "$BASE_SHA" --head "$HEAD_SHA" - name: Install Rust toolchain run: | rustup toolchain install 1.96.0 --profile minimal --component rustfmt,clippy @@ -29,12 +43,10 @@ jobs: - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7 with: python-version: '3.11' - - run: python tools/repository_checks.py - - run: python tools/check_links.py --external - - run: python tools/dependency_audit.py - - run: cargo run --locked --example parser_fuzz -- 20261005 2000 - - run: cargo fmt --check - - run: cargo clippy --workspace --locked --all-targets -- -D warnings + - name: Install build automation + run: python -m pip install -r tools/requirements-build.txt ninja==1.13.0 + - run: meson setup build + - run: meson compile -C build quality platform: name: Platform / ${{ matrix.id }} timeout-minutes: 180 @@ -94,6 +106,8 @@ jobs: extension: tar.gz steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false - name: Install Rust toolchain if: matrix.executor == 'native' run: | @@ -101,27 +115,41 @@ jobs: rustup toolchain install 1.96.0 --profile minimal --component rustfmt,clippy rustup default 1.96.0 - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7 - if: matrix.executor == 'native' + if: matrix.executor != 'vm' with: python-version: '3.11' + - name: Install build automation + if: matrix.executor == 'native' + run: python -m pip install -r tools/requirements-build.txt ninja==1.13.0 - name: Complete native acceptance if: matrix.executor == 'native' env: GH_TOKEN: ${{ github.token }} - run: python tools/ci_platform.py ${{ matrix.id }} + run: | + meson setup build -Drelease_targets=${{ matrix.target }} -Dacceptance_platform=${{ matrix.id }} + meson compile -C build acceptance - name: Register target execution if: matrix.executor == 'qemu' uses: docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 with: image: tonistiigi/binfmt@sha256:465d3fdd28d0f2b871ba4b4ec98bd183292e96167f00d9fd40bd249f8632d705 platforms: riscv64,loong64 + - name: Install amd64 cross-build toolchain + if: matrix.executor == 'qemu' + run: | + rustup set default-host x86_64-unknown-linux-gnu + rustup toolchain install 1.96.0 --profile minimal + rustup default 1.96.0 + rustup target add ${{ matrix.target }} - name: Complete emulated acceptance if: matrix.executor == 'qemu' shell: bash + env: + GH_TOKEN: ${{ github.token }} run: | - docker run --rm --platform '${{ matrix.oci_platform }}' \ - -v "$PWD:/work" -w /work '${{ matrix.image }}' \ - sh tools/ci_guest.sh '${{ matrix.id }}' + python3 -m pip install -r tools/requirements-build.txt ninja==1.13.0 + meson setup build -Drelease_targets=${{ matrix.target }} -Dacceptance_platform=${{ matrix.id }} + meson compile -C build acceptance - name: Complete FreeBSD acceptance if: matrix.executor == 'vm' uses: vmactions/freebsd-vm@c46abacb49f09938ca4e1702d15d836285d694cc # v1 diff --git a/.github/workflows/dependency-audit.yml b/.github/workflows/dependency-audit.yml index 7dc0af1..b076cd7 100644 --- a/.github/workflows/dependency-audit.yml +++ b/.github/workflows/dependency-audit.yml @@ -1,3 +1,7 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 name: Dependency audit on: schedule: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 5bc9f81..dd90d9b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,3 +1,7 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 name: Release on: @@ -78,7 +82,7 @@ jobs: python tools/release_version.py "$RELEASE_VERSION" - cargo_version="$(python x.py --version | awk '{print $2}')" + cargo_version="$(python tools/build_config.py version)" if [[ "$cargo_version" != "$RELEASE_VERSION" ]]; then echo "error: Cargo.toml version is $cargo_version, input is $RELEASE_VERSION" >&2 exit 1 @@ -96,8 +100,12 @@ jobs: - name: Audit locked release dependencies run: python tools/dependency_audit.py + - name: Install build automation + run: python -m pip install -r tools/requirements-build.txt ninja==1.13.0 - name: Run release validation - run: python x.py check + run: | + meson setup build + meson compile -C build check build: name: Package / ${{ matrix.id }} @@ -166,6 +174,7 @@ jobs: with: ref: ${{ needs.validate.outputs.commit }} fetch-depth: 0 + persist-credentials: false - name: Install Rust toolchain if: matrix.executor == 'native' run: | @@ -173,27 +182,41 @@ jobs: rustup toolchain install 1.96.0 --profile minimal --component rustfmt,clippy rustup default 1.96.0 - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7 - if: matrix.executor == 'native' + if: matrix.executor != 'vm' with: python-version: '3.11' + - name: Install build automation + if: matrix.executor == 'native' + run: python -m pip install -r tools/requirements-build.txt ninja==1.13.0 - name: Complete native acceptance if: matrix.executor == 'native' env: GH_TOKEN: ${{ github.token }} - run: python tools/ci_platform.py ${{ matrix.id }} + run: | + meson setup build -Drelease_targets=${{ matrix.target }} -Dacceptance_platform=${{ matrix.id }} + meson compile -C build acceptance - name: Register target execution if: matrix.executor == 'qemu' uses: docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 with: image: tonistiigi/binfmt@sha256:465d3fdd28d0f2b871ba4b4ec98bd183292e96167f00d9fd40bd249f8632d705 platforms: riscv64,loong64 + - name: Install amd64 cross-build toolchain + if: matrix.executor == 'qemu' + run: | + rustup set default-host x86_64-unknown-linux-gnu + rustup toolchain install 1.96.0 --profile minimal + rustup default 1.96.0 + rustup target add ${{ matrix.target }} - name: Complete emulated acceptance if: matrix.executor == 'qemu' shell: bash + env: + GH_TOKEN: ${{ github.token }} run: | - docker run --rm --platform '${{ matrix.oci_platform }}' \ - -v "$PWD:/work" -w /work '${{ matrix.image }}' \ - sh tools/ci_guest.sh '${{ matrix.id }}' + python3 -m pip install -r tools/requirements-build.txt ninja==1.13.0 + meson setup build -Drelease_targets=${{ matrix.target }} -Dacceptance_platform=${{ matrix.id }} + meson compile -C build acceptance - name: Complete FreeBSD acceptance if: matrix.executor == 'vm' uses: vmactions/freebsd-vm@c46abacb49f09938ca4e1702d15d836285d694cc # v1 @@ -244,6 +267,9 @@ jobs: with: python-version: "3.11" + - name: Install build automation + run: python -m pip install -r tools/requirements-build.txt ninja==1.13.0 + - name: Download release archives uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 with: @@ -256,16 +282,8 @@ jobs: run: | set -euo pipefail - python x.py checksum \ - x86_64-unknown-linux-gnu \ - aarch64-unknown-linux-gnu \ - riscv64gc-unknown-linux-gnu \ - loongarch64-unknown-linux-gnu \ - x86_64-apple-darwin \ - aarch64-apple-darwin \ - x86_64-pc-windows-msvc \ - aarch64-pc-windows-msvc \ - x86_64-unknown-freebsd + meson setup build -Drelease_targets=x86_64-unknown-linux-gnu,aarch64-unknown-linux-gnu,riscv64gc-unknown-linux-gnu,loongarch64-unknown-linux-gnu,x86_64-apple-darwin,aarch64-apple-darwin,x86_64-pc-windows-msvc,aarch64-pc-windows-msvc,x86_64-unknown-freebsd + meson compile -C build checksum cd dist sha256sum --check SHA256SUMS diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 05e05f7..fc9b245 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -27,13 +27,13 @@ boundaries or a persistent file format. You need: - Rust 1.96.0 with its `rustfmt` and `clippy` components -- Python 3.11 or newer for `x.py` release tooling +- Python 3.11 or newer, Meson 1.8.5+ and Ninja for repository automation - Git for dependency integration tests - a compatible `wavec` in `PATH` for end-to-end build and run tests `rust-toolchain.toml`, workspace `rust-version`, CI, and release builds select 1.96.0. This is the first supported toolchain and MSRV; changing it requires a -reviewed change to all four and native platform validation. `x.py` also selects +reviewed change to all four and native platform validation. Meson automation also selects the pinned toolchain when a caller has set a different `RUSTUP_TOOLCHAIN`. Set `VEX_WAVEC=/path/to/wavec` when testing a specific compiler binary. @@ -47,10 +47,12 @@ cargo clippy --workspace --locked --all-targets -- -D warnings cargo build --workspace --locked ``` -The same baseline is available through the repository release tool: +The same baseline is available through Meson (including the Python tooling tests): ```sh -python3 x.py check +python3 -m pip install -r tools/requirements-build.txt ninja==1.13.0 +meson setup build +meson compile -C build check ``` ## Making a change @@ -74,7 +76,7 @@ Add tests at the same level as the behavior being changed: - parser and policy details belong in unit tests - dependency graph and Git behavior belong in integration tests - compiler invocation changes require dry-run schema and end-to-end smoke tests -- release-tool changes require `python3 -m unittest discover -s tests/xpy -v` +- release-tool changes require `python3 -m unittest discover -s tests/tooling -v` - package changes require archive-content, checksum, and executable smoke tests - platform changes must preserve native integration coverage where a hosted runner exists; cross-build-only targets must be documented as experimental @@ -106,9 +108,9 @@ The official Wave v0.2.0-pre-beta archive lacks the canonical package import contract used by current Vex; do not treat its Hello World success as full package compatibility. -Release packages are created with `python3 x.py build` followed by -`python3 x.py package`. Do not hand-edit `dist/` artifacts. The stricter -`python3 x.py release` command is reserved for a clean commit carrying the exact +Release packages are created with `meson compile -C build build-release` followed by +`meson compile -C build package`. Do not hand-edit `dist/` artifacts. The stricter +`meson compile -C build release` command is reserved for a clean commit carrying the exact annotated `v` tag. Maintainers must follow [RELEASING.md](RELEASING.md) for multi-platform artifact aggregation and publication. @@ -191,3 +193,27 @@ references and missing platform lanes. No dependency-update bot is enabled. CI uses PR runs for feature branches and push runs for master. Superseded runs with the same PR/branch identity are cancelled; release runs use their separate, non-cancelling concurrency group. + +## Source licensing and line endings + +Own Rust source (including executable test fixtures), Python/shell/PowerShell and +Windows command scripts, TOML and YAML configuration carry the full MPL 2.0 source +notice plus `SPDX-License-Identifier: MPL-2.0` near the start, after any shebang. +Copyright attribution remains centralized in the existing project files. +Third-party/vendor files keep their original ownership. Generated Cargo locks, +CLI manuals/completions and notices are not relabeled. JSON and exact WSON/lock/ +Wave syntax fixtures are exempt where comments would change meaning or diagnostics. + +Text defaults to LF through `.gitattributes`; cmd/bat scripts use CRLF. Declared +binary formats are not normalized. This policy's normalization is grouped in the +repository-policy commit. `python3 tools/source_policy.py` checks both source +headers and worktree line endings without fixing files implicitly. + +The existing read-only Quality CI checks every contribution commit in the PR's +exact `base..head` range. Old base history is not checked retroactively. Each +commit needs a real author-matching `Signed-off-by: Name ` trailer; bots +and ordinary merges are not exempt. Only GitHub-generated merges verified by +GitHub's API and signature metadata receive the merge exception. Synthetic PR +merge refs are not used as contribution heads. No DCO application or repository +write token is used. Repair your own missing certification with +`git commit --amend -s`, or rebase and sign off the affected contribution commits. diff --git a/Cargo.lock b/Cargo.lock index ac960ee..e197725 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -40,11 +40,11 @@ checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" [[package]] name = "block-buffer" -version = "0.10.4" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" dependencies = [ - "generic-array", + "hybrid-array", ] [[package]] @@ -101,10 +101,17 @@ dependencies = [ "diagnostic", "process", "serde_json", + "sha2", "state", "toolchain", ] +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + [[package]] name = "core-foundation-sys" version = "0.8.7" @@ -113,9 +120,9 @@ checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" [[package]] name = "cpufeatures" -version = "0.2.17" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" dependencies = [ "libc", ] @@ -131,12 +138,11 @@ dependencies = [ [[package]] name = "crypto-common" -version = "0.1.7" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" dependencies = [ - "generic-array", - "typenum", + "hybrid-array", ] [[package]] @@ -145,11 +151,12 @@ version = "0.0.2-beta" [[package]] name = "digest" -version = "0.10.7" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ "block-buffer", + "const-oid", "crypto-common", ] @@ -216,22 +223,21 @@ dependencies = [ "percent-encoding", ] -[[package]] -name = "generic-array" -version = "0.14.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" -dependencies = [ - "typenum", - "version_check", -] - [[package]] name = "hashbrown" version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -408,6 +414,9 @@ name = "lockfile" version = "0.0.2-beta" dependencies = [ "diagnostic", + "serde", + "serde_json", + "sha2", "source", "wson", ] @@ -424,6 +433,7 @@ version = "0.0.2-beta" dependencies = [ "diagnostic", "semver", + "serde_json", "source", "wson", ] @@ -553,6 +563,7 @@ dependencies = [ "sha2", "source", "state", + "wson", ] [[package]] @@ -625,9 +636,9 @@ dependencies = [ [[package]] name = "sha2" -version = "0.10.9" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" dependencies = [ "cfg-if", "cpufeatures", @@ -657,6 +668,7 @@ name = "source" version = "0.0.2-beta" dependencies = [ "percent-encoding", + "serde", "url", ] @@ -781,12 +793,6 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" -[[package]] -name = "version_check" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" - [[package]] name = "vex" version = "0.0.2-beta" @@ -802,6 +808,7 @@ dependencies = [ "source", "state", "toolchain", + "wson", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index a730fce..39b3253 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,3 +1,7 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 [package] name = "vex" version.workspace = true @@ -37,6 +41,7 @@ state = { path = "state" } serde_json = "1.0" [dependencies] +wson.workspace = true diagnostic.workspace = true serde_json.workspace = true process.workspace = true diff --git a/MAINTAINERS b/MAINTAINERS index a4a8355..ff9ca60 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -27,8 +27,10 @@ M: LunaStev F: .github/ F: Cargo.toml F: Cargo.lock -F: x.py -F: tests/xpy/ +F: meson.build +F: meson.options +F: tools/ +F: tests/tooling/ F: RELEASING.md [Documentation and Community] diff --git a/README.md b/README.md index 6d9096e..d7edf5c 100644 --- a/README.md +++ b/README.md @@ -500,55 +500,72 @@ Vex/ └── wson/ # shared versioned string/parser boundary ``` -The repository-level `x.py` script is the supported entry point for release -builds and packages. It reads the version from `Cargo.toml`, always builds with -the committed `Cargo.lock`, and writes archives plus `SHA256SUMS` to `dist/`. -Run it with Python 3.11 or newer: +Meson is the supported repository automation entry point. Cargo continues to +own Rust dependencies, the committed `Cargo.lock`, compilation and incremental +build decisions. Python 3.11+, Meson 1.8.5+ and Ninja are required. In a Python +virtual environment, install the pinned automation version and Ninja: ```sh -# Show the host and every supported release target. -python3 x.py list-targets +python3 -m pip install -r tools/requirements-build.txt ninja==1.13.0 +meson setup build -# Run formatting, release-tool tests, Rust tests, Clippy, and a debug build. -python3 x.py check +# Show every supported release target. +meson compile -C build list-targets -# Build and package the native target. -python3 x.py build -python3 x.py package +# Formatting, tooling tests, Rust tests, Clippy and a workspace debug build. +meson compile -C build check -# Build or package one or more explicit targets. -python3 x.py build x86_64-unknown-linux-gnu -python3 x.py package x86_64-unknown-linux-gnu +# Default compilation builds the Cargo workspace in debug mode. +meson compile -C build -# Verify an assembled target set and regenerate its checksums. -python3 x.py checksum x86_64-unknown-linux-gnu +# Run the Python and Rust suites, with Meson test reports. +meson test -C build --print-errorlogs + +# Build and package the native target; archives and SHA256SUMS go to dist/. +meson compile -C build build-release +meson compile -C build package + +# Select one or more release triples (comma-separated), then build/package. +meson configure build -Drelease_targets=x86_64-unknown-linux-gnu +meson compile -C build build-release +meson compile -C build package +meson compile -C build checksum ``` +`package` validates existing binaries; it does not silently build missing ones. +Every build request reaches Cargo, even with unchanged Meson configuration; +Cargo decides whether recompilation is necessary. `meson compile -C build +clean-artifacts` runs Cargo clean and removes `dist/`. Ninja's ordinary `clean` +only cleans files owned by Meson. Keep separate build directories for different +release target sets when needed. + Archives contain the Vex executable together with `README.md`, `LICENSE`, `NOTICE`, `COPYRIGHT`, and `THIRD_PARTY_LICENSES`. Their file order, permissions, owners, and timestamps are normalized. Set `SOURCE_DATE_EPOCH` to an explicit non-negative Unix timestamp when reproducing an artifact outside the tagged source revision. -`python3 x.py release [...]` is intentionally stricter than separate -build and package commands. It runs the complete validation suite and succeeds -only when the working tree is clean and `HEAD` has the exact `v` tag. +`meson compile -C build release` is intentionally stricter than separate +build and package commands. It first verifies the release source, then runs the complete validation suite, +builds and packages the configured targets. It succeeds only when the working tree is clean and `HEAD` has the exact `v` tag. Cross-target builds still require the corresponding Rust target and native linker to be installed. `VEX_RELEASE_HOST` exists for release infrastructure that must override host-target detection; normal development should not set it. Packaging requires successful version/help execution, natively or through the configured QEMU/Wine verifier. A missing verifier fails before replacing an -existing archive. `x.py package --allow-unverified` permits an unverified +existing archive. `meson configure build -Dallow_unverified=true` followed by `package` permits an unverified development archive only when no verifier is available; it cannot suppress a -failed smoke test and is not accepted by `x.py release`. +failed smoke test and causes `release` to fail before validation or builds. Each packaged archive produces one JSON line on stdout with `schema_version: 1`, `archive`, `sha256`, `target`, `version`, `verification` (`verified` or `unverified`) and `verifier` (`native`, emulator name, or null). Progress remains -on stderr. These are packaging reports, separate from Vex command message files. +on stderr in the artifact helper. Meson/Ninja also print task logs when running +the automation target. These packaging reports are separate from Vex command +message files. -`python3 x.py verify-release` checks that the source tree is clean and `HEAD` +`meson compile -C build verify-release` checks that the source tree is clean and `HEAD` has the annotated `v` tag for local release reproduction. For an official release, a maintainer dispatches the Release workflow from `wavefnd/Vex:master`; the workflow refuses forks and non-`master` refs. It @@ -594,3 +611,49 @@ CLI help, field types, environment variables, streams, and machine-readable sche Vex supports manifest-owned prebuilt native inputs and Wave object/shared outputs. See [native interoperability](docs/native-interop.md) for C, C++ and Rust C ABI contracts, target-specific paths, artifact ownership and runtime prerequisites. + +Format 4 projects can share a lockfile and output directory using explicit +[workspaces](docs/workspaces.md), selected with `-p ` or `--workspace`. + +Create a separate format 4 project with `vex new app`; invalid inferred names are +rejected, so use `vex new my-app --name my_app` explicitly. Git initialization is +opt-in with `--git`. Existing destinations, including empty directories, remain +untouched. An interrupted scaffold keeps its recovery journal in the new project. + +```sh +vex add utility --path ../utility --offline +vex add utility --git https://example.org/utility.git --tag v1.0.0 +vex add short_name --git https://example.org/utility.git --package-name utility --version-req '^1' +vex remove utility --offline +``` + +`add`/`remove` change direct dependencies only and preserve unrelated comments and +formatting. A durable journal coordinates `vex.ws` and the root `vex.lock`; +failed resolution restores both. A normal `fetch` recovers interrupted edits, +while dry-run and metadata report pending recovery without modifying files. +Use `-p ` when editing a workspace. Legacy string meaning is preserved; +values that cannot be represented safely require explicit manifest migration. + +The installed binary includes CLI tooling generators, keeping release archives' +existing layout: `vex completions bash|zsh|fish|powershell` and `vex manpage` print +installable scripts and the `vex(1)` manual. No compiler or network is queried. +The checked-in [command reference](docs/commands.md), `docs/completions/`, and +`docs/vex.1` are generated from `tools/command-spec.json`; CI verifies drift. + +Format 4 supports explicit executable tests, each with a normal Wave `main`: + +```wson + targets = { lib = {}, tests = [{ name = "smoke", path = "tests/smoke.wave" }] }, + test_dependencies = [{ name = "fixtures", path = "../fixtures" }] +``` + +`vex test [name-substring] [--locked] [--offline] [-- ]` compiles all +selected tests before running them in package/name order. Every selected test +runs; the first failed program's exit code is returned unchanged. Test results +appear as `test_result` events in `--message-file` JSONL; program stdio is inherited. +No test result is cached. Compilation failures stop the batch. Cross targets +require a compiler-supported runner and otherwise fail before execution. +Test dependencies are fetched into the union lock, selected only for a root test +invocation, and never propagated as a dependency's ordinary imports. Query them +with `tree` or `metadata --include-tests --format-version 2`. +Wave's compiler-native unit-test harness remains unsupported until Wave adds it. diff --git a/RELEASING.md b/RELEASING.md index 81ef52d..37c9712 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -10,7 +10,7 @@ the dispatcher's explicit choice. - `Cargo.toml` is the single source of truth for the Vex version. - Official versions are normal `x.y.z` or SemVer prereleases. Build metadata - (`+...`) is not supported. `tools/release_version.py` is shared by x.py and the + (`+...`) is not supported. `tools/release_version.py` is shared by the Meson artifact tools and the workflow; leading zero numeric identifiers and empty prerelease parts are errors. - Rust 1.96.0 is the pinned release toolchain and initial supported MSRV. Keep `rust-toolchain.toml`, all workspace rust-version declarations, and CI/release @@ -72,7 +72,9 @@ checklist before tagging: 5. Run the complete local validation suite: ```sh - python3 x.py check + python3 -m pip install -r tools/requirements-build.txt ninja==1.13.0 + meson setup build + meson compile -C build check ``` 6. Run a real product smoke with a compatible `wavec`: initialize a temporary diff --git a/THIRD_PARTY_LICENSES b/THIRD_PARTY_LICENSES index 5d8806b..538a544 100644 --- a/THIRD_PARTY_LICENSES +++ b/THIRD_PARTY_LICENSES @@ -1,7 +1,7 @@ Third-party dependency notices for Vex ===================================== -Cargo.lock SHA-256 (LF): db7d1a6e1117beb5db479def50e45bdf4f24fcbd2d766bd655ba68373f60f621 +Cargo.lock SHA-256 (LF): 2603e5dfcd8fd9e451a03b538001787c14326665debd9872cd02a4ddfc865284 Generated by tools/dependency_notices.py from Cargo's locked package sources. Includes build-time and platform-specific dependencies; a given binary may @@ -41,7 +41,7 @@ Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 9 LICENSE-MIT: Text 11 -block-buffer 0.10.4 +block-buffer 0.12.1 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 12 @@ -81,17 +81,23 @@ Declared license: MPL-2.0 Source: registry+https://github.com/rust-lang/crates.io-index LICENSE: Text 19 +const-oid 0.10.2 +Declared license: Apache-2.0 OR MIT +Source: registry+https://github.com/rust-lang/crates.io-index + LICENSE-APACHE: Text 12 + LICENSE-MIT: Text 20 + core-foundation-sys 0.8.7 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 9 - LICENSE-MIT: Text 20 + LICENSE-MIT: Text 21 -cpufeatures 0.2.17 +cpufeatures 0.3.1 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 12 - LICENSE-MIT: Text 21 + LICENSE-MIT: Text 20 crc32fast 1.5.2 Declared license: MIT OR Apache-2.0 @@ -99,13 +105,13 @@ Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 22 LICENSE-MIT: Text 23 -crypto-common 0.1.7 +crypto-common 0.2.2 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 12 LICENSE-MIT: Text 24 -digest 0.10.7 +digest 0.11.3 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 12 @@ -153,15 +159,16 @@ Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 9 LICENSE-MIT: Text 29 -generic-array 0.14.7 -Declared license: MIT -Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE: Text 30 - hashbrown 0.17.1 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 9 + LICENSE-MIT: Text 30 + +hybrid-array 0.4.15 +Declared license: MIT OR Apache-2.0 +Source: registry+https://github.com/rust-lang/crates.io-index + LICENSE-APACHE: Text 12 LICENSE-MIT: Text 31 iana-time-zone 0.1.65 @@ -384,7 +391,7 @@ Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 38 LICENSE-MIT: Text 3 -sha2 0.10.9 +sha2 0.11.1 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 12 @@ -474,12 +481,6 @@ Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 62 LICENSE-MIT: Text 63 -version_check 0.9.5 -Declared license: MIT/Apache-2.0 -Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE-APACHE: Text 9 - LICENSE-MIT: Text 64 - wasm-bindgen 0.2.114 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index @@ -507,44 +508,44 @@ Source: registry+https://github.com/rust-lang/crates.io-index windows-core 0.62.2 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - license-apache-2.0: Text 65 - license-mit: Text 66 + license-apache-2.0: Text 64 + license-mit: Text 65 windows-implement 0.60.2 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - license-apache-2.0: Text 65 - license-mit: Text 66 + license-apache-2.0: Text 64 + license-mit: Text 65 windows-interface 0.59.3 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - license-apache-2.0: Text 65 - license-mit: Text 66 + license-apache-2.0: Text 64 + license-mit: Text 65 windows-link 0.2.1 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - license-apache-2.0: Text 65 - license-mit: Text 66 + license-apache-2.0: Text 64 + license-mit: Text 65 windows-result 0.4.1 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - license-apache-2.0: Text 65 - license-mit: Text 66 + license-apache-2.0: Text 64 + license-mit: Text 65 windows-strings 0.5.1 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - license-apache-2.0: Text 65 - license-mit: Text 66 + license-apache-2.0: Text 64 + license-mit: Text 65 windows-sys 0.61.2 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - license-apache-2.0: Text 65 - license-mit: Text 66 + license-apache-2.0: Text 64 + license-mit: Text 65 writeable 0.6.3 Declared license: Unicode-3.0 @@ -560,7 +561,7 @@ xattr 1.6.1 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 9 - LICENSE-MIT: Text 67 + LICENSE-MIT: Text 66 yoke 0.8.3 Declared license: Unicode-3.0 @@ -600,12 +601,12 @@ Source: registry+https://github.com/rust-lang/crates.io-index zip 9.0.4 Declared license: MIT Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE: Text 68 + LICENSE: Text 67 zlib-rs 0.6.8 Declared license: Zlib Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE: Text 69 + LICENSE: Text 68 zmij 1.0.23 Declared license: MIT @@ -615,7 +616,7 @@ Source: registry+https://github.com/rust-lang/crates.io-index zopfli 0.8.3 Declared license: Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - COPYING: Text 70 + COPYING: Text 69 Text 1 ======================================================================== @@ -1424,7 +1425,7 @@ limitations under the License. Text 13 ======================================================================== -Copyright (c) 2018-2019 The RustCrypto Project Developers +Copyright (c) 2018-2025 The RustCrypto Project Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated @@ -2167,7 +2168,7 @@ Exhibit B - "Incompatible With Secondary Licenses" Notice Text 20 ======================================================================== -Copyright (c) 2012-2013 Mozilla Foundation +Copyright (c) 2020-2026 The RustCrypto Project Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated @@ -2195,7 +2196,7 @@ DEALINGS IN THE SOFTWARE. Text 21 ======================================================================== -Copyright (c) 2020-2025 The RustCrypto Project Developers +Copyright (c) 2012-2013 Mozilla Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated @@ -2451,7 +2452,7 @@ SOFTWARE. Text 24 ======================================================================== -Copyright (c) 2021 RustCrypto Developers +Copyright (c) 2021-2026 RustCrypto Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated @@ -2479,6 +2480,7 @@ DEALINGS IN THE SOFTWARE. Text 25 ======================================================================== +Copyright (c) 2017-2025 RustCrypto Developers Copyright (c) 2017 Artyom Pavlov Permission is hereby granted, free of charge, to any @@ -2619,31 +2621,35 @@ DEALINGS IN THE SOFTWARE. Text 30 ======================================================================== -The MIT License (MIT) - -Copyright (c) 2015 Bartłomiej Kamiński +Copyright (c) 2016 Amanieu d'Antras -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. Text 31 ======================================================================== -Copyright (c) 2016 Amanieu d'Antras +Copyright (c) 2022-2026 The RustCrypto Project Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated @@ -3863,9 +3869,10 @@ at your option. Text 49 ======================================================================== -Copyright (c) 2006-2009 Graydon Hoare -Copyright (c) 2009-2013 Mozilla Foundation +Copyright (c) 2016-2026 The RustCrypto Project Developers Copyright (c) 2016 Artyom Pavlov +Copyright (c) 2009-2013 Mozilla Foundation +Copyright (c) 2006-2009 Graydon Hoare Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated @@ -4602,28 +4609,6 @@ DEALINGS IN THE SOFTWARE. Text 64 ======================================================================== -The MIT License (MIT) -Copyright (c) 2017-2018 Sergio Benitez - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -Text 65 -======================================================================== Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ @@ -4826,7 +4811,7 @@ Apache License See the License for the specific language governing permissions and limitations under the License. -Text 66 +Text 65 ======================================================================== MIT License @@ -4850,7 +4835,7 @@ MIT License OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE -Text 67 +Text 66 ======================================================================== Copyright (c) 2015 Steven Allen @@ -4878,7 +4863,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Text 68 +Text 67 ======================================================================== The MIT License (MIT) @@ -4902,7 +4887,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Text 69 +Text 68 ======================================================================== (C) 2024 Trifecta Tech Foundation @@ -4924,7 +4909,7 @@ freely, subject to the following restrictions: 3. This notice may not be removed or altered from any source distribution. -Text 70 +Text 69 ======================================================================== Apache License Version 2.0, January 2004 diff --git a/compiler/Cargo.toml b/compiler/Cargo.toml index 3e1d59d..e28b768 100644 --- a/compiler/Cargo.toml +++ b/compiler/Cargo.toml @@ -1,3 +1,7 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 [package] name = "compiler" version.workspace = true @@ -13,3 +17,4 @@ toolchain.workspace = true process.workspace = true serde_json.workspace = true state.workspace = true +sha2 = "0.11.1" diff --git a/compiler/src/freshness.rs b/compiler/src/freshness.rs new file mode 100644 index 0000000..20eacf2 --- /dev/null +++ b/compiler/src/freshness.rs @@ -0,0 +1,482 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +//! Conservative content fingerprints. Unknown compiler/runtime/SDK inputs miss. +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use std::{ + fs, + io::Read, + path::{Path, PathBuf}, + process::Command, + time::Duration, +}; + +#[derive(Clone)] +pub struct Inputs { + sources: Vec, + files: Vec, + standard: PathBuf, + environment: String, + context: String, +} +fn bytes(hash: &mut Sha256, bytes: &[u8]) { + hash.update((bytes.len() as u64).to_le_bytes()); + hash.update(bytes); +} +fn file(hash: &mut Sha256, path: &Path) -> Result<(), String> { + state::reject_link(path)?; + if !fs::metadata(path).map_err(|e| e.to_string())?.is_file() { + return Err("non-regular fingerprint input".into()); + } + bytes( + hash, + &fs::metadata(path) + .map_err(|e| e.to_string())? + .len() + .to_le_bytes(), + ); + bytes( + hash, + path.to_str() + .ok_or("non-UTF-8 fingerprint path")? + .as_bytes(), + ); + let mut reader = fs::File::open(path).map_err(|e| e.to_string())?; + let mut buffer = [0; 65536]; + loop { + let n = reader.read(&mut buffer).map_err(|e| e.to_string())?; + if n == 0 { + break; + } + hash.update(&buffer[..n]); + } + Ok(()) +} +fn tree(hash: &mut Sha256, path: &Path, sources: bool) -> Result<(), String> { + state::reject_link(path)?; + let mut children = fs::read_dir(path) + .map_err(|e| e.to_string())? + .collect::, _>>() + .map_err(|e| e.to_string())?; + children.sort_by_key(|e| e.file_name()); + for child in children { + let path = child.path(); + let name = child.file_name(); + if name == ".git" || (sources && [".vex", "target"].iter().any(|n| name == *n)) { + continue; + } + state::reject_link(&path)?; + let metadata = fs::symlink_metadata(&path).map_err(|e| e.to_string())?; + if metadata.is_dir() { + tree(hash, &path, sources)?; + } else if !sources + || path.extension().is_some_and(|e| e == "wave") + || name == "vex.ws" + || name == "vex.lock" + { + file(hash, &path)?; + } + } + Ok(()) +} +impl Inputs { + pub fn capture( + compiler: &crate::Compiler, + mut sources: Vec, + context: &str, + ) -> Result { + sources.sort(); + sources.dedup(); + let output = process::output( + Command::new(compiler.path()).args(["print", "std-path", "--format=json"]), + Duration::from_secs(60), + )?; + if !output.status.success() { + return Err("compiler cannot describe its standard library".into()); + } + let standard: PathBuf = serde_json::from_slice::>(&output.stdout) + .map_err(|_| "compiler std-path is not a known path")? + .ok_or("standard library path is unknown")? + .into(); + if !standard.is_absolute() || !standard.is_dir() { + return Err("standard library path is unavailable".into()); + } + let mut files = vec![compiler.path().canonicalize().map_err(|e| e.to_string())?]; + // The executable alone does not identify a dynamically linked compiler. + // Other hosts remain functional and conservatively compile every time. + if !cfg!(target_os = "linux") { + return Err("compiler runtime closure is not known on this host".into()); + } + let mut magic = [0; 4]; + fs::File::open(&files[0]) + .and_then(|mut f| f.read_exact(&mut magic)) + .map_err(|e| e.to_string())?; + if magic != *b"\x7fELF" { + return Err("compiler runtime closure requires an ELF executable".into()); + } + let runtime = process::output( + Command::new("/usr/bin/ldd") + .arg(&files[0]) + .env("LC_ALL", "C"), + Duration::from_secs(60), + )?; + if !runtime.status.success() { + return Err("compiler runtime dependency query was unavailable".into()); + } + let text = String::from_utf8(runtime.stdout).map_err(|e| e.to_string())?; + for line in text.lines().map(str::trim).filter(|l| !l.is_empty()) { + if line.starts_with("linux-vdso.so.") { + continue; + } + let path = line + .split_once("=>") + .map_or(line, |(_, tail)| tail.trim()) + .split_whitespace() + .next() + .ok_or("unknown compiler runtime input")?; + if !Path::new(path).is_absolute() || !Path::new(path).is_file() { + return Err("unresolved compiler runtime input".into()); + } + files.push(Path::new(path).canonicalize().map_err(|e| e.to_string())?); + } + files.sort(); + files.dedup(); + let mut environment = std::env::vars_os() + .filter(|(name, _)| { + let name = name.to_string_lossy(); + name.starts_with("WAVE_") + || name.starts_with("LLVM_") + || name.starts_with("CLANG_") + || name.starts_with("DYLD_") + || matches!( + name.as_ref(), + "PATH" + | "PATHEXT" + | "HOME" + | "USERPROFILE" + | "SDKROOT" + | "MACOSX_DEPLOYMENT_TARGET" + | "LIBRARY_PATH" + | "LD_LIBRARY_PATH" + | "LD_PRELOAD" + | "LIB" + | "INCLUDE" + | "CC" + | "CXX" + ) + }) + .collect::>(); + environment.sort(); + let environment = format!("{environment:?}"); + Ok(Self { + sources, + files, + standard, + environment, + context: context.into(), + }) + } + pub fn fingerprint(&self) -> Result { + let mut hash = Sha256::new(); + bytes(&mut hash, b"vex.freshness.v1"); + bytes(&mut hash, env!("CARGO_PKG_VERSION").as_bytes()); + bytes(&mut hash, self.environment.as_bytes()); + bytes(&mut hash, self.context.as_bytes()); + for source in &self.sources { + tree(&mut hash, source, true)?; + } + tree(&mut hash, &self.standard, false)?; + for input in &self.files { + file(&mut hash, input)?; + } + Ok(hex_digest(hash.finalize())) + } +} + +pub(crate) fn key( + base: &str, + plan: &Value, + args: &[String], + generation: Option<&Path>, +) -> Result { + if !plan["sysroot"].is_null() { + return Err("SDK/sysroot contents are not fully declared".into()); + } + let mut hash = Sha256::new(); + bytes(&mut hash, base.as_bytes()); + if !plan["link"].is_null() { + // Hosted links include implicit system libraries and SDK selection. + if !plan["target"] + .as_str() + .is_some_and(|t| t.starts_with("wasm")) + { + return Err("linker/SDK closure is not completely declared".into()); + } + let program = plan["link"]["program"] + .as_str() + .ok_or("linker program missing")?; + if !Path::new(program).is_absolute() { + return Err("linker identity is not absolute".into()); + } + file(&mut hash, Path::new(program))?; + let compiled = plan["compile"] + .as_array() + .ok_or("compile jobs missing")? + .iter() + .filter_map(|job| job["output"].as_str()) + .collect::>(); + for input in plan["link"]["inputs"] + .as_array() + .ok_or("linker inputs unknown")? + { + let input = input.as_str().ok_or("linker input missing")?; + if !compiled.contains(input) { + file(&mut hash, Path::new(input))?; + } + } + let runtime = process::output( + Command::new("/usr/bin/ldd").arg(program).env("LC_ALL", "C"), + Duration::from_secs(60), + )?; + if !runtime.status.success() { + return Err("linker runtime closure unknown".into()); + } + for line in String::from_utf8(runtime.stdout) + .map_err(|e| e.to_string())? + .lines() + .map(str::trim) + .filter(|l| !l.is_empty()) + { + if line.starts_with("linux-vdso.so.") { + continue; + } + let path = line + .split_once("=>") + .map_or(line, |(_, tail)| tail.trim()) + .split_whitespace() + .next() + .ok_or("unknown linker runtime input")?; + if !Path::new(path).is_absolute() { + return Err("unresolved linker runtime input".into()); + } + file( + &mut hash, + &Path::new(path).canonicalize().map_err(|e| e.to_string())?, + )?; + } + for arg in plan["link"]["args"] + .as_array() + .ok_or("linker arguments unknown")? + { + let value = arg.as_str().ok_or("linker argument unknown")?; + if ["-l", "-L", "@"] + .iter() + .any(|prefix| value.starts_with(prefix)) + || value.contains("sysroot") + || value.contains("script") + { + return Err( + "linker contains implicit libraries, SDK, script or response inputs".into(), + ); + } + } + } + if args.iter().any(|a| { + a.starts_with("--sysroot=") + || a.starts_with("-Clink-sysroot=") + || a.starts_with("-Csysroot=") + || a.starts_with("-Clinker=") + || a.starts_with("--linker-script") + }) { + return Err("external SDK or linker input closure is unknown".into()); + } + for input in plan["inputs"].as_array().ok_or("plan inputs missing")? { + if input["kind"] == "wave" { + file( + &mut hash, + Path::new(input["path"].as_str().ok_or("input path missing")?), + )?; + } + if input["kind"] != "wave" { + if ![ + "obj", + "object", + "archive", + "static_library", + "shared_library", + ] + .iter() + .any(|kind| input["kind"] == *kind) + { + return Err("native source dependency closure is unknown".into()); + } + file( + &mut hash, + Path::new(input["path"].as_str().ok_or("input path missing")?), + )?; + } + } + let normalize = |text: &str| { + generation.and_then(|p| p.to_str()).map_or_else( + || text.to_owned(), + |g| text.replace(g, "target/.vex-run/GENERATION"), + ) + }; + let mut normalized = plan.clone(); + normalized["execute"] = Value::Null; + bytes(&mut hash, normalize(&normalized.to_string()).as_bytes()); + for arg in args { + if arg != "--run" { + bytes(&mut hash, normalize(arg).as_bytes()); + } + } + Ok(hex_digest(hash.finalize())) +} +fn content_digest(path: &Path) -> Result { + state::reject_link(path)?; + if !path.is_file() { + return Err("cached output is not a regular file".into()); + } + let bytes = fs::read(path).map_err(|e| e.to_string())?; + Ok(hex_digest(Sha256::digest(bytes))) +} +fn directory(root: &Path, key: &str) -> PathBuf { + root.join("target/.vex-cache").join(key) +} +fn check_key(key: &str) -> bool { + key.len() == 64 && key.bytes().all(|b| b.is_ascii_hexdigit()) +} +pub(crate) fn restore( + root: &Path, + key: &str, + outputs: &[PathBuf], + optional: &[PathBuf], +) -> Result { + if !check_key(key) { + return Err("invalid freshness key".into()); + } + state::reject_link(&root.join("target"))?; + state::reject_link(&root.join("target/.vex-cache"))?; + let directory = directory(root, key); + state::reject_link(&directory)?; + state::reject_link(&directory.join("record.json"))?; + if fs::metadata(directory.join("record.json")).is_ok_and(|m| !m.is_file() || m.len() > 262144) { + return Err("invalid cache metadata file".into()); + } + let Ok(raw) = fs::read(directory.join("record.json")) else { + return Ok(false); + }; + let record: Value = serde_json::from_slice(&raw).map_err(|_| "corrupt freshness record")?; + if record["version"] != 1 || record["key"] != key { + return Err("unsupported freshness record".into()); + } + let files = record["files"].as_array().ok_or("missing cache outputs")?; + let destinations = outputs.iter().chain(optional).collect::>(); + if files.len() != destinations.len() { + return Err("cache output shape changed".into()); + } + for (index, entry) in files.iter().enumerate() { + if entry.is_null() { + if index < outputs.len() { + return Err("required cached output missing".into()); + } + continue; + } + let path = directory.join(index.to_string()); + state::reject_link(&path)?; + if content_digest(&path)? != entry.as_str().ok_or("invalid cache digest")? { + return Err("cached output content was modified".into()); + } + } + for (index, (entry, destination)) in files.iter().zip(destinations).enumerate() { + if entry.is_null() { + if destination.exists() { + fs::remove_file(destination).map_err(|e| e.to_string())?; + } + continue; + } + create_parents(root, destination)?; + // A fresh inode is essential for independent running generations. + fs::copy(directory.join(index.to_string()), destination).map_err(|e| e.to_string())?; + } + Ok(true) +} +fn create_parents(root: &Path, path: &Path) -> Result<(), String> { + let path = if path.is_absolute() { + path.to_path_buf() + } else { + root.join(path) + }; + let relative = path + .parent() + .unwrap() + .strip_prefix(root) + .map_err(|_| "output outside project")?; + let mut parent = root.to_path_buf(); + for component in relative.components() { + parent.push(component); + state::ensure_dir(&parent)?; + } + Ok(()) +} +pub(crate) fn store( + root: &Path, + key: &str, + outputs: &[PathBuf], + optional: &[PathBuf], +) -> Result<(), String> { + if !check_key(key) { + return Err("invalid freshness key".into()); + } + let directory = directory(root, key); + // Never replace an unknown or corrupted cache entry implicitly. + if fs::symlink_metadata(&directory).is_ok() { + return Ok(()); + } + let mut entries = Vec::new(); + let mut sources = Vec::new(); + for (index, path) in outputs.iter().chain(optional).enumerate() { + state::reject_link(path)?; + if !path.is_file() && index >= outputs.len() { + entries.push(Value::Null); + continue; + } + entries.push(json!(content_digest(path)?)); + sources.push((index, path)); + } + let record = directory.join("record.json"); + let mut owned = sources + .iter() + .map(|(i, _)| directory.join(i.to_string())) + .collect::>(); + owned.push(record.clone()); + let batch = state::artifacts::Batch::prepare(root, owned) + .map_err(|e| format!("cannot own cache: {e}"))?; + create_parents(root, &record)?; + for (index, path) in sources { + fs::copy(path, directory.join(index.to_string())).map_err(|e| e.to_string())?; + } + state::edit::replace( + &record, + &json!({"version":1,"key":key,"files":entries}).to_string(), + )?; + batch.verify_outputs()?; + batch.finish() +} +// Keep persisted IDs/checksums as zero-padded lowercase SHA-256 hex. The +// digest output type no longer implements LowerHex in sha2 0.11. +fn hex_digest(bytes: impl AsRef<[u8]>) -> String { + const DIGITS: &[u8; 16] = b"0123456789abcdef"; + bytes + .as_ref() + .iter() + .flat_map(|&byte| { + [ + char::from(DIGITS[(byte >> 4) as usize]), + char::from(DIGITS[(byte & 15) as usize]), + ] + }) + .collect() +} diff --git a/compiler/src/invocation.rs b/compiler/src/invocation.rs index 4c0f435..d9aa7f0 100644 --- a/compiler/src/invocation.rs +++ b/compiler/src/invocation.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use diagnostic::Error; use std::ffi::OsString; use std::fs; @@ -9,18 +13,68 @@ use crate::plan; /// Compilation ends before this value is returned. No project guard is owned /// here: the caller must drop its resolution/guard before calling execute(). pub struct Execution { + directory: PathBuf, program: String, args: Vec, } impl Execution { + pub fn in_directory(mut self, directory: &Path) -> Self { + self.directory = directory.to_owned(); + self + } pub fn execute(self) -> Result { - process::status(Command::new(&self.program).args(&self.args), None, true) - .map_err(|e| Error::environment(format!("failed to run `{}`: {e}", self.program))) + let program = runner_program(&self.program)?; + process::status( + Command::new(&program) + .args(&self.args) + .current_dir(&self.directory), + None, + true, + ) + .map_err(|e| Error::environment(format!("failed to run `{}`: {e}", self.program))) + } +} + +fn runner_program(program: &str) -> Result { + let path = Path::new(program); + if path.is_absolute() || path.components().count() > 1 { + return Ok(path.to_path_buf()); + } + let root = std::env::current_dir().map_err(Error::environment)?; + for directory in std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()) { + let candidate = root.join(directory).join(path); + #[cfg(windows)] + let candidate = if candidate.extension().is_none() { + candidate.with_extension("exe") + } else { + candidate + }; + if !candidate.is_file() { + continue; + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + if fs::metadata(&candidate) + .map_err(Error::environment)? + .permissions() + .mode() + & 0o111 + == 0 + { + continue; + } + } + return Ok(candidate); } + Err(Error::environment(format!( + "program runner `{program}` is unavailable on PATH" + ))) } /// A validated compiler plan. Constructing it does not create build outputs. pub struct PreparedBuild { + freshness: Option<(String, String, crate::freshness::Inputs)>, plan: serde_json::Value, args: Vec, root: PathBuf, @@ -30,6 +84,20 @@ pub struct PreparedBuild { generation: Option, } impl PreparedBuild { + pub fn with_fingerprint( + mut self, + base: &str, + inputs: &crate::freshness::Inputs, + ) -> (Self, Result<(), String>) { + let key = crate::freshness::key(base, &self.plan, &self.args, self.generation.as_deref()); + let status = key.as_ref().map(|_| ()).map_err(Clone::clone); + self.freshness = key.ok().map(|key| (key, base.to_owned(), inputs.clone())); + (self, status) + } + + pub fn cache_eligibility(&self) -> Result<(), String> { + crate::freshness::key("", &self.plan, &self.args, self.generation.as_deref()).map(|_| ()) + } pub fn plan(&self) -> &serde_json::Value { &self.plan } @@ -47,11 +115,20 @@ impl PreparedBuild { .map_err(Error::environment) } pub fn execute( + self, + compiler: &crate::Compiler, + report: Option<&mut dyn FnMut(serde_json::Value) -> Result<(), Error>>, + ) -> Result, Error> { + self.execute_reported(compiler, report, &mut |_| {}) + } + pub fn execute_reported( self, compiler: &crate::Compiler, mut report: Option<&mut dyn FnMut(serde_json::Value) -> Result<(), Error>>, + decision: &mut dyn FnMut(String), ) -> Result, Error> { let Self { + freshness, plan, args, root, @@ -69,51 +146,102 @@ impl PreparedBuild { .collect(); let ownership = state::artifacts::Batch::prepare_with_optional( &root, - outputs, + outputs.clone(), optional_outputs.iter().cloned(), ) .map_err(Error::environment)?; - let compile_result = (|| -> Result { - let status = if let Some(sink) = report.as_mut() { - insert_build_flag(&mut compile_args, "--error-format=json"); - let output = - process::output_without_deadline(Command::new(wavec).args(&compile_args)) - .map_err(Error::environment)?; - diagnostic::output::stdout(format_args!( - "{}", - String::from_utf8_lossy(&output.stdout) - ))?; - // Compiler diagnostics retain their original structured payload and spans. - // User-program streams never pass through this compiler-only capture. - diagnostic::output::stderr(format_args!( - "{}", - String::from_utf8_lossy(&output.stderr) - ))?; - emit_diagnostics(&output.stderr, &mut **sink)?; - output.status - } else { - process::status(Command::new(wavec).args(&compile_args), None, false).map_err( - |e| { - Error::environment(format!( - "failed to execute `{}` build: {e}", - wavec.display() - )) - }, - )? - }; - Ok(status) - })(); - let compile_result = compile_result.and_then(|status| { - if status.success() { - ownership.verify_outputs().map_err(Error::compiler) - } else { - Err(compiler_error( - status, - format!("wavec build failed [{}]", classify_exit(status)), - )) + let reused = match freshness.as_ref() { + Some((key, base, inputs)) + if inputs.fingerprint().as_deref() == Ok(base.as_str()) + && crate::freshness::key(base, &plan, &args, generation.as_deref()) + .as_deref() + == Ok(key.as_str()) => + { + match crate::freshness::restore(&root, key, &outputs, &optional_outputs) { + Ok(true) => { + decision( + "freshness: fresh; verified cached artifacts copied into owned outputs" + .into(), + ); + true + } + Ok(false) => { + decision("freshness: dirty; cache entry is absent".into()); + false + } + Err(reason) => { + decision(format!("freshness: dirty; {reason}")); + false + } + } } - }); + _ => false, + }; + if let Some(sink) = report.as_mut() { + sink(serde_json::json!({"event":"freshness","reused":reused,"origin":"vex"}))?; + } + let compile_result = if reused { + ownership.verify_outputs().map_err(Error::compiler) + } else { + let result = (|| -> Result { + let status = if let Some(sink) = report.as_mut() { + insert_build_flag(&mut compile_args, "--error-format=json"); + let output = + process::output_without_deadline(Command::new(wavec).args(&compile_args)) + .map_err(Error::environment)?; + diagnostic::output::stdout(format_args!( + "{}", + String::from_utf8_lossy(&output.stdout) + ))?; + // Compiler diagnostics retain their original structured payload and spans. + // User-program streams never pass through this compiler-only capture. + diagnostic::output::stderr(format_args!( + "{}", + String::from_utf8_lossy(&output.stderr) + ))?; + emit_diagnostics(&output.stderr, &mut **sink)?; + output.status + } else { + process::status(Command::new(wavec).args(&compile_args), None, false).map_err( + |e| { + Error::environment(format!( + "failed to execute `{}` build: {e}", + wavec.display() + )) + }, + )? + }; + Ok(status) + })(); + result.and_then(|status| { + if status.success() { + ownership.verify_outputs().map_err(Error::compiler) + } else { + Err(compiler_error( + status, + format!("wavec build failed [{}]", classify_exit(status)), + )) + } + }) + }; finish_compilation(compile_result, ownership.finish())?; + if !reused { + if let Some((key, base, inputs)) = freshness.as_ref() { + if inputs.fingerprint().as_deref() == Ok(base.as_str()) + && crate::freshness::key(base, &plan, &args, generation.as_deref()).as_deref() + == Ok(key.as_str()) + { + match crate::freshness::store(&root, key, &outputs, &optional_outputs) { + Ok(()) => decision( + "freshness: rebuilt; successful output snapshot recorded".into(), + ), + Err(reason) => decision(format!( + "freshness: rebuilt; cache was not recorded: {reason}" + )), + } + } + } + } if let Some(sink) = report.as_mut() { let mut outputs: Vec<_> = if let Some(output) = plan["link"]["output"].as_str() { vec![output.to_owned()] @@ -187,6 +315,7 @@ pub fn prepare_build( String::from_utf8_lossy(&validation_output.stderr) ))?; } + let root = std::env::current_dir().map_err(Error::environment)?; let separator = args.iter().position(|a| a == "--").unwrap_or(args.len()); let is_run = args[..separator].iter().any(|a| a == "--run"); let execution = if is_run { @@ -222,11 +351,36 @@ pub fn prepare_build( "runner plan does not reference the generated artifact", )); } - let mut execution_args: Vec = run_args.into_iter().map(OsString::from).collect(); + let absolute_output = root + .join(output) + .to_str() + .ok_or_else(|| Error::resolution("run output requires a UTF-8 path"))? + .to_owned(); + let executable = if program == output { + absolute_output.clone() + } else if Path::new(&program).components().count() > 1 { + root.join(&program) + .to_str() + .ok_or_else(|| Error::resolution("runner path requires UTF-8"))? + .to_owned() + } else { + program.clone() + }; + let mut execution_args: Vec = run_args + .into_iter() + .map(|arg| { + OsString::from(if arg == output { + absolute_output.clone() + } else { + arg + }) + }) + .collect(); execution_args.extend_from_slice(runtime); Some(( Execution { - program, + directory: root.clone(), + program: executable, args: execution_args, }, PathBuf::from(output), @@ -252,6 +406,7 @@ pub fn prepare_build( args.extend(values.into_iter().map(serde_json::Value::String)); } Ok(PreparedBuild { + freshness: None, plan, args: args[..separator].to_vec(), root, diff --git a/compiler/src/lib.rs b/compiler/src/lib.rs index 9b36195..085a021 100644 --- a/compiler/src/lib.rs +++ b/compiler/src/lib.rs @@ -1,3 +1,8 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +pub mod freshness; mod invocation; mod plan; mod selection; diff --git a/compiler/src/plan.rs b/compiler/src/plan.rs index 4eb5307..0738730 100644 --- a/compiler/src/plan.rs +++ b/compiler/src/plan.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use serde_json::Value; pub(crate) fn validate_dry_run_json_output(stdout: &[u8], _stderr: &[u8]) -> Result { diff --git a/compiler/src/selection.rs b/compiler/src/selection.rs index cacfb38..ff2d710 100644 --- a/compiler/src/selection.rs +++ b/compiler/src/selection.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use diagnostic::Error; use std::collections::BTreeMap; use std::path::{Path, PathBuf}; diff --git a/diagnostic/Cargo.toml b/diagnostic/Cargo.toml index 8344cf0..ce3c383 100644 --- a/diagnostic/Cargo.toml +++ b/diagnostic/Cargo.toml @@ -1,3 +1,7 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 [package] name = "diagnostic" version.workspace = true diff --git a/diagnostic/src/lib.rs b/diagnostic/src/lib.rs index d29279c..3a9457d 100644 --- a/diagnostic/src/lib.rs +++ b/diagnostic/src/lib.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 //! Stable Vex error categories. Messages are explanatory, never classifiers. use std::fmt; pub mod output; diff --git a/diagnostic/src/output.rs b/diagnostic/src/output.rs index 3de9cf5..1a456d3 100644 --- a/diagnostic/src/output.rs +++ b/diagnostic/src/output.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 //! Vex-owned output only; compiler and user-program stdio remain inherited. use std::fmt; use std::io::{self, Write}; diff --git a/docs/commands.md b/docs/commands.md index e1acd11..8fc695b 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -10,20 +10,27 @@ See [manifest and operational contracts](reference.md) for field types, environm Vex - Wave package manager Usage: - vex [-q|--quiet] [-v|--verbose] [--message-file ] [--manifest-path ] [options] + vex [-q|--quiet] [-v|--verbose] [--message-file ] [--manifest-path ] [-p|--package |--workspace] [--features ] [--no-default-features] [--include-tests] [options] vex init [--lib] vex build [--lib] [--bin ] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline] vex run [--bin ] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline] [-- ] vex check [--lib] [--bin ] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline] - vex fetch [--locked] [--offline] - vex update [...] + vex test [filter] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline] [-- ] + vex fetch [--locked] [--offline] [--target ] + vex update [...] [--target ] vex info - vex metadata [--format=json] [--format-version <1|2>] [--locked] [--offline] - vex tree [--invert ] [--depth ] [--locked] [--offline] + vex metadata [--format=json] [--format-version <1|2>] [--locked] [--offline] [--target ] + vex tree [--invert ] [--depth ] [--locked] [--offline] [--target ] vex clean [--dry-run] vex prune [--apply] [--dry-run] vex doctor [--format=json] [--target ] vex setup wavec [--version ] [--script-fallback] + vex new [--name ] [--lib] [--git] + vex add (--git |--path ) [--branch |--tag |--rev ] [--version ] [--version-req ] [--package-name ] [--subdir ] [--offline] + vex remove [--offline] + vex cache prune [--apply] [--dry-run] + vex completions + vex manpage vex --version Output: @@ -35,81 +42,158 @@ Output: ```text usage: vex init [--lib] + +Manage init ``` ## build ```text -usage: vex build [--lib] [--bin ] [--target ] [--profile | --release] [--dry-run] [--locked] [--offline] +usage: vex build [--lib] [--bin ] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline] + +Compile selected package targets +``` + +## run + +```text +usage: vex run [--bin ] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline] [-- ] + +Compile and execute one binary ``` ## check ```text -usage: vex check [--lib] [--bin ] [--target ] [--profile | --release] [--dry-run] [--locked] [--offline] +usage: vex check [--lib] [--bin ] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline] + +Check selected package targets ``` -## run +## test ```text -usage: vex run [--bin ] [--target ] [--profile | --release] [--dry-run] [--locked] [--offline] [-- ] +usage: vex test [filter] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline] [-- ] + +Compile and execute explicit main-based tests; run every selected test and return the first failure ``` ## fetch ```text -usage: vex fetch [--locked] [--offline] +usage: vex fetch [--locked] [--offline] [--target ] + +Manage fetch ``` ## update ```text -usage: vex update [...] +usage: vex update [...] [--target ] + +Manage update ``` ## info ```text usage: vex info -``` - -## tree -```text -usage: vex tree [--invert ] [--depth ] [--locked] [--offline] - --invert Show the packages that depend on this package - --depth Show at most n edges from the displayed root (0: root only) +Manage info ``` ## metadata ```text -usage: vex metadata [--format=json] [--format-version <1|2>] [--locked] [--offline] +usage: vex metadata [--format=json] [--format-version <1|2>] [--locked] [--offline] [--target ] + +Manage metadata ``` -## doctor +## tree ```text -usage: vex doctor [--format=json] [--target ] +usage: vex tree [--invert ] [--depth ] [--locked] [--offline] [--target ] + +Manage tree ``` ## clean ```text usage: vex clean [--dry-run] + +Manage clean ``` ## prune ```text usage: vex prune [--apply] [--dry-run] - Preview unused, unchanged checkouts created by Vex - --apply Delete only the verified unused checkouts - --dry-run Preview without changing project state (also overrides --apply) + +Manage prune +``` + +## doctor + +```text +usage: vex doctor [--format=json] [--target ] + +Manage doctor ``` ## setup ```text usage: vex setup wavec [--version ] [--script-fallback] + +Manage setup +``` + +## new + +```text +usage: vex new [--name ] [--lib] [--git] + +Create a new project without overwriting data +``` + +## add + +```text +usage: vex add (--git |--path ) [--branch |--tag |--rev ] [--version ] [--version-req ] [--package-name ] [--subdir ] [--offline] + +Add a direct dependency preserving comments and formatting +``` + +## remove + +```text +usage: vex remove [--offline] + +Remove a direct dependency preserving comments and formatting +``` + +## cache + +```text +usage: vex cache prune [--apply] [--dry-run] + +Explicitly prune shared Git objects +``` + +## completions + +```text +usage: vex completions + +Print shell completion script +``` + +## manpage + +```text +usage: vex manpage + +Print the vex(1) manual ``` diff --git a/docs/completions/vex.bash b/docs/completions/vex.bash new file mode 100644 index 0000000..0de21ef --- /dev/null +++ b/docs/completions/vex.bash @@ -0,0 +1,3 @@ +# Generated from command-spec.json +_vex() { COMPREPLY=( $(compgen -W '-- --apply --bin --branch --depth --dry-run --features --format-version --format=json --git --include-tests --invert --lib --locked --manifest-path --message-file --name --no-default-features --offline --package --package-name --path --profile --quiet --release --rev --script-fallback --subdir --tag --target --verbose --version --version-req --workspace -p -q -v add build cache check clean completions doctor fetch info init manpage metadata new prune remove run setup test tree update' -- "${COMP_WORDS[COMP_CWORD]}") ); } +complete -F _vex vex diff --git a/docs/completions/vex.fish b/docs/completions/vex.fish new file mode 100644 index 0000000..b076661 --- /dev/null +++ b/docs/completions/vex.fish @@ -0,0 +1,54 @@ +# Generated from command-spec.json +complete -c vex -l apply +complete -c vex -l bin +complete -c vex -l branch +complete -c vex -l depth +complete -c vex -l dry-run +complete -c vex -l features +complete -c vex -l format-version +complete -c vex -l format=json +complete -c vex -l git +complete -c vex -l include-tests +complete -c vex -l invert +complete -c vex -l lib +complete -c vex -l locked +complete -c vex -l manifest-path +complete -c vex -l message-file +complete -c vex -l name +complete -c vex -l no-default-features +complete -c vex -l offline +complete -c vex -l package +complete -c vex -l package-name +complete -c vex -l path +complete -c vex -l profile +complete -c vex -l quiet +complete -c vex -l release +complete -c vex -l rev +complete -c vex -l script-fallback +complete -c vex -l subdir +complete -c vex -l tag +complete -c vex -l target +complete -c vex -l verbose +complete -c vex -l version +complete -c vex -l version-req +complete -c vex -l workspace +complete -c vex -f -a add +complete -c vex -f -a build +complete -c vex -f -a cache +complete -c vex -f -a check +complete -c vex -f -a clean +complete -c vex -f -a completions +complete -c vex -f -a doctor +complete -c vex -f -a fetch +complete -c vex -f -a info +complete -c vex -f -a init +complete -c vex -f -a manpage +complete -c vex -f -a metadata +complete -c vex -f -a new +complete -c vex -f -a prune +complete -c vex -f -a remove +complete -c vex -f -a run +complete -c vex -f -a setup +complete -c vex -f -a test +complete -c vex -f -a tree +complete -c vex -f -a update diff --git a/docs/completions/vex.powershell b/docs/completions/vex.powershell new file mode 100644 index 0000000..a23b16f --- /dev/null +++ b/docs/completions/vex.powershell @@ -0,0 +1,4 @@ +# Generated from command-spec.json +Register-ArgumentCompleter -Native -CommandName vex -ScriptBlock { param($wordToComplete, $commandAst, $cursorPosition) + '-- --apply --bin --branch --depth --dry-run --features --format-version --format=json --git --include-tests --invert --lib --locked --manifest-path --message-file --name --no-default-features --offline --package --package-name --path --profile --quiet --release --rev --script-fallback --subdir --tag --target --verbose --version --version-req --workspace -p -q -v add build cache check clean completions doctor fetch info init manpage metadata new prune remove run setup test tree update'.Split(' ') | Where-Object { $_.StartsWith($wordToComplete) } | ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) } +} diff --git a/docs/completions/vex.zsh b/docs/completions/vex.zsh new file mode 100644 index 0000000..cea8d82 --- /dev/null +++ b/docs/completions/vex.zsh @@ -0,0 +1,3 @@ +#compdef vex +# Generated from command-spec.json +_arguments '*:command or option:(-- --apply --bin --branch --depth --dry-run --features --format-version --format=json --git --include-tests --invert --lib --locked --manifest-path --message-file --name --no-default-features --offline --package --package-name --path --profile --quiet --release --rev --script-fallback --subdir --tag --target --verbose --version --version-req --workspace -p -q -v add build cache check clean completions doctor fetch info init manpage metadata new prune remove run setup test tree update)' diff --git a/docs/dependency-features.md b/docs/dependency-features.md new file mode 100644 index 0000000..18f4f66 --- /dev/null +++ b/docs/dependency-features.md @@ -0,0 +1,31 @@ +# Conditional dependencies and additive features + +Format 4 adds dependency activation without raw compiler flags or scripts: + +```wson +{ + format = 4, + name = "app", + targets = { bins = [{ name = "app", path = "src/main.wave" }] }, + dependencies = [ + { name = "platform", package = "platform", path = "../unix_impl", target = { os = "linux" } }, + { name = "platform", package = "platform", path = "../windows_impl", target = { os = "windows" } }, + { name = "extras", path = "../extras", optional = true, default_features = false } + ], + features = { default = ["extended"], extended = ["dep:extras", "extras/fast"] } +} +``` + +A `target` object combines its supplied constraints with AND: exact `triple`, `os`, `arch`, and `mode`. OS values are `linux`, `macos`, `windows`, `freebsd`, `wasi`, `none`, `unknown`; architecture values are `x86_64`, `aarch64`, `riscv64`, `loongarch64`, `wasm32`, `wasm64`. Modes are `hosted`, `freestanding`, `wasi`, `bare_wasm`. Empty predicates, unknown fields/values, and OS/architecture constraints contradicting an exact triple are errors. One alias can have several distinct target predicates. Simultaneously active mappings to different concrete packages fail explicitly under Wave's global import map. + +Features are additive. Names use `[A-Za-z_][A-Za-z0-9_-]*`. A group can contain another local group, `dep:alias`, or `alias/feature`; an optional dependency also has an implicit feature with its alias unless a declared group has that name. `alias/feature` enables the dependency and requests that child's feature. Local group cycles are finite unions; package dependency cycles remain errors. Unknown feature references fail rather than being ignored. + +`default` is an ordinary group enabled initially. `--no-default-features` disables only the selected root's defaults. `--features group,other` adds root requests. Each dependency enables its own defaults unless that edge sets `default_features = false`. An edge's `features` list requests child feature groups. All active incoming requests for the same concrete package ID are united, including requests through different aliases. Defaults requested by any incoming edge remain enabled. + +The version 4 lock stores the union of all declared target and optional sources, exact commits, root declarations, activation edges and feature groups. Fetch prepares the complete union, including currently inactive packages. It does not scan a registry. After preparation, target/feature selection changes need neither network nor a lockfile rewrite. Missing union sources still require `vex fetch`; locked/offline modes never invent source choices. `prune` preserves every union source, including inactive packages. + +Build/check/run accept feature selection and use their selected compiler triple plus each binary's manifest-owned mode. Fetch/update/tree/metadata accept `--target ` without querying the compiler; their default is `build.target` or the Vex host triple with its usual mode. A target query describes graph activation and does not certify that a selected compiler supports that target. + +Tree shows the active graph. Metadata schema 2 adds the effective `selection`, `selected_features`, and `union_bindings`; each selected package has a `binding` key used by dependency edges, its import `alias`, and concrete package `id`. Inverse queries accept an alias or binding key and report ambiguity when several bindings match. Metadata remains read-only and requires the local union graph to be prepared. + +These features select dependency graphs. They do not add Wave language conditional-compilation syntax or synthesize compiler flags. Source imports must be valid for the chosen graph. diff --git a/docs/git-cache.md b/docs/git-cache.md new file mode 100644 index 0000000..1b54fff --- /dev/null +++ b/docs/git-cache.md @@ -0,0 +1,11 @@ +# Git objects and repository packages + +Format 4 accepts `subdir = "packages/math"` on a Git dependency. The selector is a portable repository-relative path: no absolute paths, backslashes, empty components, `.` or `..`. Its canonical destination must remain inside the selected checkout. Transitive paths are relative to that package's manifest. The lock records the repository commit and package subdirectory separately; compiler imports and metadata use the package directory. Older manifest formats remain unchanged. A new feature requires a version 4 lockfile; `--locked` never migrates an existing file. + +Vex retains verified Git objects in a user cache and keeps complete, independent project checkouts. Linux and FreeBSD use `$XDG_CACHE_HOME/vex` (or `~/.cache/vex`), macOS uses `~/Library/Caches/vex`, and Windows uses `%LOCALAPPDATA%/vex`. Set an absolute `VEX_CACHE_HOME` to override the root. Repository declarations, including their authentication context, are hashed into opaque directory names. Credentials are never stored in cache configuration or diagnostics. Different authentication declarations do not share a cache entry. + +A locked object missing from a checkout can be restored from this cache, including with `--offline`. The lockfile is authoritative: Vex never substitutes a branch tip for an unavailable commit. Unlocked branch selection and explicit updates still contact the source. Repeated packages from the same repository selection share a command-local commit snapshot. Local imports disallow network protocols even if Git URL rewrites are configured. No project checkout uses hardlinks or object alternates into the cache. + +The project lease is acquired before a repository cache lease. Persistent OS coordination locks are never deleted as stale PID files. Cache candidates are copied, verified with Git, synced and atomically published. Corrupt entries are quarantined; an online command can repopulate them, while an offline command fails if no exact object remains. Quarantines are preserved for inspection. Dry-run and metadata do not restore checkouts or repair caches. + +`vex cache prune` previews removal of recognized bare repositories; `vex cache prune --apply` removes them under their cache leases. It preserves coordination files, quarantines and unknown entries. Project checkouts remain usable afterward, but recreating one can require network access. There is no automatic cache GC. To investigate a quarantined entry, preserve it separately before manual removal; do not remove cache coordination files while Vex processes are running. diff --git a/docs/metadata.md b/docs/metadata.md index c8443a7..eea3bc8 100644 --- a/docs/metadata.md +++ b/docs/metadata.md @@ -87,3 +87,5 @@ Absolute paths intentionally differ when the project is moved. Object-key order is not an API guarantee. Consumers should ignore additive fields in their chosen schema; changes to existing field meanings or types require a new schema version. Unsupported future manifest formats fail without migration. + +Format 4 graphs require schema 2. See [dependency features](dependency-features.md) for binding keys, concrete IDs, union records and active selection. diff --git a/docs/package-identity.md b/docs/package-identity.md new file mode 100644 index 0000000..e3e26e6 --- /dev/null +++ b/docs/package-identity.md @@ -0,0 +1,26 @@ +# Package versions and import identities + +Manifest format 4 uses canonical SemVer package versions (`1.2.3`, `0.2.0-beta.1`). Compiler releases are a separate exact identity: `compiler = "0.2.1-pre-beta"` remains an equality check, not a SemVer compatibility promise. Existing manifest formats retain their original version strings and exact dependency comparisons. No manifest is automatically converted. + +A dependency's `version` remains exact string equality. Format 4 adds `version_req`, mutually exclusive with `version`, using SemVer requirements: `^1.2.3`, `~1.2`, `=1.2.3`, `>=1.2, <2`, `1.*`. An unprefixed requirement has caret semantics. Prereleases must be explicitly admitted for the same release tuple; `*` does not include prereleases. Build metadata does not affect requirement matching. Vex release versions still prohibit build metadata under the separate release policy. + +Requirements validate the concrete package in the selected Git/path source. They do not search tags, solve registry versions, or change the exact commit selected by a lockfile. Compatible requirements on a shared source can coexist. An incompatible request fails with its dependency path and leaves prior published state intact. + +```wson +{ + format = 4, + name = "application", + version = "1.0.0", + targets = { bins = [{ name = "application", path = "src/main.wave" }] }, + dependencies = [ + { name = "old_math", package = "math", path = "../math_v1", version_req = "^1.2" }, + { name = "new_math", package = "math", path = "../math_v2", version_req = "^2" } + ] +} +``` + +`name` is the Wave import alias; `package` is the source manifest's declared name and defaults to `name`. Vex validates that declaration rather than renaming source files. Version 4 lock records distinguish import bindings from concrete package IDs. A package ID hashes the declared name, exact version, concrete source (Git URL/commit or project-relative path), and subdirectory. Selectors and aliases do not change concrete identity. Tree output shows `alias => package`; metadata schema 2 (`--format-version 2`) adds `alias` and `id` while retaining the declared `name`. + +Current Wave accepts one global `--dep==` map. Distinct aliases can import two versions; conflicting transitive uses of one alias for different sources cannot be represented and fail explicitly. Full scoped dependency mapping remains an outstanding compiler contract under #58. Vex never rewrites user source to emulate it. + +Version 1/2/3 lockfiles remain readable. Commands using old manifest models preserve their existing `--locked` files. Format 4 requires version 4 lock state; `--locked` reports a required migration and preserves the old bytes. Run `vex fetch` explicitly before committing a migrated lockfile. IDs in a lockfile are checked against their concrete source before graph use. diff --git a/docs/reference.md b/docs/reference.md index d693c11..aa070a5 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -114,7 +114,7 @@ published checkouts with an intact ownership record are eligible. Dirty, untracked, ignored, modified Git metadata, legacy/unrecorded checkouts, and unknown files are preserved. Both cleanup commands refuse pending recovery; use a normal `fetch` to recover first. Transaction backups and compiler -installations are outside cleanup scope. No shared dependency cache exists, so +installations are outside cleanup scope. A verified shared Git cache may restore exact commits; otherwise reusing a pruned dependency may require network access through `fetch`. ## Environment @@ -131,7 +131,7 @@ reusing a pruned dependency may require network access through `fetch`. Git keeps authentication, SSH, proxy and ordinary configuration while removing repository-selection environment overrides. Transport is noninteractive; timeout and cancellation terminate supervised child trees. Release infrastructure options -such as `VEX_RELEASE_HOST` belong to `x.py`, not normal Vex commands. +such as `VEX_RELEASE_HOST` belong to the Meson release tools, not normal Vex commands. ## Streams and outcomes @@ -194,3 +194,28 @@ entries with `package_target: {name, kind}` and the validated `compiler_plan`. It replaces the previous direct compiler-plan output. Planning runs once per selected target; capability queries are cached within the invocation. See the [full build contract](targets-and-profiles.md). + +## Verified build reuse + +Freshness records live in owned `target/.vex-cache//` directories. +Inputs include package and transitive `.wave` sources and manifests, the exact +union lock, selected features, target capabilities/schema and profile arguments, +native prebuilt inputs, compiler executable/runtime libraries, standard-library +contents and relevant toolchain environment. File timestamps are not freshness. +Input contents are checked again before reuse and before recording successful +compilation. Failed compilation and program/test results are never recorded. + +The initial implementation establishes compiler runtime closure on Linux ELF +hosts with `ldd`; other hosts, unavailable queries, symlinks, unknown native +source dependencies, SDK/custom linker settings and implicit hosted system links +compile normally without reuse. Check/object plans can be reused when complete +inputs are known. Wasm links additionally require an absolute linker with known +runtime and declared inputs. Correctness takes precedence over the hit rate. + +Every command still validates its compiler plan and destination ownership. Hits +verify cached bytes and copy them into owned outputs, including a new inode for +each run generation. Missing, partial or corrupt entries are misses; unknown or +modified cache data is not silently overwritten. `clean` handles unmodified +owned cache files and preserves modified files. There is no automatic GC. +Verbose output explains eligibility, fresh copies, dirty/missing entries and +rebuilds; JSONL exposes a `freshness` event with `reused`. diff --git a/docs/release-readiness.md b/docs/release-readiness.md index 37ea0c1..50828fb 100644 --- a/docs/release-readiness.md +++ b/docs/release-readiness.md @@ -116,11 +116,11 @@ it is diagnostic output, not a stable Vex metadata interface. ## Release and merge policy Rust 1.96.0 is the initial supported toolchain/MSRV, including rustfmt and Clippy. -The checked-in toolchain, Cargo declarations and CI/release setup agree. x.py +The checked-in toolchain, Cargo declarations and CI/release setup agree. Meson automation selects that toolchain even when the caller's rustup default differs. Release versions permit normal versions and prereleases, without `+build.metadata`. -The workflow and x.py call the same validation policy. No official release is +The workflow and Meson artifact tools call the same validation policy. No official release is created by local build/package verification. Archives include the license texts and notices from the complete locked Cargo @@ -204,3 +204,29 @@ verified compiler installation, and this real Wave smoke. RISC-V and LoongArch execute target userspace through QEMU; FreeBSD uses a VM. Cross compilation alone cannot produce acceptance. The public artifact checks and eventual release run must pass before release; local candidate results do not satisfy those gates. + +The QEMU lanes compile Rust tests (including doctests), Vex release binaries and +all compiler fixtures on Linux amd64 with Rust 1.96.0 and the digest-pinned Debian +cross SDK in `tools/ci_cross.Dockerfile`. Cargo's target runner executes tests in +the pinned target container, where Git, Wave and user programs also execute. +C/C++/Rust interoperability inputs and consumers are cross-compiled on amd64; +their Wave interactions and resulting executables run in that same QEMU guest. +Fixture source/binary hashes and ELF architectures are checked before execution. +Reports distinguish the build host, target runtime and SDK package versions. +Cross test builds use optimization level 1 with debug assertions and integer +overflow checks explicitly enabled; the complete suite still executes. Native +platform lanes retain their normal unoptimized test profile. +On an amd64 Linux host with Docker, registered target binfmt handlers and the +matching Rust target installed, reproduce either lane with +Meson after installing `tools/requirements-build.txt` and Ninja: + +```sh +meson setup build/riscv64 -Drelease_targets=riscv64gc-unknown-linux-gnu -Dacceptance_platform=linux-riscv64 +meson compile -C build/riscv64 acceptance +meson setup build/loongarch64 -Drelease_targets=loongarch64-unknown-linux-gnu -Dacceptance_platform=linux-loongarch64 +meson compile -C build/loongarch64 acceptance +``` + +Meson owns automation sequencing; Cargo still owns compilation. Target guests +run the same pinned Meson version and Python tooling suite. Cross host and guest +configurations use separate build directories; the guest needs no Rust compiler. diff --git a/docs/schemas/build-plan-v1.json b/docs/schemas/build-plan-v1.json index 007c83c..660050f 100644 --- a/docs/schemas/build-plan-v1.json +++ b/docs/schemas/build-plan-v1.json @@ -2,17 +2,38 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "Vex build-plan v1", "type": "object", - "required": ["schema", "schema_version", "target", "profile", "plans"], + "required": [ + "schema", + "schema_version", + "target", + "profile", + "plans" + ], "properties": { - "schema": {"const": "vex.build-plan"}, - "schema_version": {"const": 1}, - "target": {"type": "string"}, + "schema": { + "const": "vex.build-plan" + }, + "schema_version": { + "const": 1 + }, + "target": { + "type": "string" + }, "profile": { "type": "object", - "required": ["name", "opt_level"], + "required": [ + "name", + "opt_level" + ], "properties": { - "name": {"type": "string"}, - "opt_level": {"type": "integer", "minimum": 0, "maximum": 3} + "name": { + "type": "string" + }, + "opt_level": { + "type": "integer", + "minimum": 0, + "maximum": 3 + } } }, "plans": { @@ -20,17 +41,47 @@ "minItems": 1, "items": { "type": "object", - "required": ["package_target", "compiler_plan"], + "required": [ + "package_target", + "compiler_plan" + ], "properties": { "package_target": { "type": "object", - "required": ["name", "kind"], + "required": [ + "name", + "kind" + ], "properties": { - "name": {"type": "string"}, - "kind": {"enum": ["library", "binary"]} + "name": { + "type": "string" + }, + "kind": { + "enum": [ + "library", + "binary" + ] + } } }, - "compiler_plan": {"type": "object"} + "compiler_plan": { + "type": "object" + }, + "package": { + "type": "string" + }, + "manifest_path": { + "type": "string" + }, + "build_directory": { + "type": "string" + }, + "run_directory": { + "type": [ + "string", + "null" + ] + } } } } diff --git a/docs/schemas/messages-v1.json b/docs/schemas/messages-v1.json index 8bf9bd2..403a80b 100644 --- a/docs/schemas/messages-v1.json +++ b/docs/schemas/messages-v1.json @@ -214,6 +214,61 @@ ] } } + }, + { + "required": [ + "event", + "package", + "test", + "origin", + "exit_code", + "signal", + "success" + ], + "properties": { + "event": { + "const": "test_result" + }, + "package": { + "type": "string" + }, + "test": { + "type": "string" + }, + "origin": { + "const": "program" + }, + "exit_code": { + "type": "integer" + }, + "signal": { + "type": [ + "integer", + "null" + ] + }, + "success": { + "type": "boolean" + } + } + }, + { + "required": [ + "event", + "origin", + "reused" + ], + "properties": { + "event": { + "const": "freshness" + }, + "origin": { + "const": "vex" + }, + "reused": { + "type": "boolean" + } + } } ] } diff --git a/docs/schemas/metadata-v1.json b/docs/schemas/metadata-v1.json index 4a0759a..aab205b 100644 --- a/docs/schemas/metadata-v1.json +++ b/docs/schemas/metadata-v1.json @@ -72,7 +72,8 @@ "enum": [ 1, 2, - 3 + 3, + 4 ] }, "compiler": { diff --git a/docs/schemas/metadata-v2.json b/docs/schemas/metadata-v2.json index f1f64db..efbdcea 100644 --- a/docs/schemas/metadata-v2.json +++ b/docs/schemas/metadata-v2.json @@ -13,7 +13,14 @@ "const": 2 }, "root": { - "$ref": "#/$defs/package" + "oneOf": [ + { + "$ref": "#/$defs/package" + }, + { + "$ref": "#/$defs/workspace" + } + ] }, "packages": { "type": "array", @@ -23,6 +30,33 @@ }, "target_directory": { "type": "string" + }, + "selection": { + "type": [ + "object", + "null" + ] + }, + "selected_features": { + "type": "object" + }, + "union_bindings": { + "type": "array", + "items": { + "type": "object" + } + }, + "selections": { + "type": "array", + "items": { + "type": "object" + } + }, + "workspace_members": { + "type": "array", + "items": { + "$ref": "#/$defs/package" + } } }, "$defs": { @@ -66,7 +100,8 @@ "enum": [ 1, 2, - 3 + 3, + 4 ] }, "compiler": { @@ -126,7 +161,6 @@ }, "targets": { "type": "array", - "minItems": 1, "items": { "$ref": "#/$defs/target" } @@ -217,6 +251,36 @@ } } } + }, + "id": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "alias": { + "type": "string" + }, + "binding": { + "type": "string" + }, + "features": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "tests": { + "type": "array", + "items": { + "type": "object", + "required": [ + "name", + "entry_path", + "platform" + ] + } } } }, @@ -300,6 +364,45 @@ "$ref": "#/$defs/platform" } } + }, + "workspace": { + "type": "object", + "required": [ + "kind", + "root", + "manifest_path", + "members", + "default_members" + ], + "properties": { + "kind": { + "const": "workspace" + }, + "root": { + "type": "string" + }, + "manifest_path": { + "type": "string" + }, + "package": { + "type": [ + "string", + "null" + ] + }, + "members": { + "type": "array", + "items": { + "type": "string" + } + }, + "default_members": { + "type": "array", + "items": { + "type": "string" + } + } + } } } } diff --git a/docs/vex.1 b/docs/vex.1 new file mode 100644 index 0000000..cd6ae0e --- /dev/null +++ b/docs/vex.1 @@ -0,0 +1,73 @@ +.TH VEX 1 +.SH NAME +vex \- Wave package manager +.SH SYNOPSIS +.B vex +[-q|--quiet] [-v|--verbose] [--message-file ] [--manifest-path ] [-p|--package |--workspace] [--features ] [--no-default-features] [--include-tests] [options] +.SH COMMANDS +.TP +.B vex init [\-\-lib] +Manage init +.TP +.B vex build [\-\-lib] [\-\-bin ] [\-\-target ] [\-\-profile |\-\-release] [\-\-dry\-run] [\-\-locked] [\-\-offline] +Compile selected package targets +.TP +.B vex run [\-\-bin ] [\-\-target ] [\-\-profile |\-\-release] [\-\-dry\-run] [\-\-locked] [\-\-offline] [\-\- ] +Compile and execute one binary +.TP +.B vex check [\-\-lib] [\-\-bin ] [\-\-target ] [\-\-profile |\-\-release] [\-\-dry\-run] [\-\-locked] [\-\-offline] +Check selected package targets +.TP +.B vex test [filter] [\-\-target ] [\-\-profile |\-\-release] [\-\-dry\-run] [\-\-locked] [\-\-offline] [\-\- ] +Compile and execute explicit main-based tests; run every selected test and return the first failure +.TP +.B vex fetch [\-\-locked] [\-\-offline] [\-\-target ] +Manage fetch +.TP +.B vex update [...] [\-\-target ] +Manage update +.TP +.B vex info +Manage info +.TP +.B vex metadata [\-\-format=json] [\-\-format\-version <1|2>] [\-\-locked] [\-\-offline] [\-\-target ] +Manage metadata +.TP +.B vex tree [\-\-invert ] [\-\-depth ] [\-\-locked] [\-\-offline] [\-\-target ] +Manage tree +.TP +.B vex clean [\-\-dry\-run] +Manage clean +.TP +.B vex prune [\-\-apply] [\-\-dry\-run] +Manage prune +.TP +.B vex doctor [\-\-format=json] [\-\-target ] +Manage doctor +.TP +.B vex setup wavec [\-\-version ] [\-\-script\-fallback] +Manage setup +.TP +.B vex new [\-\-name ] [\-\-lib] [\-\-git] +Create a new project without overwriting data +.TP +.B vex add (\-\-git |\-\-path ) [\-\-branch |\-\-tag |\-\-rev ] [\-\-version ] [\-\-version\-req ] [\-\-package\-name ] [\-\-subdir ] [\-\-offline] +Add a direct dependency preserving comments and formatting +.TP +.B vex remove [\-\-offline] +Remove a direct dependency preserving comments and formatting +.TP +.B vex cache prune [\-\-apply] [\-\-dry\-run] +Explicitly prune shared Git objects +.TP +.B vex completions +Print shell completion script +.TP +.B vex manpage +Print the vex(1) manual +.SH FILES +vex.ws, vex.lock +.SH ENVIRONMENT +VEX_WAVEC, VEX_CACHE_HOME +.SH EXIT STATUS +0 success; 1 internal error; 2 usage; 3 resolution; 4 compiler; 5 environment; 124 timeout; 130 cancellation. Program exit codes are preserved. diff --git a/docs/workspaces.md b/docs/workspaces.md new file mode 100644 index 0000000..9741a77 --- /dev/null +++ b/docs/workspaces.md @@ -0,0 +1,34 @@ +# User workspaces + +A workspace is a group of Wave packages with one dependency lock, coordination lease and output directory. This is separate from Vex's implementation as a Rust workspace. + +```wson +{ + format = 4, + compiler = "0.2.1-pre-beta", + workspace = { + members = ["library", "application"], + exclude = ["examples/independent"], + default_members = ["application"] + }, + profiles = { fast = { inherits = "release", opt_level = 3 } } +} +``` + +Omitting `name` creates a virtual workspace root. To include a package at the root, declare its normal name/version/targets alongside `workspace`; that package is included automatically. Member/default/exclude entries are explicit portable directory paths relative to the root; `.` denotes the root package. Globs, traversal, escaped paths, duplicate physical directories and case-conflicting package names are rejected. Members can use older manifest formats without rewriting them. + +Without `default_members`, root commands select all members. Inside a member, nearest real-path discovery selects that member. An explicit `--manifest-path` has priority and still respects workspace ownership. Use repeated `-p ` / `--package ` to select packages, or `--workspace` to select all. These two selection forms cannot be combined. A nested independent workspace must be excluded by its ancestor; a package inside a workspace must be listed or explicitly excluded. Ambiguous ownership is an error. + +Build/check process selected targets across the selected members. `--lib` and `--bin` filter matching targets across them. Run must resolve to one binary; use `-p` and `--bin` to remove ambiguity. Vex validates every source/profile, dependency/compiler requirement and compiler plan before executing the first compiler. Compilation is deterministic and stops at the first failure, retaining already successful outputs. + +Root profiles, default build target and sysroot/linker settings govern member builds. Members cannot silently override these global settings. A member may keep its own target-specific binary mode/entry/startup/script overrides. An exact compiler requirement at the workspace root applies to every member and conflicting member requirements fail. Foreign inputs remain package-owned; dependency tool settings never propagate into a root build. + +All workspace artifacts live under `target///packages//bin/` or `lib/`. This separates equal target names in different packages. Single-package projects retain their existing layout. Run uses a fresh generation under the workspace's `target/.vex-run/`, releases the workspace build lease before program spawn and executes in the selected member's directory. No automatic generation GC is added. + +The root owns `vex.lock` v4 and `.vex/`. Fetch prepares the union of every member's declared dependency graph, including currently inactive target/feature sources. Existing member lockfiles and state are neither imported, moved nor deleted; commit a freshly reviewed root lock when adopting a workspace. Locked/offline selection requires that union to be prepared. Prune protects all union sources and clean operates on workspace-owned outputs; both commands are workspace-wide rather than accepting package filters. + +Updates made with package selection refresh only bindings reachable from those selected members. A shared binding changes for every consumer of that binding. Unrelated locked bindings, even in the same Git repository, retain their commits. Targeted aliases are checked from the current local union before transport; an incomplete local graph requires fetch. + +Feature requests for the same concrete package ID are additive across selected members and their active contexts, including a member also consumed as a dependency. With multiple selected members, name requested features as `package/feature`; ambiguous unqualified names fail. Compiler import maps remain per root, so independent member builds can use one import alias for different sources. Conflicting transitive aliases within one compiler invocation still require the future scoped Wave mapping contract. + +`vex metadata --format-version 2` describes the workspace root, all member declarations, selected members, per-root `selections`, union bindings and exact sources. `selection` is null when more than one root/context is represented; the `selections` array is authoritative. Tree prints selected root views separately. Doctor diagnoses selected members. Metadata performs no compiler query or network access and does not create or repair state. diff --git a/examples/parser_fuzz.rs b/examples/parser_fuzz.rs index cc43f0c..5b17402 100644 --- a/examples/parser_fuzz.rs +++ b/examples/parser_fuzz.rs @@ -1,3 +1,6 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. // SPDX-License-Identifier: MPL-2.0 //! Bounded mutation fuzzer. A failing seed and minimized input are reproducible. use std::{fs, panic, path::PathBuf}; diff --git a/lockfile/Cargo.toml b/lockfile/Cargo.toml index ba3666e..98f4cd4 100644 --- a/lockfile/Cargo.toml +++ b/lockfile/Cargo.toml @@ -1,3 +1,7 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 [package] name = "lockfile" version.workspace = true @@ -11,3 +15,6 @@ publish = false diagnostic.workspace = true source.workspace = true wson.workspace = true +sha2 = "0.11.1" +serde_json.workspace = true +serde = { version = "1", features = ["derive"] } diff --git a/lockfile/src/lib.rs b/lockfile/src/lib.rs index 71269d8..84f5522 100644 --- a/lockfile/src/lib.rs +++ b/lockfile/src/lib.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use std::path::PathBuf; mod parse; @@ -9,7 +13,7 @@ pub use render::render_lockfile as encode; pub use store::{read_lockfile, write_lockfile}; pub const LOCKFILE_NAME: &str = "vex.lock"; -pub const LOCKFILE_VERSION: i64 = 3; +pub const LOCKFILE_VERSION: i64 = 4; #[derive(Debug, Clone, Eq, PartialEq)] pub enum LockedSource { @@ -29,6 +33,13 @@ pub enum LockedSource { #[derive(Debug, Clone, Eq, PartialEq)] pub struct LockedPackage { + pub import_name: Option, + pub edges: Vec, + pub features: source::graph::Features, + /// Import binding, distinct from the declared package name. + pub package: Option, + pub id: Option, + pub subdir: Option, pub name: String, pub version: String, pub source: LockedSource, @@ -37,20 +48,43 @@ pub struct LockedPackage { #[derive(Debug, Clone, Eq, PartialEq)] pub struct Lockfile { + pub roots: Vec, pub version: i64, pub packages: Vec, } +impl LockedPackage { + pub fn import_name(&self) -> &str { + self.import_name.as_deref().unwrap_or(&self.name) + } + pub fn package_name(&self) -> &str { + self.package.as_deref().unwrap_or(&self.name) + } + pub fn directory(&self) -> PathBuf { + let (LockedSource::Path { resolved, .. } | LockedSource::Git { resolved, .. }) = + &self.source; + self.subdir + .as_ref() + .map_or_else(|| resolved.clone(), |subdir| resolved.join(subdir)) + } +} + impl Lockfile { pub fn empty() -> Self { Self { version: LOCKFILE_VERSION, packages: Vec::new(), + roots: Vec::new(), } } pub fn normalized(mut self) -> Self { + self.roots.sort_by(|a, b| a.manifest.cmp(&b.manifest)); + for root in &mut self.roots { + normalize_activation(&mut root.edges, &mut root.features); + } for package in &mut self.packages { + normalize_activation(&mut package.edges, &mut package.features); package.dependencies.sort(); package.dependencies.dedup(); } @@ -63,16 +97,98 @@ impl Lockfile { } } +fn normalize_activation(edges: &mut [source::graph::Edge], features: &mut source::graph::Features) { + for edge in edges.iter_mut() { + edge.features.sort(); + } + edges.sort_by_cached_key(|edge| serde_json::to_string(edge).unwrap()); + for members in features.values_mut() { + members.sort(); + } +} + +pub fn package_identity( + name: &str, + version: &str, + source: &LockedSource, + subdir: Option<&str>, +) -> String { + use sha2::{Digest, Sha256}; + // Concrete source identity excludes selectors and import aliases. + let identity = match source { + LockedSource::Path { resolved, .. } => { + #[cfg(windows)] + let path = resolved.to_string_lossy().replace('\\', "/"); + #[cfg(not(windows))] + let path = resolved.to_string_lossy(); + format!("path:{path}") + } + LockedSource::Git { url, commit, .. } => format!("git:{}@{commit}", source::identity(url)), + }; + hex_digest(Sha256::digest( + format!("{name:?}|{version:?}|{identity:?}|{subdir:?}").as_bytes(), + )) +} + +// Keep persisted IDs/checksums as zero-padded lowercase SHA-256 hex. The +// digest output type no longer implements LowerHex in sha2 0.11. +fn hex_digest(bytes: impl AsRef<[u8]>) -> String { + const DIGITS: &[u8; 16] = b"0123456789abcdef"; + bytes + .as_ref() + .iter() + .flat_map(|&byte| { + [ + char::from(DIGITS[(byte >> 4) as usize]), + char::from(DIGITS[(byte & 15) as usize]), + ] + }) + .collect() +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn package_identity_preserves_legacy_sha256_hex() { + // A pre-upgrade identity with leading zeros must remain byte-identical. + let source = LockedSource::Git { + url: "https://example.com/dep.git".to_string(), + branch: None, + tag: None, + rev: None, + commit: "a".repeat(40), + resolved: PathBuf::from("unused"), + }; + assert_eq!( + package_identity("dep211", "1.2.3", &source, None), + "008cd81a9108de700a972998edf1a0fc6db4072fb68a1234a0f6986638738dd6" + ); + } + + #[test] + fn writing_a_legacy_lock_uses_an_escape_aware_format() { + let old = crate::decode(r#"{version=2,package=[{name="dep",version="1.0.0",source="path",path="../new\name",resolved="../new\name",dependencies=[]}]}"#).unwrap(); + let rendered = crate::encode(old.clone()); + let new = crate::decode(&rendered).unwrap(); + assert_eq!(new.version, 3); + assert_eq!(new.packages, old.packages); + } + #[test] fn lockfile_round_trip_preserves_git_commits_and_edges() { let lockfile = Lockfile { version: LOCKFILE_VERSION, + roots: Vec::new(), packages: vec![ LockedPackage { + package: None, + id: None, + import_name: None, + edges: Vec::new(), + features: Default::default(), + subdir: None, name: "core".to_string(), version: "1.0.0".to_string(), source: LockedSource::Path { @@ -82,6 +198,12 @@ mod tests { dependencies: vec![], }, LockedPackage { + package: None, + id: None, + import_name: None, + edges: Vec::new(), + features: Default::default(), + subdir: None, name: "math".to_string(), version: "1.2.3".to_string(), source: LockedSource::Git { diff --git a/lockfile/src/parse.rs b/lockfile/src/parse.rs index 0c42125..3936bcd 100644 --- a/lockfile/src/parse.rs +++ b/lockfile/src/parse.rs @@ -1,7 +1,11 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use std::collections::{BTreeMap, BTreeSet}; use std::path::PathBuf; -use wson::{loads, WsonMap, WsonValue}; +use wson::{loads_versions, WsonMap, WsonValue}; use crate::{LockedPackage, LockedSource, Lockfile, LOCKFILE_NAME, LOCKFILE_VERSION}; @@ -10,8 +14,8 @@ pub fn parse_lockfile(raw: &str) -> Result { } fn parse_lockfile_inner(raw: &str) -> Result { - let data = - loads(raw, "version", 3).map_err(|e| format!("failed to parse `{LOCKFILE_NAME}`: {e}"))?; + let data = loads_versions(raw, "version", &[3, 4]) + .map_err(|e| format!("failed to parse `{LOCKFILE_NAME}`: {e}"))?; let version = match data.get("version") { Some(WsonValue::Int(value)) => *value, _ => { @@ -25,19 +29,20 @@ fn parse_lockfile_inner(raw: &str) -> Result { return Ok(Lockfile { version, packages: Vec::new(), + roots: Vec::new(), }); } - if version != 2 && version != LOCKFILE_VERSION { + if version != 2 && version != 3 && version != LOCKFILE_VERSION { return Err(format!( "unsupported `{LOCKFILE_NAME}` version `{version}`; expected `{LOCKFILE_VERSION}`" )); } - reject_unknown_fields(&data, &["version", "package"], "root")?; + reject_unknown_fields(&data, &["version", "package", "roots"], "root")?; let packages = match data.get("package") { Some(WsonValue::Array(items)) => items .iter() - .map(parse_package) + .map(|value| parse_package(value, version)) .collect::, _>>()?, Some(_) => { return Err(format!( @@ -47,13 +52,23 @@ fn parse_lockfile_inner(raw: &str) -> Result { None => Vec::new(), }; - let lockfile = Lockfile { version, packages }; + let roots: Vec = match data.get("roots") { + Some(value) if version >= 4 => serde_json::from_value(wson::json_value(value)?) + .map_err(|e| format!("invalid lockfile roots: {e}"))?, + Some(_) => return Err("lockfile roots require version 4".into()), + None => Vec::new(), + }; + let lockfile = Lockfile { + version, + packages, + roots, + }; validate_graph(&lockfile)?; let normalized = lockfile.normalized(); Ok(normalized) } -fn parse_package(value: &WsonValue) -> Result { +fn parse_package(value: &WsonValue, lock_version: i64) -> Result { let WsonValue::Object(object) = value else { return Err("lockfile package entry must be an object".to_string()); }; @@ -65,6 +80,11 @@ fn parse_package(value: &WsonValue) -> Result { let fields: &[&str] = match source.as_str() { "path" => &[ "name", + "id", + "package", + "import_name", + "edges", + "features", "version", "source", "path", @@ -73,9 +93,15 @@ fn parse_package(value: &WsonValue) -> Result { ], "git" => &[ "name", + "id", + "package", + "import_name", + "edges", + "features", "version", "source", "git", + "subdir", "branch", "tag", "rev", @@ -120,7 +146,60 @@ fn parse_package(value: &WsonValue) -> Result { )) } }; + let import_name = optional_string(object, "import_name")?; + let edges = match object.get("edges") { + Some(value) => serde_json::from_value(wson::json_value(value)?) + .map_err(|e| format!("invalid lockfile edges: {e}"))?, + None => Vec::new(), + }; + let features = match object.get("features") { + Some(value) => serde_json::from_value(wson::json_value(value)?) + .map_err(|e| format!("invalid locked features: {e}"))?, + None => source::graph::Features::new(), + }; + if lock_version < 4 + && (import_name.is_some() + || object.contains_key("edges") + || object.contains_key("features")) + { + return Err("activation graph requires version 4".into()); + } + source::graph::validate(&features, &edges)?; + let package = optional_string(object, "package")?; + let id = optional_string(object, "id")?; + if (package.is_some() || id.is_some()) && lock_version < 4 { + return Err("package identity requires lockfile version 4".into()); + } + if let Some(package) = &package { + if package.is_empty() + || !package + .bytes() + .enumerate() + .all(|(i, b)| b.is_ascii_alphabetic() || b == b'_' || (i > 0 && b.is_ascii_digit())) + { + return Err("invalid package name in lockfile".into()); + } + } + if id + .as_ref() + .is_some_and(|id| id.len() != 64 || !id.bytes().all(|b| b.is_ascii_hexdigit())) + { + return Err("invalid package identity in lockfile".into()); + } + let subdir = optional_string(object, "subdir")?; + if let Some(value) = &subdir { + if lock_version < 4 { + return Err("subdir requires lockfile version 4".into()); + } + source::validate_subdir(value)?; + } Ok(LockedPackage { + import_name, + edges, + features, + package, + id, + subdir, name, version, source, @@ -142,6 +221,26 @@ fn reject_unknown_fields(object: &WsonMap, allowed: &[&str], context: &str) -> R fn validate_graph(lockfile: &Lockfile) -> Result<(), String> { let mut packages = BTreeMap::new(); for package in &lockfile.packages { + if package.id.is_some() != package.package.is_some() { + return Err( + "lockfile package identity and declared package must appear together".into(), + ); + } + if let Some(id) = &package.id { + if *id + != crate::package_identity( + package.package_name(), + &package.version, + &package.source, + package.subdir.as_deref(), + ) + { + return Err(format!( + "lockfile identity does not match source for `{}`", + package.name + )); + } + } if packages.insert(package.name.as_str(), package).is_some() { return Err(format!( "`{LOCKFILE_NAME}` contains duplicate package `{}`", @@ -149,6 +248,48 @@ fn validate_graph(lockfile: &Lockfile) -> Result<(), String> { )); } } + let validate_edges = |edges: &[source::graph::Edge]| -> Result<(), String> { + let mut seen = BTreeSet::new(); + for edge in edges { + if !seen.insert(serde_json::to_string(edge).unwrap()) { + return Err("duplicate locked activation edge".into()); + } + if !packages.contains_key(edge.key.as_str()) { + return Err(format!( + "locked activation edge references missing package `{}`", + edge.key + )); + } + manifest_alias(&edge.alias)?; + } + Ok(()) + }; + let mut root_paths = BTreeSet::new(); + for root in &lockfile.roots { + source::validate_subdir(&root.manifest)?; + manifest_alias(&root.name)?; + if !root_paths.insert(&root.manifest) { + return Err("duplicate root manifest in lockfile".into()); + } + source::graph::validate(&root.features, &root.edges)?; + validate_edges(&root.edges)?; + } + for package in &lockfile.packages { + validate_edges(&package.edges)?; + if !package.edges.is_empty() + && package + .edges + .iter() + .map(|e| e.key.clone()) + .collect::>() + != package.dependencies.iter().cloned().collect() + { + return Err("locked dependencies disagree with activation edges".into()); + } + if let Some(alias) = &package.import_name { + manifest_alias(alias)?; + } + } let mut indegree: BTreeMap<&str, usize> = packages.keys().map(|name| (*name, 0)).collect(); for package in &lockfile.packages { let mut seen = BTreeSet::new(); @@ -224,6 +365,18 @@ fn validate_graph(lockfile: &Lockfile) -> Result<(), String> { Ok(()) } +fn manifest_alias(alias: &str) -> Result<(), String> { + if alias.is_empty() + || !alias + .bytes() + .enumerate() + .all(|(i, b)| b.is_ascii_alphabetic() || b == b'_' || (i > 0 && b.is_ascii_digit())) + { + return Err("invalid locked import alias".into()); + } + Ok(()) +} + fn validate_commit(commit: &str, package: &str) -> Result<(), String> { if matches!(commit.len(), 40 | 64) && commit.bytes().all(|byte| byte.is_ascii_hexdigit()) { return Ok(()); diff --git a/lockfile/src/render.rs b/lockfile/src/render.rs index 739d3e3..124cd73 100644 --- a/lockfile/src/render.rs +++ b/lockfile/src/render.rs @@ -1,16 +1,27 @@ -use crate::{LockedPackage, LockedSource, Lockfile, LOCKFILE_VERSION}; +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +use crate::{LockedPackage, LockedSource, Lockfile}; pub fn render_lockfile(lockfile: Lockfile) -> String { + // Writing uses escaped strings. Read-only locked operations never call this. + let version = lockfile.version.max(3); + let roots = if lockfile.roots.is_empty() { + String::new() + } else { + format!(" roots = {},\n", graph_json(&lockfile.roots)) + }; let blocks = lockfile .packages .iter() .map(render_package) .collect::>(); if blocks.is_empty() { - return format!("{{\n version = {LOCKFILE_VERSION},\n package = []\n}}\n"); + return format!("{{\n version = {version},\n{roots} package = []\n}}\n"); } format!( - "{{\n version = {LOCKFILE_VERSION},\n package = [\n{}\n ]\n}}\n", + "{{\n version = {version},\n{roots} package = [\n{}\n ]\n}}\n", blocks.join(",\n") ) } @@ -20,6 +31,27 @@ fn render_package(package: &LockedPackage) -> String { render_field("name", &package.name), render_field("version", &package.version), ]; + if let Some(name) = &package.package { + fields.push(render_field("package", name)); + } + if let Some(id) = &package.id { + fields.push(render_field("id", id)); + } + if let Some(alias) = &package.import_name { + fields.push(render_field("import_name", alias)); + } + if !package.edges.is_empty() { + fields.push(format!( + " edges = {}", + graph_json(&package.edges) + )); + } + if !package.features.is_empty() { + fields.push(format!( + " features = {}", + graph_json(&package.features) + )); + } match &package.source { LockedSource::Path { requested, @@ -52,6 +84,9 @@ fn render_package(package: &LockedPackage) -> String { fields.push(render_field("resolved", &portable_path(resolved))); } } + if let Some(subdir) = &package.subdir { + fields.push(render_field("subdir", subdir)); + } let dependencies = package .dependencies .iter() @@ -81,3 +116,8 @@ fn portable_path(path: &std::path::Path) -> String { path.to_string_lossy().into_owned() } } + +fn graph_json(value: &impl serde::Serialize) -> String { + wson::render_json(&serde_json::to_value(value).expect("graph is serializable")) + .expect("validated graph field names") +} diff --git a/lockfile/src/store.rs b/lockfile/src/store.rs index 3a360b7..8d9fa80 100644 --- a/lockfile/src/store.rs +++ b/lockfile/src/store.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use std::fs; use std::io::Write; use std::path::{Path, PathBuf}; diff --git a/manifest/Cargo.toml b/manifest/Cargo.toml index d58411b..f8897ef 100644 --- a/manifest/Cargo.toml +++ b/manifest/Cargo.toml @@ -1,3 +1,7 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 [package] name = "manifest" version.workspace = true @@ -12,3 +16,4 @@ diagnostic.workspace = true source.workspace = true wson.workspace = true semver = "1" +serde_json.workspace = true diff --git a/manifest/src/lib.rs b/manifest/src/lib.rs index b8f66bc..2042e71 100644 --- a/manifest/src/lib.rs +++ b/manifest/src/lib.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use std::collections::BTreeMap; use std::path::{Path, PathBuf}; @@ -5,6 +9,8 @@ mod model; mod native; mod parse; mod render; +pub mod workspace; +pub use workspace::{Workspace, WorkspaceContext}; pub use model::{ BinaryOverride, BuildProfile, PackageTarget, PlatformMode, PlatformSettings, Startup, @@ -55,6 +61,16 @@ pub enum DependencySource { #[derive(Debug, Clone, Eq, PartialEq)] pub struct Dependency { + pub test_only: bool, + pub binding_alias: Option, + pub target: Option, + pub optional: bool, + pub features: Vec, + pub default_features: bool, + pub package: Option, + pub version_req: Option, + pub modern: bool, + pub subdir: Option, pub name: String, pub version: Option, pub source: DependencySource, @@ -62,6 +78,11 @@ pub struct Dependency { #[derive(Debug, Clone)] pub struct Manifest { + pub tests: Vec, + pub workspace: Option, + pub virtual_workspace: bool, + pub scope: Option, + pub fields: std::collections::BTreeSet, pub format: u32, pub compiler: Option, pub name: String, @@ -77,9 +98,57 @@ pub struct Manifest { pub author: Option, pub license: Option, pub dependencies: Vec, + pub features: source::graph::Features, pub source_path: PathBuf, } +impl Dependency { + pub fn import_name(&self) -> &str { + self.binding_alias.as_deref().unwrap_or(&self.name) + } + pub fn edge(&self, key: String) -> source::graph::Edge { + source::graph::Edge { + development: self.test_only, + key, + alias: self.import_name().into(), + optional: self.optional, + default_features: self.default_features, + features: self.features.clone(), + target: self.target.clone(), + } + } + + pub fn package_name(&self) -> &str { + self.package.as_deref().unwrap_or(&self.name) + } + pub fn validate_version(&self, found: &str) -> Result<(), String> { + if self + .version + .as_ref() + .is_some_and(|required| required != found) + { + return Err(format!( + "dependency `{}` requires version `{}` but source contains version `{found}`", + self.import_name(), + self.version.as_ref().unwrap() + )); + } + if let Some(required) = &self.version_req { + let version = semver::Version::parse(found).map_err(|_| { + format!("dependency `{}` version `{found}` is not SemVer", self.name) + })?; + let requirement = semver::VersionReq::parse(required).map_err(|e| e.to_string())?; + if !requirement.matches(&version) { + return Err(format!( + "dependency `{}` requires `{required}` but selected source contains `{found}`", + self.name + )); + } + } + Ok(()) + } +} + impl Manifest { pub fn load() -> Result { let source_path = Path::new(MANIFEST_FILE); @@ -158,3 +227,5 @@ impl Manifest { platform } } + +mod versions; diff --git a/manifest/src/model.rs b/manifest/src/model.rs index b4ab74b..5e1cc49 100644 --- a/manifest/src/model.rs +++ b/manifest/src/model.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use std::collections::{BTreeMap, HashSet}; use std::path::PathBuf; @@ -135,7 +139,7 @@ pub(crate) fn legacy(name: &str, lib: bool, native: Option<&NativeConfig>) -> Mo pub(crate) fn parse(data: &WsonMap, package_name: &str) -> Result { let target_object = object(data.get("targets"), "manifest field `targets`")?; - reject_unknown_fields(target_object, &["lib", "bins"], "targets")?; + reject_unknown_fields(target_object, &["lib", "bins", "tests"], "targets")?; let mut targets = Vec::new(); if let Some(value) = target_object.get("lib") { let library = object(Some(value), "targets.lib")?; @@ -189,7 +193,7 @@ pub(crate) fn parse(data: &WsonMap, package_name: &str) -> Result platform, }); } - if targets.is_empty() { + if targets.is_empty() && array(target_object, "tests", "targets")?.is_empty() { return Err("format 3 requires at least one explicitly declared target".into()); } let default_run = string(data, "default_run", "manifest")?; @@ -468,6 +472,27 @@ fn string(object: &WsonMap, field: &str, context: &str) -> Result } } +pub(crate) fn parse_tests(data: &WsonMap, name: &str) -> Result, String> { + let Some(WsonValue::Object(targets)) = data.get("targets") else { + return Ok(vec![]); + }; + let tests = array(targets, "tests", "targets")?; + if tests.is_empty() { + return Ok(vec![]); + } + let mut model = data.clone(); + model.remove("default_run"); + model.remove("target_config"); + model.insert( + "targets".into(), + WsonValue::Object(WsonMap::from([( + "bins".into(), + WsonValue::Array(tests.to_vec()), + )])), + ); + parse(&model, name).map(|model| model.targets) +} + #[cfg(test)] mod tests { use super::*; diff --git a/manifest/src/native.rs b/manifest/src/native.rs index 7c2603c..e346cfe 100644 --- a/manifest/src/native.rs +++ b/manifest/src/native.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use std::collections::HashSet; use wson::{WsonMap, WsonValue}; diff --git a/manifest/src/parse.rs b/manifest/src/parse.rs index 0d1d2e4..41599b6 100644 --- a/manifest/src/parse.rs +++ b/manifest/src/parse.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use std::collections::HashSet; use std::path::PathBuf; @@ -16,23 +20,42 @@ const ROOT_FIELDS: &[&str] = &[ "author", "license", "dependencies", + "test_dependencies", "targets", "default_run", "profiles", "build", "target_config", + "features", + "workspace", +]; +const DEPENDENCY_FIELDS: &[&str] = &[ + "name", + "version", + "path", + "git", + "branch", + "tag", + "rev", + "subdir", + "package", + "version_req", + "target", + "optional", + "features", + "default_features", ]; -const DEPENDENCY_FIELDS: &[&str] = &["name", "version", "path", "git", "branch", "tag", "rev"]; pub(crate) fn parse_manifest(raw: &str, source_path: PathBuf) -> Result { - let data = loads_versions(raw, "format", &[2, 3]) + let data = loads_versions(raw, "format", &[2, 3, 4]) .map_err(|e| format!("failed to parse manifest: {e}"))?; reject_unknown_fields(&data, ROOT_FIELDS, "manifest")?; let format = match data.get("format") { None | Some(WsonValue::Int(1)) => 1, Some(WsonValue::Int(2)) => 2, Some(WsonValue::Int(3)) => 3, - _ => return Err("unsupported manifest format; expected 1 (legacy), 2 (escaped strings), or 3 (explicit targets)".into()), + Some(WsonValue::Int(4)) => 4, + _ => return Err("unsupported manifest format; expected 1 (legacy), 2 (escaped strings), 3 (explicit targets), or 4 (package graphs)".into()), }; if format < 3 { for field in [ @@ -51,7 +74,7 @@ pub(crate) fn parse_manifest(raw: &str, source_path: PathBuf) -> Result= 3 { if let Some(WsonValue::Object(native)) = data.get("native") { if native.contains_key("output") || native.contains_key("exports") { return Err( @@ -62,8 +85,29 @@ pub(crate) fn parse_manifest(raw: &str, source_path: PathBuf) -> Result restore_url_separators(value), + None if virtual_workspace => "workspace".into(), _ => return Err("manifest field `name` must be a string".to_string()), }; crate::validate_package_name(&name)?; @@ -72,6 +116,13 @@ pub(crate) fn parse_manifest(raw: &str, source_path: PathBuf) -> Result "0.1.0".to_string(), }; + if format >= 4 { + let parsed = semver::Version::parse(&version) + .map_err(|e| format!("format 4 package version must be SemVer: {e}"))?; + if parsed.to_string() != version { + return Err("package version must be canonical SemVer".into()); + } + } let lib = match data.get("lib") { Some(WsonValue::Bool(value)) => *value, None => false, @@ -79,8 +130,30 @@ pub(crate) fn parse_manifest(raw: &str, source_path: PathBuf) -> Result= 3 { + if virtual_workspace { + let mut settings = data.clone(); + settings.insert( + "targets".into(), + wson::loads_versions( + "{format=4,targets={bins=[{name=\"workspace\",path=\"src/main.wave\"}]}}", + "format", + &[4], + )? + .remove("targets") + .unwrap(), + ); + let mut model = crate::model::parse(&settings, &name)?; + if model.target_config.iter().any(|c| !c.bins.is_empty()) { + return Err( + "virtual workspace target_config cannot override package binaries".into(), + ); + } + model.targets.clear(); + model + } else { + crate::model::parse(&data, &name)? + } } else { crate::model::legacy(&name, lib, native.as_ref()) }; @@ -100,7 +173,44 @@ pub(crate) fn parse_manifest(raw: &str, source_path: PathBuf) -> Result= 4 => serde_json::from_value(wson::json_value(value)?) + .map_err(|e| format!("invalid package features: {e}"))?, + Some(_) => return Err("package features require format = 4".into()), + None => source::graph::Features::new(), + }; + source::graph::validate( + &features, + &dependencies + .iter() + .map(|d| d.edge(d.name.clone())) + .collect::>(), + )?; if let Some(dependency) = dependencies .iter() @@ -113,6 +223,11 @@ pub(crate) fn parse_manifest(raw: &str, source_path: PathBuf) -> Result Result, field: &str) -> Result) -> Result, String> { +fn parse_dependencies(value: Option<&WsonValue>, format: u32) -> Result, String> { let mut dependencies = Vec::new(); let mut names = HashSet::new(); let Some(WsonValue::Array(items)) = value else { @@ -157,10 +273,60 @@ fn parse_dependencies(value: Option<&WsonValue>) -> Result, Stri let name = required_string(object.get("name"), "dependency field `name`")?; validate_dependency_name(&name)?; reject_unknown_fields(object, DEPENDENCY_FIELDS, &format!("dependency `{name}`"))?; - if !names.insert(name.clone()) { + let target = object + .get("target") + .map(|value| { + serde_json::from_value::(wson::json_value(value)?) + .map_err(|e| format!("invalid dependency target: {e}")) + }) + .transpose()?; + if let Some(target) = &target { + target.validate()?; + } + let optional = graph_bool(object, "optional", false)?; + let default_features = graph_bool(object, "default_features", true)?; + let features = object + .get("features") + .map(|value| { + serde_json::from_value::>(wson::json_value(value)?) + .map_err(|e| format!("invalid dependency features: {e}")) + }) + .transpose()? + .unwrap_or_default(); + if format < 4 + && ["target", "optional", "features", "default_features"] + .iter() + .any(|key| object.contains_key(*key)) + { + return Err("dependency activation requires format = 4".into()); + } + let declaration = if format >= 4 { + format!("{name}:{target:?}") + } else { + name.clone() + }; + if !names.insert(declaration) { return Err(format!("dependency `{name}` is declared more than once")); } + let package = optional_string(object.get("package"), "dependency field `package`")?; + let version_req = + optional_string(object.get("version_req"), "dependency field `version_req`")?; + if package.is_some() || version_req.is_some() { + if format < 4 { + return Err("package aliases and version_req require format = 4".into()); + } + if let Some(package) = &package { + crate::validate_package_name(package)?; + } + if let Some(required) = &version_req { + if object.contains_key("version") { + return Err("dependency must not combine version and version_req".into()); + } + semver::VersionReq::parse(required) + .map_err(|e| format!("invalid version_req for `{name}`: {e}"))?; + } + } let path = optional_string(object.get("path"), "dependency field `path`")?; let git = optional_string(object.get("git"), "dependency field `git`")?; let branch = optional_string(object.get("branch"), "dependency field `branch`")?; @@ -179,6 +345,16 @@ fn parse_dependencies(value: Option<&WsonValue>) -> Result, Stri )); } } + let subdir = optional_string(object.get("subdir"), "dependency field `subdir`")?; + if let Some(value) = &subdir { + if format < 4 { + return Err("dependency subdir requires format = 4".into()); + } + if git.is_none() { + return Err("subdir applies only to Git dependencies".into()); + } + source::validate_subdir(value)?; + } let version = match object.get("version") { Some(value) => Some(parse_version_string(value).ok_or_else(|| { format!("dependency `{name}` field `version` must be a version or string") @@ -230,6 +406,16 @@ fn parse_dependencies(value: Option<&WsonValue>) -> Result, Stri } }; dependencies.push(Dependency { + test_only: false, + binding_alias: None, + target, + optional, + features, + default_features, + package, + version_req, + modern: format >= 4, + subdir, name, version, source, @@ -238,6 +424,14 @@ fn parse_dependencies(value: Option<&WsonValue>) -> Result, Stri Ok(dependencies) } +fn graph_bool(object: &WsonMap, field: &str, default: bool) -> Result { + match object.get(field) { + None => Ok(default), + Some(WsonValue::Bool(value)) => Ok(*value), + _ => Err(format!("dependency field `{field}` must be a bool")), + } +} + pub(crate) fn reject_unknown_fields( object: &WsonMap, accepted: &[&str], diff --git a/manifest/src/render.rs b/manifest/src/render.rs index cbac799..59aa530 100644 --- a/manifest/src/render.rs +++ b/manifest/src/render.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 pub fn render_new_manifest(project_name: &str, author: &str, is_lib: bool) -> String { format!( r#"{{ diff --git a/manifest/src/versions.rs b/manifest/src/versions.rs new file mode 100644 index 0000000..d240873 --- /dev/null +++ b/manifest/src/versions.rs @@ -0,0 +1,62 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +//! Package compatibility is SemVer; compiler releases retain exact identity. +#[cfg(test)] +mod tests { + use crate::decode; + use std::path::PathBuf; + fn dependency(requirement: &str) -> crate::Dependency { + decode(&format!("{{format=4,name=\"app\",targets={{lib={{}}}},dependencies=[{{name=\"renamed\",package=\"actual\",path=\"../actual\",version_req=\"{requirement}\"}}]}}"), PathBuf::from("vex.ws")).unwrap().dependencies.remove(0) + } + #[test] + fn requirement_boundaries_and_prereleases_follow_semver() { + for (req, version, matches) in [ + ("^1.2.3", "1.9.9", true), + ("^1.2.3", "2.0.0", false), + ("^0.2.3", "0.2.9", true), + ("^0.2.3", "0.3.0", false), + ("^0.0.3", "0.0.4", false), + ("~1.2.3", "1.3.0", false), + (">=1.2.0, <2.0.0", "1.5.0", true), + ("=1.2.3", "1.2.4", false), + ("1.*", "1.7.2", true), + ("*", "1.0.0-alpha", false), + ("^1.0.0-alpha", "1.0.0-beta", true), + ("^1.0.0-alpha", "1.1.0-beta", false), + ("=1.0.0", "1.0.0+build.1", true), + ] { + let dep = dependency(req); + assert_eq!(dep.package_name(), "actual"); + assert_eq!( + dep.validate_version(version).is_ok(), + matches, + "{req} / {version}" + ); + } + } + #[test] + fn format_boundary_preserves_legacy_version_meaning() { + assert!(decode("{name=\"old\",version=\"not semver\"}", "vex.ws".into()).is_ok()); + assert!(decode( + "{format=4,name=\"new\",version=\"not semver\",targets={lib={}}}", + "vex.ws".into() + ) + .is_err()); + for fragment in [ + "version_req=\"bad range\"", + "version=\"1.0.0\",version_req=\"^1\"", + "package=\"bad-name\"", + ] { + assert!(decode(&format!("{{format=4,name=\"app\",targets={{lib={{}}}},dependencies=[{{name=\"dep\",path=\"../dep\",{fragment}}}]}}"), "vex.ws".into()).is_err()); + } + for version in ["01.0.0", "1.0", "v1.0.0", "1.0.0-01"] { + assert!(decode( + &format!("{{format=4,name=\"app\",version=\"{version}\",targets={{lib={{}}}}}}"), + "vex.ws".into() + ) + .is_err()); + } + } +} diff --git a/manifest/src/workspace.rs b/manifest/src/workspace.rs new file mode 100644 index 0000000..e2e37c6 --- /dev/null +++ b/manifest/src/workspace.rs @@ -0,0 +1,301 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +//! Explicit user workspace ownership, independent of Vex's Rust workspace. +use crate::Manifest; +use std::collections::BTreeSet; +use std::path::{Path, PathBuf}; +use wson::WsonValue; + +#[derive(Debug, Clone)] +pub struct Workspace { + pub members: Vec, + pub exclude: Vec, + pub default_members: Option>, +} +#[derive(Debug, Clone)] +pub struct WorkspaceContext { + pub owner: PathBuf, + pub members: Vec, + pub selected: Vec, +} +fn paths(value: Option<&WsonValue>, field: &str) -> Result, String> { + let Some(value) = value else { + return Ok(Vec::new()); + }; + let WsonValue::Array(values) = value else { + return Err(format!("workspace {field} must be an array")); + }; + let mut result = Vec::new(); + let mut seen = BTreeSet::new(); + for value in values { + let WsonValue::String(path) = value else { + return Err(format!("workspace {field} paths must be strings")); + }; + if path != "." { + source::validate_subdir(path)?; + } + if path.contains(['*', '?', '[', ']']) { + return Err("workspace paths are explicit; globs are unsupported".into()); + } + if !seen.insert(path) { + return Err(format!("duplicate workspace {field} path `{path}`")); + } + result.push(path.clone()); + } + Ok(result) +} +pub(crate) fn parse(value: Option<&WsonValue>, format: u32) -> Result, String> { + let Some(value) = value else { + return Ok(None); + }; + if format < 4 { + return Err("workspace requires format = 4".into()); + } + let WsonValue::Object(object) = value else { + return Err("workspace must be an object".into()); + }; + crate::parse::reject_unknown_fields( + object, + &["members", "exclude", "default_members"], + "workspace", + )?; + Ok(Some(Workspace { + members: paths(object.get("members"), "members")?, + exclude: paths(object.get("exclude"), "exclude")?, + default_members: object + .get("default_members") + .map(|value| paths(Some(value), "default_members")) + .transpose()?, + })) +} + +impl Workspace { + pub fn excluded(&self, root: &Path, path: &Path) -> bool { + self.exclude.iter().any(|entry| { + let candidate = root.join(entry); + let candidate = candidate.canonicalize().unwrap_or(candidate); + path.starts_with(candidate) + }) + } + pub fn member_paths(&self, owner: &Manifest) -> Result, diagnostic::Error> { + let root = owner + .source_path + .parent() + .unwrap() + .canonicalize() + .map_err(diagnostic::Error::environment)?; + let mut seen = BTreeSet::new(); + let mut members = Vec::new(); + if !owner.virtual_workspace { + members.push(owner.source_path.clone()); + seen.insert(root.clone()); + } + for entry in &self.members { + let directory = root.join(entry).canonicalize().map_err(|e| { + diagnostic::Error::resolution(format!( + "workspace member `{entry}` is unavailable: {e}" + )) + })?; + if !directory.starts_with(&root) { + return Err(diagnostic::Error::resolution( + "workspace member escapes its workspace root", + )); + } + if self.excluded(&root, &directory) { + continue; + } + if entry == "." && !owner.virtual_workspace { + continue; + } + if !seen.insert(directory.clone()) { + return Err(diagnostic::Error::resolution( + "workspace contains duplicate physical member paths", + )); + } + let manifest = directory.join(crate::MANIFEST_FILE); + if !manifest.is_file() { + return Err(diagnostic::Error::resolution(format!( + "workspace member has no manifest: {}", + manifest.display() + ))); + } + let manifest = manifest + .canonicalize() + .map_err(diagnostic::Error::environment)?; + if manifest.parent() != Some(directory.as_path()) + || manifest + .file_name() + .is_none_or(|n| n != crate::MANIFEST_FILE) + { + return Err(diagnostic::Error::resolution( + "workspace member manifest must stay in its declared directory", + )); + } + members.push(manifest); + } + if members.is_empty() { + return Err(diagnostic::Error::resolution( + "workspace has no package members", + )); + } + Ok(members) + } + pub fn defaults( + &self, + owner: &Manifest, + members: &[Manifest], + ) -> Result, diagnostic::Error> { + let Some(defaults) = &self.default_members else { + return Ok(members.iter().map(|m| m.source_path.clone()).collect()); + }; + let root = owner.source_path.parent().unwrap(); + let mut selected = Vec::new(); + for path in defaults { + let path = root + .join(path) + .join(crate::MANIFEST_FILE) + .canonicalize() + .map_err(diagnostic::Error::resolution)?; + if !members.iter().any(|m| m.source_path == path) { + return Err(diagnostic::Error::resolution( + "default_members must name included workspace members", + )); + } + selected.push(path); + } + if selected.is_empty() { + return Err(diagnostic::Error::resolution( + "default_members must not be empty", + )); + } + Ok(selected) + } +} + +/// Apply only workspace-owned policy. Dependency tool settings still never +/// propagate into a root build. Member-specific binary settings remain local. +pub fn apply_policy( + owner: &Manifest, + member: &mut Manifest, + context: &WorkspaceContext, +) -> Result<(), diagnostic::Error> { + let root = owner.source_path.parent().unwrap(); + if owner.source_path != member.source_path { + if member.workspace.is_some() { + return Err(diagnostic::Error::resolution( + "nested workspace members are unsupported; exclude the nested workspace", + )); + } + if member.fields.contains("profiles") || member.fields.contains("build") { + return Err(diagnostic::Error::resolution( + "workspace profiles and build target belong in the workspace root", + )); + } + if member + .target_config + .iter() + .any(|c| c.sysroot.is_some() || c.linker.is_some()) + { + return Err(diagnostic::Error::resolution( + "workspace sysroot/linker settings belong in the workspace root", + )); + } + if let Some(required) = &owner.compiler { + if member + .compiler + .as_ref() + .is_some_and(|value| value != required) + { + return Err(diagnostic::Error::resolution( + "member compiler requirement conflicts with the workspace root", + )); + } + member.compiler = Some(required.clone()); + } + member.profiles = owner.profiles.clone(); + member.build_target = owner.build_target.clone(); + let local = std::mem::take(&mut member.target_config); + member.target_config = owner + .target_config + .iter() + .map(|config| { + let mut config = config.clone(); + config.bins.clear(); + if let Some(path) = &config.sysroot { + config.sysroot = Some(root.join(path)); + } + if let Some(linker) = &config.linker { + if Path::new(linker).components().count() > 1 || linker.contains('\\') { + config.linker = Some( + root.join(linker) + .to_str() + .ok_or_else(|| { + diagnostic::Error::resolution( + "workspace linker path must be UTF-8", + ) + })? + .to_owned(), + ); + } + } + Ok(config) + }) + .collect::>()?; + for config in local { + if let Some(existing) = member + .target_config + .iter_mut() + .find(|c| c.triple == config.triple) + { + existing.bins = config.bins; + } else { + member.target_config.push(config); + } + } + } + let directory = member.source_path.parent().unwrap(); + for target in member.targets.iter_mut().chain(member.tests.iter_mut()) { + target.path = directory.join(&target.path); + } + member.scope = Some(context.clone()); + Ok(()) +} + +pub fn load_context(context: &WorkspaceContext) -> Result, diagnostic::Error> { + let owner = Manifest::load_from(&context.owner)?; + let mut names = BTreeSet::new(); + let mut members = Vec::new(); + for path in &context.members { + let mut member = Manifest::load_from(path)?; + crate::validate_target_name(&member.name).map_err(diagnostic::Error::resolution)?; + if !names.insert(member.name.to_ascii_lowercase()) { + return Err(diagnostic::Error::resolution( + "workspace package names must be unique, including ASCII case", + )); + } + // An intermediate workspace would create two owners for this package. + for directory in path + .parent() + .unwrap() + .ancestors() + .skip(1) + .take_while(|_| path != &owner.source_path) + { + if directory == owner.source_path.parent().unwrap() { + break; + } + let candidate = directory.join(crate::MANIFEST_FILE); + if candidate.is_file() && Manifest::load_from(&candidate)?.workspace.is_some() { + return Err(diagnostic::Error::resolution( + "workspace member is owned by an intermediate nested workspace", + )); + } + } + apply_policy(&owner, &mut member, context)?; + members.push(member); + } + members.sort_by(|a, b| a.name.cmp(&b.name)); + Ok(members) +} diff --git a/meson.build b/meson.build new file mode 100644 index 0000000..34df890 --- /dev/null +++ b/meson.build @@ -0,0 +1,346 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 +project( + 'vex-automation', + meson_version: '>=1.8.5', + version: run_command( + find_program('python3', 'python'), + files('tools/build_config.py')[0].full_path(), + 'version', + check: true, + ).stdout().strip(), +) + +python = import('python').find_installation() +if run_command( + python, + '-c', + 'import sys; sys.exit(sys.version_info < (3, 11))', + check: false, +).returncode() != 0 + error('Vex automation requires Python 3.11 or newer') +endif +fs = import('fs') +# Register configuration inputs so changing Cargo version/platforms regenerates +# the build definition. Rust source freshness remains exclusively Cargo-owned. +fs.read('Cargo.toml') +fs.read('rust-toolchain.toml') +fs.read('platforms.json') +config = files('tools/build_config.py')[0].full_path() +artifacts = [python, files('tools/release_artifacts.py')[0].full_path()] +executor = [python, files('tools/automation_step.py')[0].full_path()] +step_runner = executor + ['--stamp', '@OUTPUT@', '--'] +cargo = get_option('cargo') +if cargo.length() == 0 + error('The cargo command must not be empty') +endif +version = run_command(python, config, 'version', check: true).stdout().strip() +known_targets = run_command(python, config, 'targets', check: true).stdout().strip().split( + '\n', +) +release_targets = get_option('release_targets') +if release_targets.length() == 0 + release_targets = [ + run_command(python, config, 'host', check: true).stdout().strip(), + ] +endif +selected = [] +foreach triple : release_targets + if not known_targets.contains(triple) + error( + 'Unsupported release target: ' + triple + '\nKnown targets: ' + ', '.join( + known_targets, + ), + ) + endif + if not selected.contains(triple) + selected += triple + endif +endforeach +release_targets = selected + +test_args = [] +if get_option('test_target') != '' + if not known_targets.contains(get_option('test_target')) + error('Unsupported test target: ' + get_option('test_target')) + endif + test_args = ['--target', get_option('test_target')] +endif +python_tests = ['-m', 'unittest', 'discover', '-s', 'tests/tooling', '-v'] +rust_tests = cargo + ['test', '--workspace', '--locked'] + test_args +test( + 'tooling', + python, + args: python_tests, + workdir: meson.project_source_root(), + suite: 'tooling', + timeout: 1800, + is_parallel: false, +) +test( + 'rust', + python, + args: [files('tools/automation_step.py')[0].full_path(), '--'] + cargo + [ + 'test', + '--workspace', + '--locked', + ] + test_args, + workdir: meson.project_source_root(), + suite: 'rust', + timeout: 7200, + is_parallel: false, +) +custom_target( + 'build-debug', + output: 'build-debug.stamp', + command: step_runner + cargo + ['build', '--workspace', '--locked'], + build_always_stale: true, + build_by_default: true, + console: true, +) +run_target( + 'test-compile', + command: executor + ['--'] + rust_tests + ['--no-run'], +) + +# Explicit dependency chains preserve fail-fast ordering. No stamp file may +# suppress a Cargo invocation: Cargo itself owns incremental compilation. +check_steps = [ + {'name': 'format', 'command': cargo + ['fmt', '--check']}, + { + 'name': 'tooling', + 'command': [ + find_program('meson'), + 'test', + '-C', + meson.project_build_root(), + '--no-rebuild', + '--suite', + 'tooling', + '--print-errorlogs', + ], + }, + { + 'name': 'rust', + 'command': [ + find_program('meson'), + 'test', + '-C', + meson.project_build_root(), + '--no-rebuild', + '--suite', + 'rust', + '--print-errorlogs', + ], + }, + { + 'name': 'clippy', + 'command': cargo + [ + 'clippy', + '--workspace', + '--locked', + '--all-targets', + '--', + '-D', + 'warnings', + ], + }, + {'name': 'build', 'command': cargo + ['build', '--workspace', '--locked']}, +] +verify = custom_target( + 'verify-release', + output: 'verify-release.stamp', + command: step_runner + artifacts + ['verify-source'], + build_always_stale: true, + console: true, +) +foreach pipeline : ['check', 'release'] + previous = [] + if pipeline == 'release' + # A development opt-in must never weaken the official release entry point. + source_command = artifacts + ['verify-source'] + if get_option('allow_unverified') + source_command = [ + python, + '-c', + 'raise SystemExit("error: official releases require -Dallow_unverified=false")', + ] + endif + previous = [ + custom_target( + 'release-source', + output: 'release-source.stamp', + command: step_runner + source_command, + build_always_stale: true, + console: true, + ), + ] + endif + foreach step : check_steps + name = pipeline + '-' + step['name'] + phase = custom_target( + name, + output: name + '.stamp', + command: step_runner + step['command'], + depends: previous, + build_always_stale: true, + console: true, + ) + previous = [phase] + endforeach + if pipeline == 'check' + alias_target('check', previous) + else + foreach triple : release_targets + name = 'release-build-' + triple + phase = custom_target( + name, + output: name + '.stamp', + command: step_runner + cargo + [ + 'build', + '--locked', + '--release', + '--target', + triple, + ], + depends: previous, + build_always_stale: true, + console: true, + ) + previous = [phase] + endforeach + run_target( + 'release', + command: artifacts + ['package'] + release_targets, + depends: previous, + ) + endif +endforeach + +builds = [] +foreach triple : release_targets + name = 'build-' + triple + phase = custom_target( + name, + output: name + '.stamp', + command: step_runner + cargo + [ + 'build', + '--locked', + '--release', + '--target', + triple, + ], + depends: builds, + build_always_stale: true, + console: true, + ) + builds = [phase] +endforeach +alias_target('build-release', builds) +package_args = get_option('allow_unverified') ? ['--allow-unverified'] : [] +run_target( + 'package', + command: artifacts + ['package'] + package_args + release_targets, +) +run_target('checksum', command: artifacts + ['checksum'] + release_targets) +run_target('list-targets', command: [python, config, 'list-targets']) +run_target('version', command: [python, config, 'version']) +clean_cargo = custom_target( + 'clean-cargo', + output: 'clean-cargo.stamp', + command: step_runner + cargo + ['clean'], + build_always_stale: true, + console: true, +) +run_target( + 'clean-artifacts', + command: artifacts + ['clean'], + depends: clean_cargo, +) + +quality_steps = [ + { + 'name': 'source', + 'command': [python, files('tools/source_policy.py')[0].full_path()], + }, + { + 'name': 'repository', + 'command': [python, files('tools/repository_checks.py')[0].full_path()], + }, + { + 'name': 'links', + 'command': [ + python, + files('tools/check_links.py')[0].full_path(), + '--external', + ], + }, + { + 'name': 'audit', + 'command': [python, files('tools/dependency_audit.py')[0].full_path()], + }, + { + 'name': 'parser', + 'command': cargo + [ + 'run', + '--locked', + '--example', + 'parser_fuzz', + '--', + '20261005', + '2000', + ], + }, + {'name': 'format', 'command': cargo + ['fmt', '--check']}, + { + 'name': 'clippy', + 'command': cargo + [ + 'clippy', + '--workspace', + '--locked', + '--all-targets', + '--', + '-D', + 'warnings', + ], + }, +] +previous = [] +foreach step : quality_steps + name = 'quality-' + step['name'] + phase = custom_target( + name, + output: name + '.stamp', + command: step_runner + step['command'], + depends: previous, + build_always_stale: true, + console: true, + ) + previous = [phase] +endforeach +alias_target('quality', previous) + +platform = get_option('acceptance_platform') +if platform != '' + known_platforms = run_command(python, config, 'platforms', check: true).stdout().strip().split( + '\n', + ) + if not known_platforms.contains(platform) + error('Unsupported acceptance platform: ' + platform) + endif + script = ['linux-riscv64', 'linux-loongarch64'].contains(platform) ? 'tools/ci_cross.py' : 'tools/ci_platform.py' + run_target( + 'acceptance', + command: [python, files(script)[0].full_path(), platform], + ) +endif +summary( + { + 'Cargo version': version, + 'release targets': release_targets, + 'test target': get_option('test_target'), + 'development unverified packaging': get_option('allow_unverified'), + }, +) diff --git a/meson.options b/meson.options new file mode 100644 index 0000000..f13b6e8 --- /dev/null +++ b/meson.options @@ -0,0 +1,34 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 +option( + 'release_targets', + type: 'array', + value: [], + description: 'Release triples; empty selects the rustc host', +) +option( + 'allow_unverified', + type: 'boolean', + value: false, + description: 'Development package only: allow a missing execution verifier', +) +option( + 'cargo', + type: 'array', + value: ['cargo'], + description: 'Cargo executable and optional leading arguments; never interpreted by a shell', +) +option( + 'test_target', + type: 'string', + value: '', + description: 'Cargo test triple, for host-compiled QEMU acceptance', +) +option( + 'acceptance_platform', + type: 'string', + value: '', + description: 'Platform ID from platforms.json for full compiler/ABI acceptance', +) diff --git a/process/Cargo.toml b/process/Cargo.toml index 91a0179..33d7282 100644 --- a/process/Cargo.toml +++ b/process/Cargo.toml @@ -1,3 +1,7 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 [package] name = "process" version.workspace = true diff --git a/process/src/lib.rs b/process/src/lib.rs index edd9535..cc704aa 100644 --- a/process/src/lib.rs +++ b/process/src/lib.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 //! Supervised child processes. Captured tool output is bounded; user programs //! inherit standard streams and have no implicit timeout. use std::io::Read; diff --git a/resolver/Cargo.toml b/resolver/Cargo.toml index 8fc0ed1..9bea0cc 100644 --- a/resolver/Cargo.toml +++ b/resolver/Cargo.toml @@ -1,3 +1,7 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 [package] name = "resolver" version.workspace = true @@ -15,4 +19,5 @@ manifest.workspace = true lockfile.workspace = true state.workspace = true serde_json.workspace = true -sha2 = "0.10" +sha2 = "0.11.1" +wson.workspace = true diff --git a/resolver/src/activation.rs b/resolver/src/activation.rs new file mode 100644 index 0000000..4b13abc --- /dev/null +++ b/resolver/src/activation.rs @@ -0,0 +1,277 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +//! Pure activation of fully locked union graphs. No filesystem or network I/O. +use diagnostic::Error; +use lockfile::{LockedPackage, LockedSource}; +use source::graph::{Context, Edge, Root, Selection}; +use std::collections::{BTreeMap, BTreeSet}; +use std::path::{Path, PathBuf}; + +#[derive(Clone, Debug)] +pub struct Request { + pub manifest: String, + pub selection: Selection, +} +#[derive(Clone, Debug)] +pub struct View { + pub root: Root, + pub selection: Selection, + pub packages: Vec, + pub dependencies: Vec, + pub features: BTreeMap>, +} +#[derive(Default, Clone, Eq, PartialEq)] +struct Features { + features: BTreeSet, + defaults: bool, +} +fn identity(package: &LockedPackage) -> String { + package.id.clone().unwrap_or_else(|| { + lockfile::package_identity( + package.package_name(), + &package.version, + &package.source, + package.subdir.as_deref(), + ) + }) +} +pub fn root_identity(root: &Root) -> String { + let directory = Path::new(&root.manifest) + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + lockfile::package_identity( + &root.name, + &root.version, + &LockedSource::Path { + requested: directory.to_string_lossy().into_owned(), + resolved: PathBuf::from(directory), + }, + None, + ) +} +fn edges(package: &LockedPackage, packages: &BTreeMap<&str, &LockedPackage>) -> Vec { + if !package.edges.is_empty() { + return package.edges.clone(); + } + package + .dependencies + .iter() + .map(|key| Edge::unconditional(key.clone(), packages[key.as_str()].import_name().into())) + .collect() +} +fn selected( + edges: &[Edge], + enabled: &BTreeSet, + target: &Context, + tests: bool, +) -> Vec { + edges + .iter() + .filter(|edge| { + (!edge.development || tests) + && edge.target.as_ref().is_none_or(|p| p.matches(target)) + && (!edge.optional || enabled.contains(&edge.alias)) + }) + .cloned() + .collect() +} +/// Workspace package qualification is resolved before feature expansion. With +/// several selected roots, unqualified names would silently affect the wrong +/// package and are rejected. +pub(crate) fn qualify(roots: &[Root], requests: &[Request]) -> Result, Error> { + let selected: BTreeSet<_> = requests.iter().map(|r| r.manifest.as_str()).collect(); + let mut result = Vec::new(); + for request in requests { + let root = roots + .iter() + .find(|root| root.manifest == request.manifest) + .ok_or_else(|| Error::resolution("selected root is not in the workspace graph"))?; + let mut selection = request.selection.clone(); + selection.features.clear(); + for feature in &request.selection.features { + if let Some((package, value)) = feature.split_once('/') { + if let Some(owner) = roots.iter().find(|root| root.name == package) { + if !selected.contains(owner.manifest.as_str()) { + return Err(Error::resolution(format!( + "feature names unselected package `{package}`" + ))); + } + if owner.manifest == root.manifest { + selection.features.insert(value.into()); + } + continue; + } + } + if selected.len() > 1 { + return Err(Error::resolution( + "features for several workspace packages require package/feature qualification", + )); + } + selection.features.insert(feature.clone()); + } + if selection.target.is_none() { + selection.target = Some(Context::host()); + } + result.push(Request { + manifest: request.manifest.clone(), + selection, + }); + } + Ok(result) +} + +pub(crate) fn select( + roots: &[Root], + union: &[LockedPackage], + requests: &[Request], +) -> Result, Error> { + let requests = qualify(roots, requests)?; + let packages: BTreeMap<_, _> = union.iter().map(|p| (p.name.as_str(), p)).collect(); + let roots: BTreeMap<_, _> = roots + .iter() + .map(|root| (root.manifest.as_str(), root)) + .collect(); + let mut reached: BTreeSet<(String, Context)> = BTreeSet::new(); + let mut groups: BTreeMap = BTreeMap::new(); + for request in &requests { + let group = groups + .entry(root_identity(roots[request.manifest.as_str()])) + .or_default(); + group + .features + .extend(request.selection.features.iter().cloned()); + group.defaults |= !request.selection.no_default_features; + } + loop { + let previous = (reached.clone(), groups.clone()); + let mut parents = Vec::new(); + for request in &requests { + let root = roots[request.manifest.as_str()]; + let context = request.selection.target.as_ref().unwrap(); + let group = &groups[&root_identity(root)]; + let expanded = + source::graph::expand(&root.features, &root.edges, &group.features, group.defaults) + .map_err(|e| Error::resolution(e).with_field("package", &root.name))?; + parents.push(( + selected( + &root.edges, + &expanded.enabled, + context, + request.selection.include_tests, + ), + expanded.forwarded, + context.clone(), + )); + } + for (key, context) in &reached { + let package = packages[key.as_str()]; + let group = &groups[&identity(package)]; + let all_edges = edges(package, &packages); + let expanded = source::graph::expand( + &package.features, + &all_edges, + &group.features, + group.defaults, + ) + .map_err(|e| Error::resolution(e).with_field("package", package.package_name()))?; + parents.push(( + selected(&all_edges, &expanded.enabled, context, false), + expanded.forwarded, + context.clone(), + )); + } + for (edges, forwarded, context) in parents { + for edge in edges { + let child = packages + .get(edge.key.as_str()) + .ok_or_else(|| Error::resolution("activation edge has no locked source"))?; + reached.insert((edge.key, context.clone())); + let group = groups.entry(identity(child)).or_default(); + group.defaults |= edge.default_features; + group.features.extend(edge.features); + if let Some(features) = forwarded.get(&edge.alias) { + group.features.extend(features.iter().cloned()); + } + } + } + if previous == (reached.clone(), groups.clone()) { + break; + } + } + let mut views = Vec::new(); + for request in requests { + let root = roots[request.manifest.as_str()]; + let context = request.selection.target.as_ref().unwrap(); + let group = &groups[&root_identity(root)]; + let expanded = + source::graph::expand(&root.features, &root.edges, &group.features, group.defaults) + .map_err(Error::resolution)?; + let root_edges = selected( + &root.edges, + &expanded.enabled, + context, + request.selection.include_tests, + ); + let mut features = BTreeMap::from([(root_identity(root), expanded.features)]); + let mut pending: Vec<_> = root_edges.iter().map(|edge| edge.key.clone()).collect(); + let mut seen = BTreeSet::new(); + let mut aliases = BTreeMap::new(); + let mut active = Vec::new(); + while let Some(key) = pending.pop() { + if !seen.insert(key.clone()) { + continue; + } + let package = packages[key.as_str()]; + let id = identity(package); + let alias = package.import_name(); + if alias == root.name { + return Err(Error::resolution(format!( + "dependency alias `{alias}` conflicts with root package `{}`", + root.name + ))); + } + if aliases + .insert(alias, id.clone()) + .is_some_and(|previous| previous != id) + { + return Err(Error::resolution(format!("import alias `{alias}` refers to multiple active package sources; Wave currently exposes a global import-name map\nhelp: choose distinct aliases; scoped compiler dependency mappings are required for conflicting transitive imports"))); + } + let group = &groups[&id]; + let all_edges = edges(package, &packages); + let expanded = source::graph::expand( + &package.features, + &all_edges, + &group.features, + group.defaults, + ) + .map_err(Error::resolution)?; + features.insert(id, expanded.features); + let mut package = package.clone(); + package.dependencies = selected(&all_edges, &expanded.enabled, context, false) + .into_iter() + .map(|e| e.key) + .collect::>() + .into_iter() + .collect(); + pending.extend(package.dependencies.iter().cloned()); + active.push(package); + } + active.sort_by(|a, b| a.name.cmp(&b.name)); + views.push(View { + root: root.clone(), + selection: request.selection, + packages: active, + dependencies: root_edges + .into_iter() + .map(|e| e.key) + .collect::>() + .into_iter() + .collect(), + features, + }); + } + Ok(views) +} diff --git a/resolver/src/cache.rs b/resolver/src/cache.rs new file mode 100644 index 0000000..d5a6928 --- /dev/null +++ b/resolver/src/cache.rs @@ -0,0 +1,356 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +//! Shared immutable Git objects; project worktrees never depend on cache lifetime. +use crate::{git, paths::git_cli_path}; +use diagnostic::Error; +use sha2::{Digest, Sha256}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::Command; + +fn home() -> Result { + if let Some(path) = std::env::var_os("VEX_CACHE_HOME") { + let path = PathBuf::from(path); + if !path.is_absolute() { + return Err(Error::environment("VEX_CACHE_HOME must be absolute")); + } + return Ok(path); + } + #[cfg(windows)] + let base = std::env::var_os("LOCALAPPDATA").map(PathBuf::from); + #[cfg(target_os = "macos")] + let base = std::env::var_os("HOME").map(|p| PathBuf::from(p).join("Library/Caches")); + #[cfg(all(not(windows), not(target_os = "macos")))] + let base = std::env::var_os("XDG_CACHE_HOME") + .map(PathBuf::from) + .filter(|p| p.is_absolute()) + .or_else(|| std::env::var_os("HOME").map(|p| PathBuf::from(p).join(".cache"))); + base.filter(|p| p.is_absolute()) + .map(|p| p.join("vex")) + .ok_or_else(|| Error::environment("cannot locate user cache; set VEX_CACHE_HOME")) +} + +struct Cache { + path: PathBuf, + _guard: state::FileGuard, +} +impl Cache { + fn open(url: &str) -> Result { + // Credential contexts may expose different repositories at the same URL. + // Hash the declaration, never persist or display its authentication. + let key = crate::hex_digest(Sha256::digest(url.as_bytes())); + let root = home()?.join("git"); + fs::create_dir_all(&root).map_err(Error::environment)?; + state::reject_link(&root).map_err(Error::environment)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&root, fs::Permissions::from_mode(0o700)) + .map_err(Error::environment)?; + } + let guard = state::FileGuard::exclusive(&root.join(format!("{key}.lock")), || {}) + .map_err(Error::environment)?; + Ok(Self { + path: root.join(format!("{key}.git")), + _guard: guard, + }) + } + fn valid(&self, url: &str) -> Result { + state::reject_link(&self.path).map_err(Error::environment)?; + if !self.path.exists() { + return Ok(false); + } + // No source content is trusted until Git verifies its complete object graph. + let checked = (|| { + crate::transaction::reject_git_metadata_links(&self.path) + .map_err(Error::environment)?; + let origin = git::stdout( + bare(&self.path).args(["config", "--get", "remote.origin.url"]), + "read cache origin", + )?; + if origin.trim_end() != source::identity(url) { + return Err(Error::resolution("cache source mismatch")); + } + git::run( + bare(&self.path).args(["fsck", "--full", "--no-dangling"]), + "verify cached objects", + ) + })(); + if let Err(error) = checked { + if process::cancelled() || process::failure_code() == 124 { + return Err(error); + } + let quarantine = self.path.with_extension(format!("quarantine-{}", stamp())); + fs::rename(&self.path, quarantine).map_err(Error::environment)?; + state::sync_dir(self.path.parent().unwrap())?; + return Ok(false); + } + Ok(true) + } +} + +fn stamp() -> u128 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_nanos() +} +fn local() -> Command { + let mut command = git::command(); + // Even a user's insteadOf rewrite cannot turn an offline import into HTTP/SSH. + command.args([ + "-c", + "protocol.allow=never", + "-c", + "protocol.file.allow=always", + ]); + command +} +fn bare(path: &Path) -> Command { + let mut command = local(); + // Match project Git commands: let Win32 enter the repository and keep + // Git's own object paths relative, including in index-pack children. + command.current_dir(path).args(["--git-dir", "."]); + command +} + +pub(crate) fn restore(destination: &Path, url: &str, commit: &str) -> Result { + let cache = Cache::open(url)?; + if !cache.valid(url)? { + return Ok(false); + } + if !matches!(git::stdout(bare(&cache.path).args(["cat-file", "-t", commit]), "inspect cached commit"), Ok(value) if value == "commit") + { + return Ok(false); + } + if !destination.join(".git").exists() { + fs::create_dir_all(destination.parent().unwrap()).map_err(Error::environment)?; + if destination.as_os_str().len() > 200 { + let format = git::stdout( + bare(&cache.path).args(["rev-parse", "--show-object-format"]), + "read cached object format", + )?; + if !matches!(format.as_str(), "sha1" | "sha256") { + return Err(Error::resolution("unsupported cached object format")); + } + fs::create_dir(destination).map_err(Error::environment)?; + git::run( + local().current_dir(destination).args([ + "init", + "--template=", + &format!("--object-format={format}"), + "--", + ".", + ]), + "initialize cached checkout", + )?; + let mut command = git::command_in(destination); + command + .args([ + "-c", + "protocol.allow=never", + "-c", + "protocol.file.allow=always", + "fetch", + "--no-tags", + "--", + ]) + .arg(git_cli_path(&cache.path).as_ref()) + .arg(commit); + git::run(&mut command, "restore cached Git objects")?; + } else { + git::run( + local() + .args([ + "clone", + "--no-hardlinks", + "--dissociate", + "--no-checkout", + "--local", + "--", + ]) + .arg(git_cli_path(&cache.path).as_ref()) + .arg(git_cli_path(destination).as_ref()), + "restore cached Git objects", + )?; + } + git::run( + git::command_in(destination).args([ + "config", + "--replace-all", + "remote.origin.url", + &source::identity(url), + ]), + "store cached source origin", + )?; + git::run( + git::command_in(destination).args(["checkout", "--detach", commit]), + "populate cached checkout", + )?; + } else { + git::verify_origin(destination, url)?; + let mut command = git::command_in(destination); + command + .args([ + "-c", + "protocol.allow=never", + "-c", + "protocol.file.allow=always", + "fetch", + "--no-tags", + "--", + ]) + .arg(git_cli_path(&cache.path).as_ref()) + .arg(commit); + git::run(&mut command, "import cached Git objects")?; + } + git::has_commit(destination, commit) +} + +pub(crate) fn store(checkout: &Path, url: &str, commit: &str) -> Result<(), Error> { + let cache = Cache::open(url)?; + if cache.valid(url)? { + if matches!(git::stdout(bare(&cache.path).args(["cat-file", "-t", commit]), "inspect cached commit"), Ok(value) if value == "commit") + { + return Ok(()); + } + // Do not serve a deep transactional checkout through upload-pack. + // Git for Windows can select the wrong repository or exceed its loose + // object path limit in that nested local transport. A self-contained + // bundle is produced from the checkout's own cwd, then indexed locally; + // no transport rewrites, repository refs, or alternates are involved. + let bundle = cache.path.with_extension(format!( + "incoming-{}-{}.bundle", + std::process::id(), + stamp() + )); + let result = (|| { + git::run( + git::command_in(checkout) + .args(["bundle", "create"]) + .arg(git_cli_path(&bundle).as_ref()) + .args(["HEAD", commit]), + "bundle verified Git objects", + )?; + git::run( + bare(&cache.path) + .args(["bundle", "verify"]) + .arg(git_cli_path(&bundle).as_ref()), + "verify Git object bundle", + )?; + git::run( + bare(&cache.path) + .args(["bundle", "unbundle"]) + .arg(git_cli_path(&bundle).as_ref()), + "import verified Git objects", + )?; + git::run( + bare(&cache.path).args(["update-ref", &format!("refs/vex/pins/{commit}"), commit]), + "retain verified Git object", + )?; + git::run( + bare(&cache.path).args(["fsck", "--full", "--no-dangling"]), + "verify extended cache", + )?; + crate::transaction::sync_tree(&cache.path).map_err(Error::environment) + })(); + if bundle.exists() { + let _ = fs::remove_file(&bundle); + } + result?; + return Ok(()); + } + let stage = cache + .path + .with_extension(format!("stage-{}-{}", std::process::id(), stamp())); + let result = (|| { + git::run( + local() + .args([ + "clone", + "--bare", + "--no-hardlinks", + "--dissociate", + "--local", + "--", + ]) + .arg(git_cli_path(checkout).as_ref()) + .arg(git_cli_path(&stage).as_ref()), + "cache verified Git objects", + )?; + git::run( + bare(&stage).args([ + "config", + "--replace-all", + "remote.origin.url", + &source::identity(url), + ]), + "store credential-free cache origin", + )?; + git::run( + bare(&stage).args(["update-ref", &format!("refs/vex/pins/{commit}"), commit]), + "retain locked cached object", + )?; + git::run( + bare(&stage).args(["fsck", "--full", "--no-dangling"]), + "verify new cache", + )?; + crate::transaction::sync_tree(&stage).map_err(Error::environment)?; + fs::rename(&stage, &cache.path).map_err(Error::environment)?; + state::sync_dir(cache.path.parent().unwrap())?; + Ok(()) + })(); + if stage.exists() { + let _ = fs::remove_dir_all(&stage); + } + result +} + +/// Explicit cache cleanup. Project checkouts own all their objects, so no project +/// liveness guessing is needed. Coordination inodes and quarantines are retained. +pub fn prune(apply: bool) -> Result, Error> { + let root = home()?.join("git"); + state::reject_link(&root).map_err(Error::environment)?; + if !root.exists() { + return Ok(Vec::new()); + } + let mut candidates = fs::read_dir(&root) + .map_err(Error::environment)? + .map(|e| e.map(|e| e.path())) + .collect::, _>>()?; + candidates.sort(); + let mut removed = Vec::new(); + for path in candidates { + let Some(key) = path.file_stem().and_then(|s| s.to_str()) else { + continue; + }; + if path.extension().and_then(|s| s.to_str()) != Some("git") + || key.len() != 64 + || !key.bytes().all(|b| b.is_ascii_hexdigit()) + { + continue; + } + let _guard = state::FileGuard::exclusive(&root.join(format!("{key}.lock")), || {}) + .map_err(Error::environment)?; + state::reject_link(&path).map_err(Error::environment)?; + if !path.is_dir() { + continue; + } + // Only recognized bare repositories in the cache namespace are removed. + if git::stdout( + bare(&path).args(["rev-parse", "--is-bare-repository"]), + "inspect cache repository", + )? != "true" + { + continue; + } + if apply { + fs::remove_dir_all(&path).map_err(Error::environment)?; + state::sync_dir(&root)?; + } + removed.push(path); + } + Ok(removed) +} diff --git a/resolver/src/git.rs b/resolver/src/git.rs index aec388a..4790c9b 100644 --- a/resolver/src/git.rs +++ b/resolver/src/git.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use diagnostic::Error; use std::fs; use std::path::Path; @@ -80,7 +84,7 @@ pub(crate) fn ensure_repository( } else { run( command() - .args(["clone", "--", url]) + .args(["clone", "--no-hardlinks", "--dissociate", "--", url]) .arg(git_cli_path(destination).as_ref()), "clone Git dependency", )?; @@ -410,7 +414,7 @@ pub(crate) fn command_in(destination: &Path) -> Command { command } -fn command() -> Command { +pub(crate) fn command() -> Command { let mut command = Command::new("git"); command.args(["-c", "protocol.ext.allow=never"]); // Canonical checkout names plus transaction staging can exceed MAX_PATH @@ -472,7 +476,7 @@ fn inject_failure(_action: &str) -> Result<(), Error> { Ok(()) } -fn run(command: &mut Command, action: &str) -> Result<(), Error> { +pub(crate) fn run(command: &mut Command, action: &str) -> Result<(), Error> { inject_failure(action)?; let output = command .supervised_output() diff --git a/resolver/src/graph.rs b/resolver/src/graph.rs index b04a3c5..94d5310 100644 --- a/resolver/src/graph.rs +++ b/resolver/src/graph.rs @@ -1,5 +1,9 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use diagnostic::Error; -use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::collections::{BTreeMap, HashMap}; use std::path::{Path, PathBuf}; use lockfile::{LockedPackage, LockedSource, Lockfile, LOCKFILE_NAME}; @@ -8,11 +12,12 @@ use manifest::{Dependency, DependencySource, Manifest, MANIFEST_FILE}; use crate::git; use crate::paths::{relative_to_root, resolve_path}; use crate::transaction::Transaction; -use crate::{ResolveOptions, UpdatePolicy}; +use crate::ResolveOptions; pub(crate) struct Resolver<'a> { options: ResolveOptions, preflight: bool, + updating: bool, root: PathBuf, transaction: Option<&'a Transaction>, root_name: String, @@ -22,17 +27,21 @@ pub(crate) struct Resolver<'a> { requests: HashMap, request_origins: HashMap, visiting: Vec, + git_selections: HashMap, status: &'a mut dyn FnMut(&str, String), - validate: &'a mut dyn FnMut(&Manifest) -> Result<(), Error>, + manifests: BTreeMap, } #[derive(Clone, Debug, Eq, PartialEq)] enum RequestKey { Path { + package: String, resolved: PathBuf, version: Option, }, Git { + package: String, + subdir: Option, url: String, branch: Option, tag: Option, @@ -52,11 +61,11 @@ impl<'a> Resolver<'a> { root_manifest: PathBuf, existing: &'a Lockfile, status: &'a mut dyn FnMut(&str, String), - validate: &'a mut dyn FnMut(&Manifest) -> Result<(), Error>, ) -> Self { Self { options, preflight: false, + updating: true, root, transaction, root_name, @@ -66,8 +75,9 @@ impl<'a> Resolver<'a> { requests: HashMap::new(), request_origins: HashMap::new(), visiting: Vec::new(), + git_selections: HashMap::new(), status, - validate, + manifests: BTreeMap::new(), } } @@ -116,65 +126,24 @@ impl<'a> Resolver<'a> { self.preflight = true; } - pub(crate) fn into_packages(self) -> Vec { - self.packages.into_values().collect() + pub(crate) fn into_packages(self) -> (Vec, BTreeMap) { + (self.packages.into_values().collect(), self.manifests) } - pub(crate) fn validate_selected_packages(&self) -> Result<(), Error> { - let UpdatePolicy::UpdateSelected(selected) = &self.options.update else { - return Ok(()); - }; - - let available = self - .packages - .values() - .filter(|package| matches!(package.source, LockedSource::Git { .. })) - .map(|package| package.name.as_str()) - .collect::>(); - let unavailable = selected - .iter() - .filter(|name| !available.contains(name.as_str())) - .cloned() - .collect::>(); - - if unavailable.is_empty() { - return Ok(()); - } - - let requested = unavailable - .iter() - .map(|name| format!("`{name}`")) - .collect::>() - .join(", "); - let package_label = if unavailable.len() == 1 { - "package" - } else { - "packages" - }; - let available = if available.is_empty() { - "".to_string() - } else { - available.into_iter().collect::>().join(", ") - }; - Err(Error::resolution(format!( - "cannot update {package_label} {requested}: one or more requested names are not Git dependencies in the current graph\nhelp: available Git packages: {available}\nhelp: run `vex update ...` using one or more available package names" - ))) + pub(crate) fn set_updating(&mut self, value: bool) { + self.updating = value; } pub(crate) fn resolve_manifest_dependencies( &mut self, manifest: &Manifest, ) -> Result, Error> { - (self.validate)(manifest).map_err(|error| { - error - .with_field("package", &manifest.name) - .with_field("manifest", manifest.source_path.display()) - })?; let mut dependencies = Vec::new(); let mut edges: Vec<_> = manifest.dependencies.iter().collect(); edges.sort_by(|a, b| a.name.cmp(&b.name)); for dependency in edges { - self.resolve_dependency(dependency, &manifest.source_path) + let key = self + .resolve_dependency(dependency, &manifest.source_path) .map_err(|error| { error .with_field("package", &dependency.name) @@ -185,13 +154,86 @@ impl<'a> Resolver<'a> { manifest.source_path.display() )) })?; - dependencies.push(dependency.name.clone()); + dependencies.push(key); } dependencies.sort(); Ok(dependencies) } + fn binding_key(&self, dependency: &Dependency, parent: &Path) -> Result { + if !dependency.modern && !self.options.force_bindings { + return Ok(dependency.name.clone()); + } + use sha2::{Digest, Sha256}; + let source = match &dependency.source { + DependencySource::Path { path } => format!( + "path:{:?}", + crate::paths::portable_path(&relative_to_root( + &self.logical(&self.resolve_path(path, parent)?), + &self.root + ))? + ), + DependencySource::Git { + url, + branch, + tag, + rev, + } => format!("git:{:?}|{branch:?}|{tag:?}|{rev:?}", source::identity(url)), + }; + Ok(format!( + "binding_{}", + crate::hex_digest(Sha256::digest( + format!( + "{:?}|{:?}|{source}|{:?}", + dependency.name, + dependency.package_name(), + dependency.subdir + ) + .as_bytes() + )) + )) + } + fn edges_for(&self, manifest: &Manifest) -> Result, Error> { + manifest + .dependencies + .iter() + .map(|dep| Ok(dep.edge(self.binding_key(dep, &manifest.source_path)?))) + .collect() + } + pub(crate) fn root_record(&self, manifest: &Manifest) -> Result { + let path = if manifest.source_path.is_absolute() { + manifest.source_path.clone() + } else { + self.root.join(&manifest.source_path) + }; + Ok(source::graph::Root { + manifest: crate::paths::portable_path(&relative_to_root( + &self.logical(&path), + &self.root, + ))?, + name: manifest.name.clone(), + version: manifest.version.clone(), + edges: self.edges_for(manifest)?, + features: manifest.features.clone(), + }) + } fn resolve_dependency( + &mut self, + dependency: &Dependency, + parent: &Path, + ) -> Result { + let mut binding = dependency.clone(); + binding.name = self.binding_key(dependency, parent)?; + if dependency.modern || self.options.force_bindings { + binding.modern = true; + binding.binding_alias = Some(dependency.name.clone()); + binding.package = Some(dependency.package_name().into()); + } + self.resolve_binding(&binding, parent)?; + Ok(binding.name) + } + + fn resolve_binding( &mut self, dependency: &Dependency, parent_manifest: &Path, @@ -215,8 +257,13 @@ impl<'a> Resolver<'a> { let key = match &dependency.source { DependencySource::Path { path } => RequestKey::Path { + package: dependency.package_name().to_owned(), resolved: self.logical(&self.resolve_path(path, parent_manifest)?), - version: dependency.version.clone(), + version: if dependency.modern { + None + } else { + dependency.version.clone() + }, }, DependencySource::Git { url, @@ -224,11 +271,17 @@ impl<'a> Resolver<'a> { tag, rev, } => RequestKey::Git { + package: dependency.package_name().to_owned(), + subdir: dependency.subdir.clone(), url: source::identity(url), branch: branch.clone(), tag: tag.clone(), rev: rev.clone(), - version: dependency.version.clone(), + version: if dependency.modern { + None + } else { + dependency.version.clone() + }, }, }; @@ -240,7 +293,7 @@ impl<'a> Resolver<'a> { if let Some(previous) = self.requests.get(&dependency.name) { if previous != &key { return Err(Error::resolution(format!( - "package name `{}` refers to more than one source or version requirement\nfirst: {} ({})\nsecond: {} ({})", + "package name `{}` refers to more than one source or version requirement\nfirst: {} ({})\nsecond: {} ({})\nWave currently exposes a global import-name map; conflicting transitive aliases require scoped compiler dependency mappings", dependency.name, self.request_origins[&dependency.name].0, self.request_origins[&dependency.name].1, chain, parent_manifest.display() )).with_field("first_dependency_path", &self.request_origins[&dependency.name].0) @@ -249,6 +302,14 @@ impl<'a> Resolver<'a> { .with_field("second_request", format!("{key:?}"))); } if let Some(package) = self.packages.get_mut(&dependency.name) { + dependency.validate_version(&package.version).map_err(|e| { + Error::resolution(e) + .with_field( + "first_dependency_path", + &self.request_origins[&dependency.name].0, + ) + .with_field("second_dependency_path", &chain) + })?; if self.existing.package(&dependency.name).is_none() { if let (LockedSource::Path { requested, .. }, DependencySource::Path { path }) = (&mut package.source, &dependency.source) @@ -432,6 +493,10 @@ impl<'a> Resolver<'a> { } else { self.resolve_git_commit(dependency, &destination)? }; + self.git_selections.insert( + format!("{url:?}|{branch:?}|{tag:?}|{rev:?}"), + commit.clone(), + ); git::reject_submodules(&destination, name, &commit)?; let logical_destination = self.logical(&destination); (self.status)( @@ -454,12 +519,36 @@ impl<'a> Resolver<'a> { } }; + let checkout_path = resolved_path.clone(); + let resolved_path = if let Some(subdir) = &dependency.subdir { + let selected = resolved_path + .join(subdir) + .canonicalize() + .map_err(Error::resolution)?; + let repository = resolved_path.canonicalize().map_err(Error::resolution)?; + if !selected.starts_with(&repository) { + return Err(Error::resolution( + "dependency subdir escapes its repository", + )); + } + selected + } else { + resolved_path + }; let manifest_path = resolved_path.join(MANIFEST_FILE); + if matches!(locked_source, LockedSource::Git { .. }) && manifest_path.exists() { + let actual = manifest_path.canonicalize().map_err(Error::resolution)?; + if !actual.starts_with(checkout_path.canonicalize().map_err(Error::resolution)?) { + return Err(Error::resolution( + "dependency manifest escapes its Git repository", + )); + } + } let package_manifest = Manifest::load_from(&manifest_path).map_err(|e| { e.with_field("package", &dependency.name) .with_field("operation", "load dependency manifest") })?; - if package_manifest.name != dependency.name { + if package_manifest.name != dependency.package_name() { return Err(Error::resolution(format!( "dependency is named `{}` but `{}` declares package `{}`", dependency.name, @@ -482,14 +571,17 @@ impl<'a> Resolver<'a> { library_entry.display() ))); } - if let Some(required) = dependency.version.as_deref() { - if package_manifest.version != required { - return Err(Error::resolution(format!( - "dependency `{}` requires version `{required}` but source contains version `{}`", - dependency.name, package_manifest.version - ))); + if matches!(locked_source, LockedSource::Git { .. }) { + let actual = library_entry.canonicalize().map_err(Error::resolution)?; + if !actual.starts_with(checkout_path.canonicalize().map_err(Error::resolution)?) { + return Err(Error::resolution( + "dependency library entry escapes its Git repository", + )); } } + dependency + .validate_version(&package_manifest.version) + .map_err(|e| Error::resolution(e).with_field("dependency_path", &chain))?; self.visiting.push(dependency.name.clone()); let dependencies = self.resolve_manifest_dependencies(&package_manifest)?; @@ -498,7 +590,7 @@ impl<'a> Resolver<'a> { if let Some(replace) = record_checkout { if let LockedSource::Git { url, commit, .. } = &locked_source { crate::prune::record_checkout( - &resolved_path, + &checkout_path, &dependency.name, url, commit, @@ -507,9 +599,42 @@ impl<'a> Resolver<'a> { } } + // Deletion ownership is deliberately stricter than source verification. + // A validated staged checkout still supplies immutable Git objects when + // prune must preserve its layout or user-created repository metadata. + if !self.options.dry_run && self.logical(&checkout_path) != checkout_path { + if let LockedSource::Git { url: _, commit, .. } = &locked_source { + if let DependencySource::Git { url, .. } = &dependency.source { + crate::cache::store(&checkout_path, url, commit)?; + } + } + } + + let edges = self.edges_for(&package_manifest)?; + self.manifests + .insert(dependency.name.clone(), package_manifest.clone()); self.packages.insert( dependency.name.clone(), LockedPackage { + import_name: dependency + .modern + .then(|| dependency.import_name().to_owned()), + edges: if dependency.modern || package_manifest.format >= 4 { + edges + } else { + Vec::new() + }, + features: package_manifest.features.clone(), + package: dependency.modern.then(|| package_manifest.name.clone()), + id: dependency.modern.then(|| { + lockfile::package_identity( + &package_manifest.name, + &package_manifest.version, + &locked_source, + dependency.subdir.as_deref(), + ) + }), + subdir: dependency.subdir.clone(), name: dependency.name.clone(), version: package_manifest.version, source: locked_source, @@ -529,29 +654,53 @@ impl<'a> Resolver<'a> { else { return None; }; - if !self.preflight && self.options.update.updates(&dependency.name) { - None - } else { - self.existing - .package(&dependency.name) - .and_then(|package| match &package.source { - LockedSource::Git { - url: locked_url, - branch: locked_branch, - tag: locked_tag, - rev: locked_rev, - commit, - .. - } if source::identity(locked_url) == source::identity(url) - && locked_branch == branch - && locked_tag == tag - && locked_rev == rev => - { - Some(commit.clone()) - } - _ => None, - }) + let pinned = self.existing_git(dependency).and_then(|package| { + if let LockedSource::Git { commit, .. } = &package.source { + Some(commit.clone()) + } else { + None + } + }); + if self.preflight || self.options.dry_run || self.options.locked { + return pinned; } + if !(self.updating + && self + .options + .updates_binding(&dependency.name, dependency.import_name())) + && pinned.is_some() + { + return pinned; + } + self.git_selections + .get(&format!("{url:?}|{branch:?}|{tag:?}|{rev:?}")) + .cloned() + } + + fn existing_git(&self, dependency: &Dependency) -> Option<&LockedPackage> { + let DependencySource::Git { + url, + branch, + tag, + rev, + } = &dependency.source + else { + return None; + }; + let matches = |package: &&LockedPackage| { + package.import_name() == dependency.import_name() + && package.package_name() == dependency.package_name() + && package.subdir == dependency.subdir + && matches!(&package.source, LockedSource::Git { url: old, branch: b, tag: t, rev: r, .. } if source::identity(old) == source::identity(url) && b == branch && t == tag && r == rev) + }; + if let Some(package) = self + .existing + .package(&dependency.name) + .filter(|p| matches(p)) + { + return Some(package); + } + self.existing.packages.iter().find(matches) } fn resolve_git_commit( @@ -596,6 +745,45 @@ impl<'a> Resolver<'a> { return Ok(commit); } + // Entering a workspace changes binding layout, not an unchanged Git + // selection. Import old managed objects without discarding user edits. + if !destination.exists() { + if let (Some(commit), Some(old)) = (&locked, self.existing_git(dependency)) { + if let LockedSource::Git { resolved, .. } = &old.source { + manifest::validate_package_name(&old.name).map_err(Error::resolution)?; + let legacy = PathBuf::from(".vex/deps").join(&old.name); + let encoded = + PathBuf::from(".vex/deps").join(crate::paths::checkout_name(&old.name)); + if resolved != &legacy && resolved != &encoded { + return Err(Error::resolution( + "invalid historical managed checkout path", + )); + } + let old_path = self.root.join(resolved); + if old_path.exists() { + git::verify_origin(&old_path, url)?; + git::reject_dirty_checkout(&old_path, dependency.import_name())?; + if git::has_commit(&old_path, commit)? { + crate::cache::store(&old_path, url, commit)?; + } + } + } + } + } + if let Some(commit) = &locked { + if (!destination.join(".git").exists() || !git::has_commit(destination, commit)?) + && crate::cache::restore(destination, url, commit)? + { + (self.status)( + "Detail", + format!( + "{}: restored exact commit from shared cache without network", + dependency.name + ), + ); + } + } + if self.options.offline { let commit = locked.ok_or_else(|| { Error::resolution(format!( @@ -676,7 +864,12 @@ impl<'a> Resolver<'a> { git::RepositoryState::Initialized => { "long-path checkout was initialized without objects" } - git::RepositoryState::Existing if self.options.update.updates(&dependency.name) => { + git::RepositoryState::Existing + if (self.updating + && self + .options + .updates_binding(&dependency.name, dependency.import_name())) => + { "explicit update requires refreshed remote refs" } git::RepositoryState::Existing => { @@ -705,10 +898,12 @@ mod tests { #[test] fn path_identity_uses_resolved_location() { let first = RequestKey::Path { + package: "package".into(), resolved: PathBuf::from("/tmp/package"), version: Some("1.0.0".to_string()), }; let second = RequestKey::Path { + package: "package".into(), resolved: PathBuf::from("/tmp/package"), version: Some("1.0.0".to_string()), }; diff --git a/resolver/src/lib.rs b/resolver/src/lib.rs index 21370cc..74ab009 100644 --- a/resolver/src/lib.rs +++ b/resolver/src/lib.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use diagnostic::Error; use std::collections::BTreeSet; @@ -6,12 +10,16 @@ use lockfile::{ }; use manifest::Manifest; +mod activation; +mod cache; mod git; mod graph; mod paths; mod prune; mod transaction; +pub use activation::{root_identity, Request as ActivationRequest, View as RootView}; +pub use cache::prune as prune_cache; pub use prune::{prune, PruneEntry, PruneReport}; pub fn recover_project(guard: &state::Guard, dry_run: bool) -> Result<(), Error> { @@ -23,17 +31,31 @@ pub fn recover_project(guard: &state::Guard, dry_run: bool) -> Result<(), Error> "recovery", "run a normal project command to recover; preserve user edits", ) - }) + })?; + state::edit::recover(guard.root(), dry_run).map_err(Error::environment) } #[derive(Clone, Debug, Default)] pub struct ResolveOptions { + pub requests: Vec, + pub update_bindings: Option>, + pub force_bindings: bool, + pub additional_contexts: Vec, + pub selection: source::graph::Selection, pub dry_run: bool, pub update: UpdatePolicy, pub locked: bool, pub offline: bool, } +impl ResolveOptions { + pub(crate) fn updates_binding(&self, key: &str, alias: &str) -> bool { + self.update_bindings + .as_ref() + .map_or_else(|| self.update.updates(alias), |keys| keys.contains(key)) + } +} + #[derive(Clone, Debug, Default, Eq, PartialEq)] pub enum UpdatePolicy { #[default] @@ -59,25 +81,91 @@ impl UpdatePolicy { #[derive(Debug)] pub struct Resolution { packages: Vec, + union: Vec, + root: source::graph::Root, + roots: Vec, + requests: Vec, + views: Vec, + selection: source::graph::Selection, + selected_edges: Vec, + selected_features: std::collections::BTreeMap>, _guard: state::Guard, } impl Resolution { + pub fn selection(&self) -> &source::graph::Selection { + &self.selection + } + pub fn root_dependencies(&self) -> &[String] { + &self.selected_edges + } + pub fn selected_features( + &self, + ) -> &std::collections::BTreeMap> { + &self.selected_features + } + pub fn union_packages(&self) -> &[LockedPackage] { + &self.union + } + pub fn root_records(&self) -> &[source::graph::Root] { + &self.roots + } + pub fn views(&self) -> &[RootView] { + &self.views + } + pub fn activate(&mut self, selection: &source::graph::Selection) -> Result<(), Error> { + let path = self._guard.root().join(&self.root.manifest); + self.activate_root(&path, selection) + } + pub fn activate_root( + &mut self, + manifest: &std::path::Path, + selection: &source::graph::Selection, + ) -> Result<(), Error> { + let key = manifest_key(manifest)?; + let mut selection = selection.clone(); + if selection.target.is_none() { + selection.target = Some(source::graph::Context::host()); + } + let mut requests = self.requests.clone(); + if !requests + .iter() + .any(|r| r.manifest == key && r.selection.target == selection.target) + { + requests.push(ActivationRequest { + manifest: key.clone(), + selection: selection.clone(), + }); + } + let views = activation::select(&self.roots, &self.union, &requests)?; + let view = views + .iter() + .find(|v| v.root.manifest == key && v.selection.target == selection.target) + .ok_or_else(|| Error::internal("missing selected root activation"))?; + self.root = view.root.clone(); + self.selection = view.selection.clone(); + self.packages = view.packages.clone(); + self.selected_edges = view.dependencies.clone(); + self.selected_features = view.features.clone(); + self.views = views; + Ok(()) + } + pub fn dependency_args(&self) -> Result, Error> { let mut args = vec!["--dep-root=.vex/deps".to_string()]; + let mut aliases = BTreeSet::new(); for package in &self.packages { - let path = match &package.source { - LockedSource::Path { resolved, .. } | LockedSource::Git { resolved, .. } => { - resolved - } - }; + if !aliases.insert(package.import_name()) { + continue; + } + let path = package.directory(); let path = path.to_str().ok_or_else(|| { Error::resolution(format!( "wavec JSON protocol cannot represent non-UTF-8 source path for `{}`", package.name )) })?; - args.push(format!("--dep={}={path}", package.name)); + args.push(format!("--dep={}={path}", package.import_name())); } Ok(args) } @@ -91,6 +179,68 @@ impl Resolution { } } +pub fn manifest_key(path: &std::path::Path) -> Result { + let root = paths::env_root()?; + let path = root.join(path); + paths::portable_path(&paths::relative_to_root(&path, &root)) +} +fn aggregate( + views: &[RootView], +) -> ( + Vec, + Vec, + std::collections::BTreeMap>, +) { + let mut packages: std::collections::BTreeMap = Default::default(); + let mut edges = BTreeSet::new(); + let mut features: std::collections::BTreeMap> = Default::default(); + for view in views { + edges.extend(view.dependencies.iter().cloned()); + for (id, values) in &view.features { + features + .entry(id.clone()) + .or_default() + .extend(values.iter().cloned()); + } + for package in &view.packages { + if let Some(existing) = packages.get_mut(&package.name) { + existing + .dependencies + .extend(package.dependencies.iter().cloned()); + existing.dependencies.sort(); + existing.dependencies.dedup(); + } else { + packages.insert(package.name.clone(), package.clone()); + } + } + } + ( + packages.into_values().collect(), + edges.into_iter().collect(), + features, + ) +} +fn reachable( + roots: &[source::graph::Root], + selected: &BTreeSet, + packages: &[LockedPackage], +) -> BTreeSet { + let packages: std::collections::BTreeMap<_, _> = + packages.iter().map(|p| (&p.name, p)).collect(); + let mut pending: Vec<_> = roots + .iter() + .filter(|r| selected.contains(&r.manifest)) + .flat_map(|r| r.edges.iter().map(|e| e.key.clone())) + .collect(); + let mut seen = BTreeSet::new(); + while let Some(key) = pending.pop() { + if seen.insert(key.clone()) { + pending.extend(packages[&key].dependencies.iter().cloned()); + } + } + seen +} + pub fn resolve( manifest: &Manifest, options: ResolveOptions, @@ -114,6 +264,19 @@ where F: FnMut(&str, String), V: FnMut(&Manifest) -> Result<(), Error>, { + if manifest.scope.is_none() { + source::graph::expand( + &manifest.features, + &manifest + .dependencies + .iter() + .map(|d| d.edge(d.name.clone())) + .collect::>(), + &options.selection.features, + !options.selection.no_default_features, + ) + .map_err(Error::resolution)?; + } if !manifest.dependencies.is_empty() { status( "Resolving", @@ -147,16 +310,35 @@ where "Trace", "project lease: acquired before reading vex.lock".into(), ); - resolve_guarded(manifest, options, status, guard, &mut validate) + resolve_guarded(manifest, options, status, guard, &mut validate, true) } /// Inspect only the existing local graph under a read-only shared lease. pub fn inspect( manifest: &Manifest, locked: bool, + status: impl FnMut(&str, String), +) -> Result { + inspect_selected( + manifest, + locked, + source::graph::Selection::default(), + status, + ) +} + +pub fn inspect_selected( + manifest: &Manifest, + locked: bool, + selection: source::graph::Selection, mut status: impl FnMut(&str, String), ) -> Result { let options = ResolveOptions { + requests: Vec::new(), + update_bindings: None, + force_bindings: false, + selection, + additional_contexts: Vec::new(), dry_run: true, offline: true, locked, @@ -172,7 +354,7 @@ pub fn inspect( "Trace", "project lease: acquired before reading vex.lock".into(), ); - resolve_guarded(manifest, options, status, guard, &mut |_| Ok(())).map_err(|e| { + resolve_guarded(manifest, options, status, guard, &mut |_| Ok(()), true).map_err(|e| { Error::new( e.category, format!("{e}\nhelp: run `vex fetch` to prepare the local graph"), @@ -211,12 +393,20 @@ fn report_policy(options: &ResolveOptions, status: &mut impl FnMut(&str, String) fn resolve_guarded( manifest: &Manifest, - options: ResolveOptions, + mut options: ResolveOptions, mut status: F, guard: state::Guard, validate: &mut dyn FnMut(&Manifest) -> Result<(), Error>, + recover: bool, ) -> Result { - recover_project(&guard, options.dry_run)?; + if recover { + recover_project(&guard, options.dry_run)?; + } + // Official edits only change dependency spans. Reload them after acquiring + // the lease so no command uses an old manifest with a newly published lock. + let mut refreshed = Manifest::load_from(&manifest.source_path)?; + refreshed.scope = manifest.scope.clone(); + let manifest = &refreshed; let existing = read_lockfile()?; let missing_lockfile = existing.is_none(); status( @@ -245,7 +435,7 @@ fn resolve_guarded( "`{LOCKFILE_NAME}` is required by `--locked`\nhelp: run `vex fetch` and commit `{LOCKFILE_NAME}`" )) })?; - if lockfile.version != 2 && lockfile.version != LOCKFILE_VERSION { + if lockfile.version != 2 && lockfile.version != 3 && lockfile.version != LOCKFILE_VERSION { return Err(Error::resolution(format!( "`{LOCKFILE_NAME}` version {} cannot be used with `--locked`; expected version {LOCKFILE_VERSION}\nhelp: run `vex fetch` to regenerate the lockfile", lockfile.version @@ -264,14 +454,101 @@ fn resolve_guarded( let dry_run = options.dry_run; paths::validate_managed_root(&root, &dep_root)?; - if let UpdatePolicy::UpdateSelected(selected) = &options.update { + let mut root_manifests = if let Some(scope) = &manifest.scope { + manifest::workspace::load_context(scope)? + } else { + vec![manifest.clone()] + }; + options.force_bindings = manifest.scope.is_some(); + let selected_paths: BTreeSet<_> = if let Some(scope) = &manifest.scope { + scope + .selected + .iter() + .map(|p| manifest_key(p)) + .collect::>()? + } else { + BTreeSet::from([manifest_key(&manifest.source_path)?]) + }; + // Resolve selected roots first: an update of a shared binding is then seen + // by other roots, while unrelated pinned bindings remain unchanged. + let root_keys = root_manifests + .iter() + .map(|m| Ok((m.source_path.clone(), manifest_key(&m.source_path)?))) + .collect::, Error>>()?; + root_manifests.sort_by_key(|m| { + ( + !selected_paths.contains(&root_keys[&m.source_path]), + m.name.clone(), + ) + }); + let mut requests = options.requests.clone(); + if requests.is_empty() { + for member in root_manifests + .iter() + .filter(|m| selected_paths.contains(&manifest_key(&m.source_path).unwrap())) + { + let mut selection = options.selection.clone(); + if selection.target.is_none() { + selection.target = Some(match &member.build_target { + Some(t) => source::graph::Context::new(t).map_err(Error::resolution)?, + None => source::graph::Context::host(), + }); + } + requests.push(ActivationRequest { + manifest: manifest_key(&member.source_path)?, + selection: selection.clone(), + }); + for context in &options.additional_contexts { + selection.target = Some(context.clone()); + requests.push(ActivationRequest { + manifest: manifest_key(&member.source_path)?, + selection: selection.clone(), + }); + } + } + } + let provisional_roots = root_manifests + .iter() + .map(|m| { + Ok(source::graph::Root { + manifest: manifest_key(&m.source_path)?, + name: m.name.clone(), + version: m.version.clone(), + edges: m + .dependencies + .iter() + .map(|d| d.edge(d.name.clone())) + .collect(), + features: m.features.clone(), + }) + }) + .collect::, Error>>()?; + let qualified = activation::qualify(&provisional_roots, &requests)?; + for request in &qualified { + let candidate = root_manifests + .iter() + .find(|m| manifest_key(&m.source_path).as_deref() == Ok(request.manifest.as_str())) + .unwrap(); + source::graph::expand( + &candidate.features, + &candidate + .dependencies + .iter() + .map(|d| d.edge(d.name.clone())) + .collect::>(), + &request.selection.features, + !request.selection.no_default_features, + ) + .map_err(Error::resolution)?; + validate(candidate)?; + } + if let UpdatePolicy::UpdateSelected(wanted) = &options.update { + let mut local_options = options.clone(); + local_options.dry_run = true; + local_options.offline = true; + local_options.locked = false; let mut preflight = graph::Resolver::new( - ResolveOptions { - dry_run: true, - update: UpdatePolicy::UpdateSelected(selected.clone()), - locked: false, - offline: true, - }, + local_options, root.clone(), dep_root.clone(), None, @@ -279,12 +556,34 @@ fn resolve_guarded( root_manifest.clone(), &existing, &mut status, - validate, ); - // Local discovery must reuse pinned sources even for selected names. preflight.local_preflight(); - preflight.resolve_manifest_dependencies(manifest).map_err(|e| Error::new(e.category, format!("cannot validate update names from the local current graph: {e}\nhelp: run `vex fetch` first")))?; - preflight.validate_selected_packages()?; + let mut roots = Vec::new(); + for member in &root_manifests { + preflight.resolve_manifest_dependencies(member).map_err(|e| Error::new(e.category, format!("cannot validate update names from the local current graph: {e}\nhelp: run `vex fetch` first")))?; + roots.push(preflight.root_record(member)?); + } + let (packages, _) = preflight.into_packages(); + let eligible = reachable(&roots, &selected_paths, &packages); + let git: Vec<_> = packages + .iter() + .filter(|p| eligible.contains(&p.name) && matches!(p.source, LockedSource::Git { .. })) + .collect(); + let available: BTreeSet<_> = git.iter().map(|p| p.import_name()).collect(); + for name in wanted { + if !git + .iter() + .any(|p| p.import_name() == name || p.name == *name) + { + return Err(Error::resolution(format!("cannot update package `{name}`: not a Git dependency in the selected current graph\nhelp: available Git packages: {}\nhelp: run `vex update ...` using an available dependency alias", available.iter().copied().collect::>().join(", ")))); + } + } + options.update_bindings = Some( + git.into_iter() + .filter(|p| wanted.contains(p.import_name()) || wanted.contains(&p.name)) + .map(|p| p.name.clone()) + .collect(), + ); } let transaction = if dry_run { None @@ -295,25 +594,40 @@ fn resolve_guarded( .as_ref() .map(|t| t.stage.clone()) .unwrap_or(dep_root); - let packages = { + let ((packages, manifests), roots) = { let mut resolver = graph::Resolver::new( options, - root, + root.clone(), physical_deps, transaction.as_ref(), manifest.name.clone(), root_manifest, &existing, &mut status, - validate, ); - resolver.resolve_manifest_dependencies(manifest)?; - resolver.validate_selected_packages()?; - resolver.into_packages() + let mut roots = Vec::new(); + for member in &root_manifests { + resolver.set_updating(selected_paths.contains(&manifest_key(&member.source_path)?)); + resolver.resolve_manifest_dependencies(member)?; + roots.push(resolver.root_record(member)?); + } + (resolver.into_packages(), roots) }; + let requires_v4 = manifest.scope.is_some() + || manifest.format >= 4 + || packages + .iter() + .any(|p| p.id.is_some() || p.subdir.is_some()); let resolved = Lockfile { - version: if (locked || dry_run) && existing.version == 2 { - 2 + roots: if requires_v4 { + roots.clone() + } else { + Vec::new() + }, + version: if !requires_v4 && (locked || dry_run) && matches!(existing.version, 2 | 3) { + existing.version + } else if !requires_v4 && (missing_lockfile || existing.version < 4) { + 3 } else { LOCKFILE_VERSION }, @@ -334,6 +648,24 @@ fn resolve_guarded( } } + let views = activation::select(&roots, &resolved.packages, &requests)?; + let (active_packages, selected_edges, selected_features) = aggregate(&views); + let validate_keys = active_packages + .iter() + .map(|p| p.name.clone()) + .collect::>(); + for key in validate_keys { + let candidate = &manifests[&key]; + validate(candidate).map_err(|error| { + error + .with_field("package", &candidate.name) + .with_field("manifest", candidate.source_path.display()) + .context(format!( + "failed to validate selected dependency `{}`", + candidate.name + )) + })?; + } let needs_lockfile = missing_lockfile || resolved != existing; let lockfile_decision = if missing_lockfile { "lockfile: write required because vex.lock is missing".to_owned() @@ -375,6 +707,10 @@ fn resolve_guarded( } if let Some(transaction) = transaction { + if needs_lockfile { + state::edit::expect_lock(guard.root(), lockfile::encode(resolved.clone())) + .map_err(Error::environment)?; + } status( "Trace", format!( @@ -387,7 +723,81 @@ fn resolve_guarded( } Ok(Resolution { - packages: resolved.packages, + packages: active_packages, + union: resolved.packages, + root: views[0].root.clone(), + selection: views[0].selection.clone(), + roots, + requests, + views, + selected_edges, + selected_features, _guard: guard, }) } + +/// Edit a direct dependency and resolve the pair under one exclusive lease. +pub fn edit_manifest( + manifest: &Manifest, + offline: bool, + transform: impl FnOnce(&Manifest, &str) -> Result, + mut status: impl FnMut(&str, String), +) -> Result<(), Error> { + let guard = state::Guard::acquire(false, &mut status).map_err(Error::environment)?; + recover_project(&guard, false)?; + let mut current = Manifest::load_from(&manifest.source_path)?; + current.scope = manifest.scope.clone(); + let raw = wson::read_document(¤t.source_path)?; + let next = transform(¤t, &raw)?; + // Validate before starting the durable edit. + manifest::decode(&next, current.source_path.clone()).map_err(Error::resolution)?; + state::edit::begin(&guard, ¤t.source_path, next).map_err(Error::environment)?; + #[cfg(debug_assertions)] + if std::env::var_os("VEX_TEST_EDIT_CRASH_MANIFEST").is_some() { + std::process::exit(99); + } + match resolve_guarded( + ¤t, + ResolveOptions { + offline, + ..Default::default() + }, + &mut status, + guard, + &mut |_| Ok(()), + false, + ) { + Ok(resolution) => { + #[cfg(debug_assertions)] + if std::env::var_os("VEX_TEST_EDIT_CRASH_LOCK").is_some() { + std::process::exit(99); + } + state::edit::commit(&resolution._guard).map_err(Error::environment) + } + Err(error) => { + let guard = state::Guard::acquire(false, &mut status).map_err(Error::environment)?; + recover_project(&guard, false)?; + Err(error) + } + } +} + +/// The same sanitized Git environment is used by explicit project creation. +pub fn project_git_command() -> std::process::Command { + git::command() +} +// Keep persisted IDs/checksums as zero-padded lowercase SHA-256 hex. The +// digest output type no longer implements LowerHex in sha2 0.11. +fn hex_digest(bytes: impl AsRef<[u8]>) -> String { + const DIGITS: &[u8; 16] = b"0123456789abcdef"; + bytes + .as_ref() + .iter() + .flat_map(|&byte| { + [ + char::from(DIGITS[(byte >> 4) as usize]), + char::from(DIGITS[(byte & 15) as usize]), + ] + }) + .collect() +} diff --git a/resolver/src/paths.rs b/resolver/src/paths.rs index f33501e..354969f 100644 --- a/resolver/src/paths.rs +++ b/resolver/src/paths.rs @@ -1,10 +1,17 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use diagnostic::Error; use std::borrow::Cow; /// Filesystem identity is independent of platform case folding and reserved /// device names. The full SHA-256 also bounds directory component length. pub(crate) fn checkout_name(package: &str) -> String { use sha2::{Digest, Sha256}; - format!("pkg_{:x}", Sha256::digest(package.as_bytes())) + format!( + "pkg_{}", + crate::hex_digest(Sha256::digest(package.as_bytes())) + ) } #[cfg(all(test, unix))] @@ -34,7 +41,11 @@ pub(crate) fn resolve_path(path: &str, manifest_path: &Path) -> PathBuf { pub(crate) fn relative_to_root(path: &Path, root: &Path) -> PathBuf { if let Ok(relative) = path.strip_prefix(root) { - return relative.to_path_buf(); + return if relative.as_os_str().is_empty() { + PathBuf::from(".") + } else { + relative.to_path_buf() + }; } let path_components = path.components().collect::>(); @@ -134,6 +145,20 @@ pub(crate) fn git_cli_path(path: &Path) -> Cow<'_, Path> { } } +pub(crate) fn portable_path(path: &Path) -> Result { + let value = path + .to_str() + .ok_or_else(|| Error::resolution("dependency graph cannot represent a non-UTF-8 path"))?; + #[cfg(windows)] + { + Ok(value.replace('\\', "/")) + } + #[cfg(not(windows))] + { + Ok(value.to_owned()) + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/resolver/src/prune.rs b/resolver/src/prune.rs index bab7e89..a2ca4b9 100644 --- a/resolver/src/prune.rs +++ b/resolver/src/prune.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use diagnostic::{Category, Error}; use lockfile::LockedSource; use manifest::Manifest; @@ -39,6 +43,11 @@ pub fn prune( let resolution = resolve_guarded( manifest, ResolveOptions { + requests: Vec::new(), + update_bindings: None, + force_bindings: false, + additional_contexts: Vec::new(), + selection: Default::default(), dry_run: true, locked: true, offline: true, @@ -47,12 +56,13 @@ pub fn prune( |_, _| {}, guard, &mut |_| Ok(()), + true, ) .map_err(|error| { error.context("cannot prune before the local graph is prepared; run `vex fetch`") })?; let used: Vec<_> = resolution - .packages() + .union_packages() .iter() .map(|package| { let (LockedSource::Path { resolved, .. } | LockedSource::Git { resolved, .. }) = @@ -351,7 +361,7 @@ fn snapshot_directory( } files.insert( name, - json!({"kind":"file", "mode":mode, "sha256":format!("{:x}", digest.finalize())}), + json!({"kind":"file", "mode":mode, "sha256":crate::hex_digest(digest.finalize())}), ); } else { return Err("checkout contains an unsupported filesystem entry".into()); diff --git a/resolver/src/transaction.rs b/resolver/src/transaction.rs index 4ef75dd..94132c7 100644 --- a/resolver/src/transaction.rs +++ b/resolver/src/transaction.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use serde_json::{json, Value}; use std::cell::RefCell; use std::collections::BTreeSet; @@ -407,7 +411,7 @@ fn copy_tree(from: &Path, to: &Path) -> Result<(), String> { } Ok(()) } -fn sync_tree(path: &Path) -> Result<(), String> { +pub(crate) fn sync_tree(path: &Path) -> Result<(), String> { let meta = fs::symlink_metadata(path).map_err(err)?; if meta.file_type().is_symlink() { return Ok(()); @@ -449,7 +453,7 @@ fn sync_file(path: &Path) -> Result<(), String> { fn fingerprint(value: &str) -> String { use sha2::{Digest, Sha256}; - format!("{:x}", Sha256::digest(value.as_bytes())) + crate::hex_digest(Sha256::digest(value.as_bytes())) } #[cfg(test)] diff --git a/rust-toolchain.toml b/rust-toolchain.toml index c2294d8..10bd71f 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,3 +1,7 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 [toolchain] channel = "1.96.0" profile = "minimal" diff --git a/source/Cargo.toml b/source/Cargo.toml index bfcaacc..b797c49 100644 --- a/source/Cargo.toml +++ b/source/Cargo.toml @@ -1,3 +1,7 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 [package] name = "source" version.workspace = true @@ -10,3 +14,4 @@ publish = false [dependencies] percent-encoding = "2.3" url = "2.5.8" +serde = { version = "1", features = ["derive"] } diff --git a/source/build.rs b/source/build.rs new file mode 100644 index 0000000..d138b7c --- /dev/null +++ b/source/build.rs @@ -0,0 +1,10 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +fn main() { + println!( + "cargo:rustc-env=VEX_HOST_TARGET={}", + std::env::var("TARGET").unwrap() + ); +} diff --git a/source/src/graph.rs b/source/src/graph.rs new file mode 100644 index 0000000..c8bde63 --- /dev/null +++ b/source/src/graph.rs @@ -0,0 +1,323 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +//! Stable dependency activation concepts shared by manifests and locks. +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, BTreeSet}; + +#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Predicate { + pub triple: Option, + pub os: Option, + pub arch: Option, + pub mode: Option, +} +impl Predicate { + pub fn validate(&self) -> Result<(), String> { + if self == &Self::default() { + return Err("target predicate must contain a constraint".into()); + } + if let Some(triple) = &self.triple { + Context::new(triple)?; + } + for (label, value, allowed) in [ + ( + "os", + &self.os, + &[ + "linux", "macos", "windows", "freebsd", "wasi", "none", "unknown", + ][..], + ), + ( + "arch", + &self.arch, + &[ + "x86_64", + "aarch64", + "riscv64", + "loongarch64", + "wasm32", + "wasm64", + ][..], + ), + ( + "mode", + &self.mode, + &["hosted", "freestanding", "wasi", "bare_wasm"][..], + ), + ] { + if value + .as_ref() + .is_some_and(|value| !allowed.contains(&value.as_str())) + { + return Err(format!("unsupported target predicate {label}")); + } + } + if let Some(triple) = &self.triple { + let context = Context::new(triple)?; + if self.os.as_ref().is_some_and(|os| *os != context.os) + || self.arch.as_ref().is_some_and(|arch| *arch != context.arch) + { + return Err("target predicate contradicts its exact triple".into()); + } + } + Ok(()) + } + pub fn matches(&self, context: &Context) -> bool { + [&self.triple, &self.os, &self.arch, &self.mode] + .into_iter() + .zip([&context.triple, &context.os, &context.arch, &context.mode]) + .all(|(required, found)| required.as_ref().is_none_or(|required| required == found)) + } +} +#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)] +pub struct Context { + pub triple: String, + pub os: String, + pub arch: String, + pub mode: String, +} +impl Context { + pub fn new(triple: &str) -> Result { + let parts: Vec<_> = triple.split('-').collect(); + if parts.len() < 3 + || parts.iter().any(|p| p.is_empty()) + || !triple + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.')) + { + return Err("target must be a complete portable triple".into()); + } + let os = if parts.contains(&"windows") { + "windows" + } else if parts.contains(&"darwin") { + "macos" + } else if parts.contains(&"linux") { + "linux" + } else if parts.contains(&"freebsd") { + "freebsd" + } else if parts.iter().any(|p| p.starts_with("wasi")) { + "wasi" + } else if parts.contains(&"none") { + "none" + } else { + "unknown" + }; + let mode = if os == "wasi" { + "wasi" + } else if parts[0].starts_with("wasm") { + "bare_wasm" + } else if os == "none" { + "freestanding" + } else { + "hosted" + }; + Ok(Self { + triple: triple.into(), + os: os.into(), + arch: parts[0].into(), + mode: mode.into(), + }) + } + pub fn host() -> Self { + Self::new(&env!("VEX_HOST_TARGET").replacen("riscv64gc-", "riscv64-", 1)) + .expect("Rust target triple") + } +} +#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)] +pub struct Selection { + pub include_tests: bool, + pub target: Option, + pub features: BTreeSet, + pub no_default_features: bool, +} +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Edge { + #[serde(default, skip_serializing_if = "is_false")] + pub development: bool, + pub key: String, + pub alias: String, + pub optional: bool, + pub default_features: bool, + pub features: Vec, + pub target: Option, +} +impl Edge { + pub fn unconditional(key: String, alias: String) -> Self { + Self { + development: false, + key, + alias, + optional: false, + default_features: true, + features: Vec::new(), + target: None, + } + } +} +pub type Features = BTreeMap>; +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Root { + pub manifest: String, + pub name: String, + pub version: String, + pub edges: Vec, + pub features: Features, +} + +pub fn feature_name(name: &str) -> bool { + let mut bytes = name.bytes(); + bytes + .next() + .is_some_and(|b| b.is_ascii_alphabetic() || b == b'_') + && bytes.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-')) +} +/// Additive closure: local features, dep:alias, and alias/feature. Cyclic local +/// groups are finite unions; dependency cycles are rejected separately. +pub struct Expanded { + pub enabled: BTreeSet, + pub forwarded: BTreeMap>, + pub features: BTreeSet, +} + +pub fn expand( + features: &Features, + edges: &[Edge], + requested: &BTreeSet, + defaults: bool, +) -> Result { + let mut queue: Vec<_> = requested.iter().cloned().collect(); + if defaults && features.contains_key("default") { + queue.push("default".into()); + } + let mut visited = BTreeSet::new(); + let mut enabled = BTreeSet::new(); + let mut forwarded: BTreeMap> = BTreeMap::new(); + while let Some(value) = queue.pop() { + if !visited.insert(value.clone()) { + continue; + } + if let Some(alias) = value.strip_prefix("dep:") { + if !edges.iter().any(|e| e.alias == alias) { + return Err(format!("unknown feature dependency `{alias}`")); + } + enabled.insert(alias.to_owned()); + } else if let Some((alias, feature)) = value.split_once('/') { + if !feature_name(feature) || !edges.iter().any(|e| e.alias == alias) { + return Err(format!("invalid dependency feature `{value}`")); + } + enabled.insert(alias.to_owned()); + forwarded + .entry(alias.into()) + .or_default() + .insert(feature.into()); + } else if let Some(members) = features.get(&value) { + queue.extend(members.iter().cloned()); + } else if edges.iter().any(|e| e.optional && e.alias == value) { + enabled.insert(value); + } else { + return Err(format!("unknown package feature `{value}`")); + } + } + let active = visited + .into_iter() + .filter(|name| { + features.contains_key(name) + || edges + .iter() + .any(|edge| edge.optional && edge.alias == *name) + }) + .collect(); + Ok(Expanded { + enabled, + forwarded, + features: active, + }) +} + +pub fn validate(features: &Features, edges: &[Edge]) -> Result<(), String> { + for (name, values) in features { + if !feature_name(name) { + return Err(format!("invalid feature name `{name}`")); + } + if values.iter().collect::>().len() != values.len() { + return Err(format!("duplicate member of feature `{name}`")); + } + for value in values { + if let Some(alias) = value.strip_prefix("dep:") { + if !edges.iter().any(|e| e.alias == alias) { + return Err(format!("unknown feature dependency `{alias}`")); + } + } else if let Some((alias, feature)) = value.split_once('/') { + if !feature_name(feature) || !edges.iter().any(|e| e.alias == alias) { + return Err(format!("invalid dependency feature `{value}`")); + } + } else if !features.contains_key(value) + && !edges.iter().any(|e| e.optional && e.alias == *value) + { + return Err(format!("unknown package feature `{value}`")); + } + } + } + for edge in edges { + if let Some(target) = &edge.target { + target.validate()?; + } + if !edge.features.iter().all(|feature| feature_name(feature)) + || edge.features.iter().collect::>().len() != edge.features.len() + { + return Err("invalid or duplicate dependency feature".into()); + } + } + Ok(()) +} + +fn is_false(value: &bool) -> bool { + !*value +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn predicates_are_conjunctions_and_reject_contradictory_triples() { + let linux = Context::new("x86_64-unknown-linux-gnu").unwrap(); + let predicate = Predicate { + os: Some("linux".into()), + arch: Some("x86_64".into()), + ..Default::default() + }; + assert!(predicate.matches(&linux)); + assert!(!predicate.matches(&Context::new("aarch64-unknown-linux-gnu").unwrap())); + assert!(Predicate { + triple: Some(linux.triple), + os: Some("windows".into()), + ..Default::default() + } + .validate() + .is_err()); + assert!(Predicate::default().validate().is_err()); + } + #[test] + fn additive_local_cycles_terminate_and_defaults_can_be_disabled() { + let features = Features::from([ + ("default".into(), vec!["first".into()]), + ("first".into(), vec!["second".into()]), + ("second".into(), vec!["first".into()]), + ]); + validate(&features, &[]).unwrap(); + let result = expand(&features, &[], &BTreeSet::new(), true).unwrap(); + assert_eq!(result.features.len(), 3); + assert!(expand(&features, &[], &BTreeSet::new(), false) + .unwrap() + .features + .is_empty()); + for invalid in ["", "-bad", "bad/name", "bad name", "β"] { + assert!(!feature_name(invalid)); + } + } +} diff --git a/source/src/lib.rs b/source/src/lib.rs index 46a9821..dcb054a 100644 --- a/source/src/lib.rs +++ b/source/src/lib.rs @@ -1,5 +1,10 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 //! Git source identity and credential-safe rendering. Transport credentials are //! ephemeral; source declarations remain in user-controlled manifests only. +pub mod graph; use std::sync::{Mutex, OnceLock}; use url::Url; @@ -143,6 +148,23 @@ pub fn redact(message: &str) -> String { rendered } +/// Portable repository-relative package selector. Dot/empty components and +/// platform prefixes are rejected before touching a repository. +pub fn validate_subdir(value: &str) -> Result<(), String> { + if value.is_empty() + || value.contains(['\\', ':', '\0']) + || value + .split('/') + .any(|part| part.is_empty() || part == "." || part == "..") + { + return Err( + "subdir must be a nonempty portable relative path without dot or empty components" + .into(), + ); + } + Ok(()) +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/cli.rs b/src/cli.rs index 3238db2..081d262 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use colorex::Colorize; use std::io::IsTerminal; @@ -43,7 +47,50 @@ fn run_reported() -> Result { runtime.extend(raw); break; } - if arg == "--quiet" || arg == "-q" { + if arg == "-p" + || arg == "--package" + || arg.to_str().is_some_and(|s| s.starts_with("--package=")) + { + let inline = arg + .to_str() + .and_then(|s| s.strip_prefix("--package=")) + .map(str::to_owned); + let value = inline + .or_else(|| raw.next().and_then(|s| s.into_string().ok())) + .filter(|s| !s.is_empty() && !s.starts_with('-')) + .ok_or_else(|| Error::usage("--package requires a package name"))?; + selection.packages.push(value); + } else if arg == "--workspace" { + if selection.all_packages { + return Err(Error::usage("--workspace may only be specified once")); + } + selection.all_packages = true; + } else if arg == "--features" || arg.to_str().is_some_and(|s| s.starts_with("--features=")) + { + let inline = arg + .to_str() + .and_then(|s| s.strip_prefix("--features=")) + .map(str::to_owned); + let value = inline + .or_else(|| raw.next().and_then(|s| s.into_string().ok())) + .ok_or_else(|| Error::usage("--features requires a comma-separated list"))?; + if value.starts_with('-') || value.split(',').any(str::is_empty) { + return Err(Error::usage("empty feature name")); + } + selection + .graph + .features + .extend(value.split(',').map(str::to_owned)); + } else if arg == "--include-tests" { + selection.graph.include_tests = true; + } else if arg == "--no-default-features" { + if selection.graph.no_default_features { + return Err(Error::usage( + "--no-default-features may only be specified once", + )); + } + selection.graph.no_default_features = true; + } else if arg == "--quiet" || arg == "-q" { quiet = true; } else if arg == "--verbose" || arg == "-v" || arg == "-vv" { verbosity = (verbosity + if arg == "-vv" { 2 } else { 1 }).min(2); @@ -80,13 +127,94 @@ fn run_reported() -> Result { )); } crate::ui::configure(quiet, verbosity); + if selection.all_packages && !selection.packages.is_empty() { + return Err(Error::usage( + "--workspace cannot be combined with --package", + )); + } + if (selection.all_packages || !selection.packages.is_empty()) + && !args.first().is_some_and(|s| { + matches!( + s.as_str(), + "test" + | "add" + | "remove" + | "build" + | "check" + | "run" + | "fetch" + | "update" + | "tree" + | "metadata" + | "info" + | "doctor" + ) + }) + { + return Err(Error::usage( + "package selection requires a workspace project command", + )); + } + if selection.graph.include_tests + && !args + .first() + .is_some_and(|s| matches!(s.as_str(), "fetch" | "update" | "tree" | "metadata")) + { + return Err(Error::usage("--include-tests selects a dependency query graph; vex test includes tests automatically")); + } + let graph_command = args.first().is_some_and(|s| { + matches!( + s.as_str(), + "test" | "build" | "check" | "run" | "fetch" | "update" | "tree" | "metadata" + ) + }); + if !graph_command + && (!selection.graph.features.is_empty() || selection.graph.no_default_features) + { + return Err(Error::usage( + "feature selection requires a build or dependency graph command", + )); + } + if args + .first() + .is_some_and(|s| matches!(s.as_str(), "fetch" | "update" | "tree" | "metadata")) + { + let mut position = 1; + while position < args.len() { + let value = if args[position] == "--target" { + if position + 1 >= args.len() { + return Err(Error::usage("--target requires a triple")); + } + let value = args.remove(position + 1); + args.remove(position); + Some(value) + } else if let Some(value) = args[position].strip_prefix("--target=") { + let value = value.to_owned(); + args.remove(position); + Some(value) + } else { + None + }; + if let Some(value) = value { + if selection.graph.target.is_some() { + return Err(Error::usage("--target may only be specified once")); + } + selection.graph.target = + Some(source::graph::Context::new(&value).map_err(Error::usage)?); + } else { + position += 1; + } + } + } let command = args.first().map(String::as_str).unwrap_or("help"); - let dry_run = matches!(command, "build" | "check" | "run" | "clean" | "prune") - && args - .iter() - .skip(1) - .take_while(|s| s.as_str() != "--") - .any(|s| s == "--dry-run"); + let dry_run = matches!( + command, + "test" | "build" | "check" | "run" | "clean" | "prune" | "cache" + ) && args + .iter() + .skip(1) + .take_while(|s| s.as_str() != "--") + .any(|s| s == "--dry-run"); let mut messages = Messages::open(path.as_deref(), command, dry_run)?; messages.emit(json!({"event":"started"}))?; let result = process::install_handlers() @@ -168,7 +296,10 @@ fn dispatch( if selection.manifest_path.is_some() && !matches!( args[0].as_str(), - "build" + "test" + | "add" + | "remove" + | "build" | "run" | "check" | "fetch" @@ -185,8 +316,23 @@ fn dispatch( "--manifest-path is only valid for project commands", )); } + if args + .iter() + .skip(1) + .any(|arg| matches!(arg.as_str(), "-h" | "--help")) + && crate::command_spec::help(Some(&args[0]))? + { + return Ok(Outcome::success()); + } match args[0].as_str() { + "new" => crate::commands::new::new(&args[1..]).map(|()| Outcome::success()), + "add" | "remove" => crate::commands::edit::edit(args[0] == "remove", &args[1..], selection) + .map(|()| Outcome::success()), + "completions" => crate::command_spec::completions(&args[1..]).map(|()| Outcome::success()), + "manpage" => crate::command_spec::manpage(&args[1..]).map(|()| Outcome::success()), + "cache" => crate::commands::cache::cache(&args[1..]).map(|()| Outcome::success()), "init" => init(&args[1..]).map(|()| Outcome::success()), + "test" => build(BuildMode::Test, &args[1..], runtime, selection, messages), "build" => build(BuildMode::Build, &args[1..], runtime, selection, messages), "run" => run_package(&args[1..], runtime, selection, messages), "check" => check(&args[1..], runtime, selection, messages), @@ -234,41 +380,5 @@ fn print_version() -> Result<(), diagnostic::Error> { } fn print_help() -> Result<(), diagnostic::Error> { - diagnostic::outln!("Vex - Wave package manager"); - diagnostic::outln!(); - diagnostic::outln!("Usage:"); - diagnostic::outln!( - " vex [-q|--quiet] [-v|--verbose] [--message-file ] [--manifest-path ] [options]" - ); - diagnostic::outln!(" vex init [--lib]"); - diagnostic::outln!( - " vex build [--lib] [--bin ] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline]" - ); - diagnostic::outln!( - " vex run [--bin ] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline] [-- ]" - ); - diagnostic::outln!( - " vex check [--lib] [--bin ] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline]" - ); - diagnostic::outln!(" vex fetch [--locked] [--offline]"); - diagnostic::outln!(" vex update [...]"); - diagnostic::outln!(" vex info"); - diagnostic::outln!( - " vex metadata [--format=json] [--format-version <1|2>] [--locked] [--offline]" - ); - diagnostic::outln!(" vex tree [--invert ] [--depth ] [--locked] [--offline]"); - diagnostic::outln!(" vex clean [--dry-run]"); - diagnostic::outln!(" vex prune [--apply] [--dry-run]"); - diagnostic::outln!(" vex doctor [--format=json] [--target ]"); - diagnostic::outln!(" vex setup wavec [--version ] [--script-fallback]"); - diagnostic::outln!(" vex --version"); - diagnostic::outln!(); - diagnostic::outln!("Output:"); - diagnostic::outln!( - " -q, --quiet Hide Vex progress; keep results, warnings, errors, and program output" - ); - diagnostic::outln!( - " -v, --verbose Show decisions; repeat (-vv) for redacted diagnostic detail" - ); - Ok(()) + crate::command_spec::help(None).map(|_| ()) } diff --git a/src/command_spec.rs b/src/command_spec.rs new file mode 100644 index 0000000..fffea1c --- /dev/null +++ b/src/command_spec.rs @@ -0,0 +1,85 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +//! One command model drives help and installable offline CLI tooling. +use diagnostic::Error; +use serde_json::Value; +fn spec() -> Value { + serde_json::from_str(include_str!("../tools/command-spec.json")) + .expect("validated embedded command specification") +} +pub fn help(command: Option<&str>) -> Result { + let spec = spec(); + if let Some(name) = command { + if let Some(entry) = spec["commands"] + .as_array() + .unwrap() + .iter() + .find(|c| c["name"] == name) + { + diagnostic::outln!( + "usage: vex {}\n\n{}", + entry["usage"].as_str().unwrap(), + entry["description"].as_str().unwrap() + ); + return Ok(true); + } + return Ok(false); + } + diagnostic::outln!( + "Vex - Wave package manager\n\nUsage:\n vex {} [options]", + spec["globals"].as_str().unwrap() + ); + for entry in spec["commands"].as_array().unwrap() { + diagnostic::outln!(" vex {}", entry["usage"].as_str().unwrap()); + } + diagnostic::outln!(" vex --version\n\nOutput:\n -q, --quiet Hide Vex progress; keep results, warnings, errors, and program output\n -v, --verbose Show decisions; repeat (-vv) for redacted diagnostic detail"); + Ok(true) +} +pub fn completions(args: &[String]) -> Result<(), Error> { + let [shell] = args else { + return Err(Error::usage( + "usage: vex completions ", + )); + }; + let spec = spec(); + let commands = spec["commands"].as_array().unwrap(); + let mut words = std::collections::BTreeSet::new(); + for text in commands + .iter() + .filter_map(|c| c["usage"].as_str()) + .chain(spec["globals"].as_str()) + { + for word in text.split(|c: char| c.is_whitespace() || "[]()|".contains(c)) { + if word.starts_with('-') || commands.iter().any(|c| c["name"] == word) { + words.insert(word); + } + } + } + let list = words.iter().copied().collect::>().join(" "); + match shell.as_str() { + "bash"=>diagnostic::outln!("# Generated from command-spec.json\n_vex() {{ COMPREPLY=( $(compgen -W '{list}' -- \"${{COMP_WORDS[COMP_CWORD]}}\") ); }}\ncomplete -F _vex vex"), + "zsh"=>diagnostic::outln!("#compdef vex\n# Generated from command-spec.json\n_arguments '*:command or option:({list})'"), + "fish"=> {diagnostic::outln!("# Generated from command-spec.json"); for word in words { if let Some(long)=word.strip_prefix("--").filter(|long| !long.is_empty()) {diagnostic::outln!("complete -c vex -l {long}");} else if !word.starts_with('-') {diagnostic::outln!("complete -c vex -f -a {word}");} }}, + "powershell"=>diagnostic::outln!("# Generated from command-spec.json\nRegister-ArgumentCompleter -Native -CommandName vex -ScriptBlock {{ param($wordToComplete, $commandAst, $cursorPosition)\n '{list}'.Split(' ') | Where-Object {{ $_.StartsWith($wordToComplete) }} | ForEach-Object {{ [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }}\n}}"), + _=>return Err(Error::usage("unsupported completion shell; choose bash, zsh, fish, or powershell")), + } + Ok(()) +} +pub fn manpage(args: &[String]) -> Result<(), Error> { + if !args.is_empty() { + return Err(Error::usage("usage: vex manpage")); + } + let spec = spec(); + diagnostic::outln!(".TH VEX 1\n.SH NAME\nvex \\- Wave package manager\n.SH SYNOPSIS\n.B vex\n{} [options]\n.SH COMMANDS",spec["globals"].as_str().unwrap()); + for entry in spec["commands"].as_array().unwrap() { + diagnostic::outln!( + ".TP\n.B vex {}\n{}", + entry["usage"].as_str().unwrap().replace('-', "\\-"), + entry["description"].as_str().unwrap() + ); + } + diagnostic::outln!(".SH FILES\nvex.ws, vex.lock\n.SH ENVIRONMENT\nVEX_WAVEC, VEX_CACHE_HOME\n.SH EXIT STATUS\n0 success; 1 internal error; 2 usage; 3 resolution; 4 compiler; 5 environment; 124 timeout; 130 cancellation. Program exit codes are preserved."); + Ok(()) +} diff --git a/src/commands/build.rs b/src/commands/build.rs index 45eefaf..f8d75f4 100644 --- a/src/commands/build.rs +++ b/src/commands/build.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use crate::{messages::Messages, outcome::Outcome}; use diagnostic::Error; use std::path::{Path, PathBuf}; @@ -15,15 +19,17 @@ pub enum BuildMode { Build, Run, Check, + Test, } -#[derive(Debug, Default)] +#[derive(Clone, Debug, Default)] struct VexBuildOptions { target: Option, release: bool, profile: Option, library: bool, binaries: Vec, + filter: Option, dry_run: bool, locked: bool, offline: bool, @@ -43,66 +49,180 @@ pub fn build( let options = parse_vex_build_options(mode, args).map_err(Error::usage)?; let compiler = Compiler::select(); let _project = selection.enter()?; - let manifest = Manifest::load()?; - run_build(mode, &manifest, options, runtime, compiler, messages) + run_build( + mode, + &_project.selected, + options, + runtime, + compiler, + messages, + selection.graph.clone(), + ) } +struct MemberBuild { + manifest: Manifest, + targets: Vec, +} +struct PlannedTarget { + package: String, + manifest_path: PathBuf, + directory: PathBuf, + target: PackageTarget, + plan: compiler::PreparedBuild, +} fn run_build( mode: BuildMode, - manifest: &Manifest, + manifests: &[Manifest], options: VexBuildOptions, runtime: &[std::ffi::OsString], compiler: Result, messages: &mut Messages, + mut graph_selection: source::graph::Selection, ) -> Result { + graph_selection.include_tests = mode == BuildMode::Test; let started = Instant::now(); let root = std::env::current_dir().map_err(Error::environment)?; root.to_str().ok_or_else(|| { Error::resolution("wavec JSON protocol cannot represent a non-UTF-8 project root") })?; - let selected = select_targets(manifest, mode, &options)?; + let requested_selection = options.library || !options.binaries.is_empty(); + if manifests.len() > 1 { + for name in &options.binaries { + if !manifests.iter().any(|m| { + m.targets + .iter() + .any(|t| t.kind == TargetKind::Binary && t.name == *name) + }) { + return Err(Error::resolution(format!("unknown binary target `{name}`"))); + } + } + } + let mut members = Vec::new(); + for manifest in manifests { + if mode == BuildMode::Test + && !manifest + .tests + .iter() + .any(|t| options.filter.as_ref().is_none_or(|f| t.name.contains(f))) + { + continue; + } + let mut local = options.clone(); + if manifests.len() > 1 { + local.library &= manifest.lib; + local.binaries.retain(|name| { + manifest + .targets + .iter() + .any(|t| t.kind == TargetKind::Binary && t.name == *name) + }); + if requested_selection && !local.library && local.binaries.is_empty() { + continue; + } + if mode == BuildMode::Run + && !manifest + .targets + .iter() + .any(|t| t.kind == TargetKind::Binary) + { + continue; + } + } + let targets = select_targets(manifest, mode, &local)? + .into_iter() + .cloned() + .collect(); + members.push(MemberBuild { + manifest: manifest.clone(), + targets, + }); + } + if mode == BuildMode::Test { + members.sort_by(|a, b| a.manifest.name.cmp(&b.manifest.name)); + } + if members.is_empty() { + return Err(Error::resolution("no package targets match the selection")); + } + if mode == BuildMode::Run && (members.len() != 1 || members[0].targets.len() != 1) { + return Err(Error::resolution("vex run requires one binary across the selected packages; use -p and --bin ")); + } + let selected_paths: Vec<_> = members + .iter() + .map(|m| m.manifest.source_path.clone()) + .collect(); let profile_name = options .profile .as_deref() .unwrap_or(if options.release { "release" } else { "dev" }); - let profile = manifest.profile(profile_name).map_err(Error::resolution)?; - for target in &selected { - validate_entry(manifest, target)?; + for member in &mut members { + if let Some(scope) = &mut member.manifest.scope { + scope.selected = selected_paths.clone(); + } + member + .manifest + .profile(profile_name) + .map_err(Error::resolution)?; + for target in &member.targets { + validate_entry(&member.manifest, target)?; + } } + let primary = &members[0].manifest; let mut selected_compiler = compiler?; let compiler = &mut selected_compiler; let requested_triple = options .target .as_deref() - .or(manifest.build_target.as_deref()); + .or(primary.build_target.as_deref()); if let Some(target) = requested_triple { compiler.validate_target(target)?; } - compiler.validate_version(manifest.compiler.as_deref())?; - let resolution = resolve_validated( - manifest, + for member in &members { + compiler.validate_version(member.manifest.compiler.as_deref())?; + } + let recovery_guard = + state::Guard::acquire(options.dry_run, ui::status).map_err(Error::environment)?; + resolver::recover_project(&recovery_guard, options.dry_run)?; + drop(recovery_guard); + let spec = compiler.target_spec(requested_triple)?; + let triple = spec["triple"].as_str().unwrap().to_owned(); + let mut requests = Vec::new(); + for member in &members { + for target in &member.targets { + let mut selection = graph_selection.clone(); + let mut context = source::graph::Context::new(&triple).map_err(Error::resolution)?; + if let Some(mode) = member.manifest.platform_for(target, &triple).mode { + context.mode = mode.as_str().into(); + } + selection.target = Some(context); + requests.push(resolver::ActivationRequest { + manifest: resolver::manifest_key(&member.manifest.source_path)?, + selection, + }); + } + } + let mut resolution = resolve_validated( + primary, ResolveOptions { + requests, + selection: graph_selection.clone(), dry_run: options.dry_run, update: UpdatePolicy::ReuseLocked, locked: options.locked, offline: options.offline, + ..Default::default() }, ui::status, |candidate| compiler.validate_version(candidate.compiler.as_deref()), )?; - let spec = compiler.target_spec(requested_triple)?; - let triple = spec["triple"].as_str().unwrap().to_owned(); ui::verbose(format!("target: {triple}")); ui::verbose(format!("compiler: {}", compiler.path().display())); - ui::trace(format!( - "build options: {options:?}; compiler plan is queried for each selected package target" - )); ui::verbose(format!( - "resolved {} dependencies", + "resolved {} dependency bindings", resolution.package_count() )); - if mode == BuildMode::Run + if matches!(mode, BuildMode::Run | BuildMode::Test) && !runtime.is_empty() && spec["object_format"] == "wasm" && spec["hosted"] == false @@ -112,7 +232,7 @@ fn run_build( )); } let mut run_lease = None; - let generation = if mode == BuildMode::Run { + let generation = if matches!(mode, BuildMode::Run | BuildMode::Test) { Some(if options.dry_run { PathBuf::from("target/.vex-run/planned") } else { @@ -127,88 +247,139 @@ fn run_build( let mut prepared = Vec::new(); let reporting = messages.enabled(); messages.status("compiler")?; - for target in &selected { - let configuration = crate::native::prepare_target( - manifest, - target, - &resolution, - compiler, - &triple, - profile_name, - mode == BuildMode::Check, - generation.as_deref(), - )?; - let mut args = resolution.dependency_args()?; - if target.kind == TargetKind::Binary && manifest.lib { - args.push(format!("--dep={}={}", manifest.name, root.display())); - } - args.push(format!("-O{}", profile.opt_level)); - args.extend(configuration.global); - args.push("build".into()); - args.push(input_string(&target.path)?); - if mode == BuildMode::Run { - args.push("--run".into()); - } - if mode == BuildMode::Check { - args.push("--emit=check".into()); + for member in &members { + let profile = member + .manifest + .profile(profile_name) + .map_err(Error::resolution)?; + let directory = member + .manifest + .source_path + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or(Path::new(".")) + .canonicalize() + .map_err(Error::environment)?; + for target in &member.targets { + let mut selection = graph_selection.clone(); + let mut context = source::graph::Context::new(&triple).map_err(Error::resolution)?; + if let Some(mode) = member.manifest.platform_for(target, &triple).mode { + context.mode = mode.as_str().into(); + } + selection.target = Some(context); + resolution.activate_root(&member.manifest.source_path, &selection)?; + let configuration = crate::native::prepare_target( + &member.manifest, + target, + &resolution, + compiler, + &triple, + profile_name, + mode == BuildMode::Check, + generation.as_deref(), + )?; + let mut args = resolution.dependency_args()?; + if target.kind == TargetKind::Binary && member.manifest.lib { + args.push(format!( + "--dep={}={}", + member.manifest.name, + input_string(&directory)? + )); + } + args.push(format!("-O{}", profile.opt_level)); + args.extend(configuration.global); + args.push("build".into()); + args.push(input_string(&target.path)?); + if matches!(mode, BuildMode::Run | BuildMode::Test) { + args.push("--run".into()); + } + if mode == BuildMode::Check { + args.push("--emit=check".into()); + } + args.extend(configuration.inputs); + args.extend(configuration.output); + let identity = json!({"name":target.name,"kind":target.kind.as_str()}); + let mut report = |mut event: serde_json::Value| { + event["package"] = json!(member.manifest.name); + event["package_target"] = identity.clone(); + event["profile"] = json!(profile_name); + messages.emit(event) + }; + let plan = prepare_build( + compiler, + &args, + runtime, + options.dry_run, + generation.as_deref(), + if reporting { Some(&mut report) } else { None }, + ) + .map_err(|e| target_error(e, target, profile_name))?; + prepared.push(PlannedTarget { + package: member.manifest.name.clone(), + manifest_path: member.manifest.source_path.clone(), + directory: directory.clone(), + target: target.clone(), + plan, + }); } - args.extend(configuration.inputs); - args.extend(configuration.output); - let identity = json!({"name":target.name,"kind":target.kind.as_str()}); - let mut report = |mut event: serde_json::Value| { - event["package_target"] = identity.clone(); - event["profile"] = json!(profile_name); - messages.emit(event) - }; - let plan = prepare_build( - compiler, - &args, - runtime, - options.dry_run, - generation.as_deref(), - if reporting { Some(&mut report) } else { None }, - ) - .map_err(|e| target_error(e, target, profile_name))?; - prepared.push((*target, plan)); } - // Even optional linker companions must be disjoint between package targets. let paths = prepared .iter() - .flat_map(|(_, p)| p.output_paths().cloned()) + .flat_map(|p| p.plan.output_paths().cloned()) .collect::>(); state::artifacts::validate_output_paths(&root, &paths).map_err(Error::compiler)?; if options.dry_run { ui::verbose("freshness: planning only; compiler will not execute"); - for (target, _) in &prepared { + let plans = prepared.iter().map(|task| json!({"package":task.package,"manifest_path":task.manifest_path,"build_directory":root,"run_directory":if matches!(mode, BuildMode::Run|BuildMode::Test) { Some(&task.directory) } else { None },"package_target":{"name":task.target.name,"kind":task.target.kind.as_str()},"compiler_plan":task.plan.plan()})).collect::>(); + for task in &prepared { ui::status( "Planning", - format!("{} {}", target.kind.as_str(), target.name), + format!( + "{} {} ({})", + task.target.kind.as_str(), + task.target.name, + task.package + ), ); } - let plans = prepared - .iter() - .map(|(target, plan)| { - json!({ - "package_target":{"name":target.name,"kind":target.kind.as_str()}, - "compiler_plan":plan.plan() - }) - }) - .collect::>(); - let envelope = json!({"schema":"vex.build-plan","schema_version":1,"target":triple, - "profile":{"name":profile_name,"opt_level":profile.opt_level},"plans":plans}); - diagnostic::outln!( - "{}", - serde_json::to_string_pretty(&envelope).map_err(Error::internal)? - ); + let profile = primary.profile(profile_name).map_err(Error::resolution)?; + diagnostic::outln!("{}", serde_json::to_string_pretty(&json!({"schema":"vex.build-plan","schema_version":1,"target":triple,"profile":{"name":profile_name,"opt_level":profile.opt_level},"plans":plans})).map_err(Error::internal)?); return Ok(Outcome::success()); } - for (target, plan) in &prepared { - plan.preflight_ownership() - .map_err(|e| target_error(e, target, profile_name))?; + for task in &prepared { + task.plan + .preflight_ownership() + .map_err(|e| target_error(e, &task.target, profile_name))?; } - ui::verbose("freshness: no build cache; compiling the current project"); - let mut execution = None; - for (target, plan) in prepared { + let mut source_roots = members + .iter() + .map(|m| m.manifest.source_path.parent().unwrap().to_path_buf()) + .collect::>(); + source_roots.push(root.clone()); + source_roots.extend(resolution.union_packages().iter().map(|p| p.directory())); + let freshness = if prepared + .iter() + .any(|task| task.plan.cache_eligibility().is_ok()) + { + compiler::freshness::Inputs::capture(compiler, source_roots, &json!({"capabilities":spec,"selection":graph_selection,"features":resolution.views().iter().map(|view|&view.features).collect::>()} ).to_string()) + .and_then(|inputs| inputs.fingerprint().map(|base| (inputs, base))) + } else { + Err(prepared + .first() + .and_then(|task| task.plan.cache_eligibility().err()) + .unwrap_or_else(|| "no reusable outputs".into())) + }; + match &freshness {Ok(_)=>ui::verbose("freshness: source, dependency, compiler runtime and standard library contents fingerprinted"), Err(reason)=>ui::verbose(format!("freshness: compiling; {reason}"))}; + let mut executions = Vec::new(); + for mut task in prepared { + if let Ok((inputs, base)) = &freshness { + let (plan, status) = task.plan.with_fingerprint(base, inputs); + task.plan = plan; + match status { + Ok(()) => ui::verbose("freshness: verify cached artifacts before reuse"), + Err(reason) => ui::verbose(format!("freshness: compiling; {reason}")), + }; + } ui::status( if mode == BuildMode::Check { "Checking" @@ -216,26 +387,26 @@ fn run_build( "Compiling" }, format!( - "{} v{} ({} {})", - manifest.name, - manifest.version, - target.kind.as_str(), - target.name + "{} ({} {})", + task.package, + task.target.kind.as_str(), + task.target.name ), ); - let final_paths = if let Some(path) = plan.plan()["link"]["output"].as_str() { + let final_paths = if let Some(path) = task.plan.plan()["link"]["output"].as_str() { vec![path.to_owned()] } else { - plan.plan()["compile"] + task.plan.plan()["compile"] .as_array() .unwrap() .iter() .filter_map(|job| job["output"].as_str().map(str::to_owned)) .collect() }; - let identity = json!({"name":target.name,"kind":target.kind.as_str()}); - let artifact_kind = target.output.map(|v| v.as_str()).unwrap_or("binary"); + let identity = json!({"name":task.target.name,"kind":task.target.kind.as_str()}); + let artifact_kind = task.target.output.map(|v| v.as_str()).unwrap_or("binary"); let mut report = |mut event: serde_json::Value| { + event["package"] = json!(task.package); event["package_target"] = identity.clone(); event["profile"] = json!(profile_name); if event["event"] == "artifact" { @@ -243,19 +414,50 @@ fn run_build( } messages.emit(event) }; - execution = plan - .execute(compiler, if reporting { Some(&mut report) } else { None }) - .map_err(|e| target_error(e, target, profile_name))?; + let execution = task + .plan + .execute_reported( + compiler, + if reporting { Some(&mut report) } else { None }, + &mut |message| ui::verbose(message), + ) + .map_err(|e| target_error(e, &task.target, profile_name))? + .map(|execution| execution.in_directory(&task.directory)); + if let Some(execution) = execution { + executions.push((task.package.clone(), task.target.name.clone(), execution)); + } for path in final_paths { ui::status("Artifact", path); } } drop(resolution); let mut outcome = Outcome::success(); - if let Some(execution) = execution { - ui::status("Running", &selected[0].name); - messages.status("running")?; - outcome = Outcome::program(execution.execute()?); + for (package, name, execution) in executions { + ui::status( + if mode == BuildMode::Test { + "Testing" + } else { + "Running" + }, + &name, + ); + if mode == BuildMode::Test && outcome.origin == "program" { + messages.program_event(json!({"event":"status","phase":"running"})); + } else { + messages.status("running")?; + } + let result = Outcome::program(execution.execute()?); + if mode == BuildMode::Test { + ui::result(format!( + "test {package}::{name} ... {} (exit {})", + if result.code == 0 { "ok" } else { "FAILED" }, + result.code + )); + messages.program_event(json!({"event":"test_result","package":package,"test":name,"origin":"program","exit_code":result.code,"signal":result.signal,"success":result.code==0})); + } + if outcome.code == 0 { + outcome = result; + } } drop(run_lease); if outcome.code == 0 { @@ -284,6 +486,25 @@ fn select_targets<'a>( mode: BuildMode, options: &VexBuildOptions, ) -> Result, Error> { + if mode == BuildMode::Test { + let mut tests = manifest + .tests + .iter() + .filter(|target| { + options + .filter + .as_ref() + .is_none_or(|filter| target.name.contains(filter)) + }) + .collect::>(); + tests.sort_by(|a, b| a.name.cmp(&b.name)); + if tests.is_empty() { + return Err(Error::resolution( + "no executable tests match the name filter", + )); + } + return Ok(tests); + } let binaries = manifest .targets .iter() @@ -352,8 +573,14 @@ pub(crate) fn validate_entry(manifest: &Manifest, target: &PackageTarget) -> Res target.name ))); } - if manifest.format == 3 { - let root = std::env::current_dir().map_err(Error::environment)?; + if manifest.format >= 3 { + let root = manifest + .source_path + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or(Path::new(".")) + .canonicalize() + .map_err(Error::environment)?; let actual = path.canonicalize().map_err(Error::environment)?; if !actual.starts_with(root) { return Err(Error::resolution( @@ -372,7 +599,7 @@ fn parse_vex_build_options(mode: BuildMode, args: &[String]) -> Result Result { + options.filter = Some(token.into()) + } _ => { return Err(format!( "unexpected argument `{token}`. Vex builds the package described by vex.ws" @@ -437,6 +667,11 @@ fn parse_vex_build_options(mode: BuildMode, args: &[String]) -> Result 1) { return Err( "vex run selects one binary with --bin; --lib and multiple binaries are invalid".into(), @@ -489,6 +724,7 @@ fn set_target(options: &mut VexBuildOptions, target: &str) -> Result<(), String> fn build_usage(mode: BuildMode) -> &'static str { match mode { + BuildMode::Test => "usage: vex test [filter] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline] [-- ]", BuildMode::Build => { "usage: vex build [--lib] [--bin ] [--target ] [--profile | --release] [--dry-run] [--locked] [--offline]" } @@ -502,9 +738,23 @@ fn build_usage(mode: BuildMode) -> &'static str { } fn input_string(path: &Path) -> Result { - path.to_str().map(str::to_owned).ok_or_else(|| { + let value = path.to_str().ok_or_else(|| { Error::resolution("wavec JSON protocol cannot represent a non-UTF-8 input path") - }) + })?; + #[cfg(windows)] + { + if let Some(value) = value.strip_prefix(r"\\?\UNC\") { + return Ok(format!("//{}", value.replace('\\', "/"))); + } + Ok(value + .strip_prefix(r"\\?\") + .unwrap_or(value) + .replace('\\', "/")) + } + #[cfg(not(windows))] + { + Ok(value.to_owned()) + } } #[cfg(test)] diff --git a/src/commands/cache.rs b/src/commands/cache.rs new file mode 100644 index 0000000..63ab21b --- /dev/null +++ b/src/commands/cache.rs @@ -0,0 +1,40 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +use diagnostic::Error; + +pub fn cache(args: &[String]) -> Result<(), Error> { + if matches!(args, [arg] if arg == "--help" || arg == "-h") { + diagnostic::outln!("usage: vex cache prune [--apply] [--dry-run]"); + return Ok(()); + } + if args.first().map(String::as_str) != Some("prune") { + return Err(Error::usage("usage: vex cache prune [--apply] [--dry-run]")); + } + let mut apply = false; + let mut dry_run = false; + for arg in &args[1..] { + match arg.as_str() { + "--apply" if !apply => apply = true, + "--dry-run" if !dry_run => dry_run = true, + _ => { + return Err(Error::usage(format!( + "unexpected cache prune argument `{arg}`" + ))) + } + } + } + for path in resolver::prune_cache(apply && !dry_run)? { + diagnostic::outln!( + "{} {}", + if apply && !dry_run { + "Removed" + } else { + "Would remove" + }, + path.display() + ); + } + Ok(()) +} diff --git a/src/commands/check.rs b/src/commands/check.rs index 9b68dd0..c74ef51 100644 --- a/src/commands/check.rs +++ b/src/commands/check.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 pub fn check( args: &[String], runtime: &[std::ffi::OsString], diff --git a/src/commands/clean.rs b/src/commands/clean.rs index 6996f7a..48d6897 100644 --- a/src/commands/clean.rs +++ b/src/commands/clean.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use crate::{project::Selection, ui}; use diagnostic::Error; @@ -13,7 +17,7 @@ pub fn clean(args: &[String], selection: &Selection) -> Result<(), Error> { _ => return Err(Error::usage(USAGE)), }; let _project = selection.enter()?; - manifest::Manifest::load()?; + let _manifest = _project.primary(); let root = std::env::current_dir().map_err(Error::environment)?; for name in [".vex", ".vex/init.json", ".vex/transaction.json"] { state::reject_link(&root.join(name)).map_err(Error::environment)?; diff --git a/src/commands/doctor.rs b/src/commands/doctor.rs index 29eb442..e922605 100644 --- a/src/commands/doctor.rs +++ b/src/commands/doctor.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use compiler::Compiler; use diagnostic::Error; use manifest::{Manifest, TargetKind}; @@ -148,7 +152,7 @@ pub fn doctor(args: &[String], selection: &crate::project::Selection) -> Result< project .map(|project| { let path = path_text(&project.manifest_path)?; - let manifest = Manifest::load()?; + let manifest = project.primary(); Ok((project, path, manifest)) }) .transpose() @@ -217,19 +221,21 @@ pub fn doctor(args: &[String], selection: &crate::project::Selection) -> Result< ); } match project { - Ok(Some((_project, path, manifest))) => { + Ok(Some((project, path, manifest))) => { report.check( "project", "ok", false, &format!("{} at {path}", manifest.name), json!({"manifest_path":path, "name":manifest.name, "manifest_format":manifest.format}), ); - inspect_project( - &mut report, - &manifest, - compiler.as_mut(), - compatible_target, - target.as_deref(), - &host, - ); + for member in &project.selected { + inspect_project( + &mut report, + member, + compiler.as_mut(), + compatible_target, + target.as_deref(), + &host, + ); + } } Ok(None) => { report.check( @@ -478,7 +484,22 @@ fn inspect_project( ); return; } - let resolution = match resolver::inspect(manifest, false, |_, _| {}) { + let mut graph_selection = source::graph::Selection::default(); + if let Some(target) = target { + match source::graph::Context::new(target) { + Ok(context) => graph_selection.target = Some(context), + Err(error) => { + report.failure("local_graph", Error::resolution(error)); + return; + } + } + } + let mut resolution = match resolver::inspect_selected( + manifest, + false, + graph_selection.clone(), + |_, _| {}, + ) { Ok(resolution) => resolution, Err(error) => { report.check( @@ -514,14 +535,6 @@ fn inspect_project( }; let profile = &manifest.profiles["dev"]; let prerequisite = (|| { - for package in resolution.packages() { - let directory = match &package.source { - lockfile::LockedSource::Path { resolved, .. } - | lockfile::LockedSource::Git { resolved, .. } => resolved, - }; - let manifest = Manifest::load_from(directory.join(manifest::MANIFEST_FILE))?; - compiler.validate_version(manifest.compiler.as_deref())?; - } let spec = compiler.target_spec(target)?; Ok(spec["triple"].as_str().unwrap().to_owned()) })(); @@ -535,6 +548,18 @@ fn inspect_project( let mut planned_paths = Vec::new(); for package_target in targets { let result = (|| { + let mut context = source::graph::Context::new(&triple).map_err(Error::resolution)?; + if let Some(mode) = manifest.platform_for(package_target, &triple).mode { + context.mode = mode.as_str().into(); + } + graph_selection.target = Some(context); + resolution.activate_root(&manifest.source_path, &graph_selection)?; + for package in resolution.packages() { + let directory = package.directory(); + let manifest = Manifest::load_from(directory.join(manifest::MANIFEST_FILE))?; + compiler.validate_version(manifest.compiler.as_deref())?; + } + let native = crate::native::prepare_target( manifest, package_target, diff --git a/src/commands/edit.rs b/src/commands/edit.rs new file mode 100644 index 0000000..cc9aa24 --- /dev/null +++ b/src/commands/edit.rs @@ -0,0 +1,100 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +use crate::{project::Selection, ui}; +use diagnostic::Error; +use std::collections::BTreeMap; + +pub fn edit(remove: bool, args: &[String], selection: &Selection) -> Result<(), Error> { + let name = args + .first() + .filter(|s| !s.starts_with('-')) + .ok_or_else(|| Error::usage("expected a direct dependency name"))?; + manifest::validate_package_name(name).map_err(Error::usage)?; + let mut options = BTreeMap::new(); + let mut offline = false; + let mut i = 1; + while i < args.len() { + if args[i] == "--offline" && !offline { + offline = true; + i += 1; + continue; + } + let key = args[i] + .strip_prefix("--") + .filter(|k| { + matches!( + *k, + "git" + | "path" + | "branch" + | "tag" + | "rev" + | "version" + | "version-req" + | "package-name" + | "subdir" + ) + }) + .ok_or_else(|| Error::usage(format!("unknown dependency option `{}`", args[i])))?; + let value = args + .get(i + 1) + .filter(|s| !s.is_empty() && !s.starts_with('-')) + .ok_or_else(|| Error::usage(format!("missing value for --{key}")))?; + if options.insert(key, value).is_some() { + return Err(Error::usage(format!("duplicate --{key}"))); + } + i += 2; + } + if remove && !options.is_empty() { + return Err(Error::usage( + "remove accepts only a direct dependency name and --offline", + )); + } + if !remove && (options.contains_key("git") == options.contains_key("path")) { + return Err(Error::usage("add requires exactly one of --git or --path")); + } + let project = selection.enter()?; + if project.selected.len() != 1 { + return Err(Error::usage( + "select one package with -p for dependency editing", + )); + } + resolver::edit_manifest( + &project.primary(), + offline, + |m, raw| { + let addition = if remove { + None + } else { + let quote = |value: &str| -> Result { + if m.format >= 2 { + Ok(wson::quote(value)) + } else if value.contains(['"', '\n', '\r']) || value.ends_with('\\') { + Err(Error::usage("value cannot be represented without changing legacy string semantics; migrate the manifest explicitly")) + } else { + Ok(format!("\"{value}\"")) + } + }; + let mut fields = vec![format!("name = {}", quote(name)?)]; + for (key, value) in &options { + fields.push(format!( + "{} = {}", + if *key == "package-name" { + "package".to_owned() + } else { + key.replace('-', "_") + }, + quote(value)? + )); + } + Some(format!("{{ {} }}", fields.join(", "))) + }; + wson::edit::dependency(raw, name, addition.as_deref()).map_err(Error::resolution) + }, + ui::status, + )?; + ui::status(if remove { "Removed" } else { "Added" }, name); + Ok(()) +} diff --git a/src/commands/fetch.rs b/src/commands/fetch.rs index 3bc02b1..f39efcd 100644 --- a/src/commands/fetch.rs +++ b/src/commands/fetch.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use diagnostic::Error; use std::collections::BTreeSet; use std::time::Instant; @@ -42,12 +46,16 @@ pub(super) fn dependency_command( return Err(Error::usage(format!("`{option}` cannot be used with `vex update` because update refreshes Git refs and rewrites vex.lock"))); } let _project = selection.enter()?; - run_fetch(update, options) + run_fetch(update, options, selection.graph.clone(), _project.primary()) } -fn run_fetch(update: bool, options: DependencyOptions) -> Result<(), Error> { +fn run_fetch( + update: bool, + options: DependencyOptions, + graph: source::graph::Selection, + manifest: Manifest, +) -> Result<(), Error> { let started = Instant::now(); - let manifest = Manifest::load()?; let update_policy = if update { if options.packages.is_empty() { ui::status("Updating", "all Git dependencies"); @@ -74,6 +82,11 @@ fn run_fetch(update: bool, options: DependencyOptions) -> Result<(), Error> { let resolution = resolve( &manifest, ResolveOptions { + requests: Vec::new(), + update_bindings: None, + force_bindings: false, + additional_contexts: Vec::new(), + selection: graph, dry_run: false, update: update_policy, locked: options.locked, diff --git a/src/commands/info.rs b/src/commands/info.rs index c5de0a9..f6677cb 100644 --- a/src/commands/info.rs +++ b/src/commands/info.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use diagnostic::Error; use manifest::{DependencySource, Manifest, TargetKind}; @@ -12,11 +16,25 @@ pub fn info(args: &[String], selection: &crate::project::Selection) -> Result<() ))); } let project = selection.enter()?; - run_info(&project) + if project.workspace { + diagnostic::outln!("workspace: {}", project.owner.source_path.display()); + diagnostic::outln!( + "members: {}", + project + .members + .iter() + .map(|m| m.name.as_str()) + .collect::>() + .join(", ") + ); + } + for manifest in &project.selected { + run_info(manifest)?; + } + Ok(()) } -fn run_info(project: &crate::project::Project) -> Result<(), Error> { - let manifest = Manifest::load()?; +fn run_info(manifest: &Manifest) -> Result<(), Error> { diagnostic::outln!("Vex project info"); diagnostic::outln!("name: {}", manifest.name); diagnostic::outln!("version: {}", manifest.version); @@ -36,7 +54,7 @@ fn run_info(project: &crate::project::Project) -> Result<(), Error> { if let Some(default_run) = &manifest.default_run { diagnostic::outln!("default_run: {default_run}"); } - diagnostic::outln!("manifest: {}", project.manifest_path.display()); + diagnostic::outln!("manifest: {}", manifest.source_path.display()); if let Some(description) = manifest.description.as_ref() { diagnostic::outln!("description: {description}"); } @@ -48,11 +66,20 @@ fn run_info(project: &crate::project::Project) -> Result<(), Error> { } diagnostic::outln!("dependencies: {}", manifest.dependencies.len()); - for dep in manifest.dependencies { + for dep in manifest.dependencies.clone() { + let alias = if dep.name != dep.package_name() { + format!("{} => {}", dep.name, dep.package_name()) + } else { + dep.name.clone() + }; + let label = dep + .version_req + .as_ref() + .map_or_else(|| alias.clone(), |req| format!("{alias} requires {req}")); match dep.source { DependencySource::Path { path } => match dep.version { - Some(version) => diagnostic::outln!(" {} {} path {}", dep.name, version, path), - None => diagnostic::outln!(" {} path {}", dep.name, path), + Some(version) => diagnostic::outln!(" {} {} path {}", label, version, path), + None => diagnostic::outln!(" {} path {}", label, path), }, DependencySource::Git { url, @@ -69,7 +96,7 @@ fn run_info(project: &crate::project::Project) -> Result<(), Error> { Some(version) => { diagnostic::outln!( " {} {} git {}{}", - dep.name, + label, version, source::identity(&url), reference @@ -77,7 +104,7 @@ fn run_info(project: &crate::project::Project) -> Result<(), Error> { } None => diagnostic::outln!( " {} git {}{}", - dep.name, + label, source::identity(&url), reference ), diff --git a/src/commands/init.rs b/src/commands/init.rs index 0a11416..c90677b 100644 --- a/src/commands/init.rs +++ b/src/commands/init.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use diagnostic::Error; use std::env; use std::fs; @@ -51,7 +55,14 @@ fn run_init(is_lib: bool) -> Result<(), Error> { }; let mut files = vec![ (source_name.as_str(), source_template.to_string()), - ("vex.lock", lockfile::encode(Lockfile::empty())), + ( + "vex.lock", + lockfile::encode(Lockfile { + version: 3, + packages: Vec::new(), + roots: Vec::new(), + }), + ), ]; let created_ignore = fs::symlink_metadata(Path::new(".gitignore")).is_err(); if created_ignore { diff --git a/src/commands/metadata.rs b/src/commands/metadata.rs index 5ea4837..7b37066 100644 --- a/src/commands/metadata.rs +++ b/src/commands/metadata.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use diagnostic::Error; use lockfile::LockedSource; use manifest::{Manifest, PackageTarget, PlatformSettings, TargetKind}; @@ -34,16 +38,21 @@ pub fn metadata(args: &[String], selection: &crate::project::Selection) -> Resul } let format_version = format_version.unwrap_or(1); let project = selection.enter()?; - let root = project.manifest_path.parent().unwrap(); + let root = project.owner.source_path.parent().unwrap(); json_path(root)?; - let manifest = Manifest::load()?; + let manifest = project.primary(); if format_version == 1 { require_single_target(&manifest)?; } - let resolution = resolver::inspect(&manifest, locked, crate::ui::status)?; + let resolution = resolver::inspect_selected( + &manifest, + locked, + selection.graph.clone(), + crate::ui::status, + )?; let mut packages = Vec::new(); for package in resolution.packages() { - let (resolved, source) = match &package.source { + let (_resolved, source) = match &package.source { LockedSource::Path { requested, resolved, @@ -57,10 +66,13 @@ pub fn metadata(args: &[String], selection: &crate::project::Selection) -> Resul resolved, } => ( resolved, - json!({"kind":"git", "url":source::identity(url), "branch":branch,"tag":tag,"rev":rev,"commit":commit}), + json!({"kind":"git", "url":source::identity(url), "branch":branch,"tag":tag,"rev":rev,"commit":commit,"subdir":package.subdir}), ), }; - let directory = resolved.canonicalize().map_err(Error::environment)?; + let directory = package + .directory() + .canonicalize() + .map_err(Error::environment)?; let package_manifest_path = directory.join(manifest::MANIFEST_FILE); let package_manifest = Manifest::load_from(&package_manifest_path)?; let mut value = package_record( @@ -70,14 +82,69 @@ pub fn metadata(args: &[String], selection: &crate::project::Selection) -> Resul format_version, )?; value["source"] = source; + if format_version >= 2 { + value["dependency_declarations"] = json!(package.edges); + } + if package.id.is_some() { + value["id"] = json!(package.id); + value["alias"] = json!(package.import_name()); + value["binding"] = json!(package.name); + } let mut dependencies = package.dependencies.clone(); dependencies.sort(); value["dependencies"] = json!(dependencies); packages.push(value); } packages.sort_by(|a, b| a["name"].as_str().cmp(&b["name"].as_str())); - let value: Value = json!({"schema_version":format_version, - "root":package_record(&manifest, root, &project.manifest_path, format_version)?, + let root_record = if project.workspace { + let default_paths = project + .owner + .workspace + .as_ref() + .unwrap() + .defaults(&project.owner, &project.members)?; + json!({"kind":"workspace", "root":json_path(root)?, "manifest_path":json_path(&project.owner.source_path)?, "package":if project.owner.virtual_workspace { None } else { Some(&project.owner.name) }, "members":project.members.iter().map(|m| &m.name).collect::>(), "default_members":project.members.iter().filter(|m| default_paths.contains(&m.source_path)).map(|m| &m.name).collect::>()}) + } else { + let mut value = package_record(&manifest, root, &project.manifest_path, format_version)?; + value["dependencies"] = json!(resolution.root_dependencies()); + if format_version >= 2 { + value["dependency_declarations"] = json!(resolution.root_records()[0].edges); + } + value + }; + let mut members = Vec::new(); + if project.workspace { + for member in &project.members { + let directory = member.source_path.parent().unwrap(); + let mut value = package_record(member, directory, &member.source_path, 2)?; + let key = resolver::manifest_key(&member.source_path)?; + let selected = project + .selected + .iter() + .any(|m| m.source_path == member.source_path); + value["selected"] = json!(selected); + value["dependency_declarations"] = json!( + resolution + .root_records() + .iter() + .find(|r| r.manifest == key) + .unwrap() + .edges + ); + value["dependencies"] = json!(resolution + .views() + .iter() + .filter(|v| v.root.manifest == key) + .flat_map(|v| v.dependencies.iter().cloned()) + .collect::>()); + members.push(value); + } + } + let selections = resolution.views().iter().map(|v| json!({"manifest":v.root.manifest,"package":v.root.name,"selection":v.selection,"dependencies":v.dependencies,"features":v.features})).collect::>(); + let union = resolution.union_packages().iter().map(|p| Ok(json!({"binding":p.name,"alias":p.import_name(),"id":p.id,"name":p.package_name(),"version":p.version,"dependencies":p.dependencies,"edges":p.edges,"features":p.features,"source":source_record(p),"root":json_path(&root.join(p.directory()))?}))).collect::, Error>>()?; + let value: Value = json!({"schema_version":format_version,"root":root_record, + "selected_features":resolution.selected_features(), "selection":if resolution.views().len() == 1 { Some(resolution.selection()) } else { None }, "selections":selections, + "workspace_members":members,"union_bindings":union, "target_directory":json_path(&root.join("target"))?, "packages":packages}); diagnostic::outln!( "{}", @@ -86,6 +153,22 @@ pub fn metadata(args: &[String], selection: &crate::project::Selection) -> Resul Ok(()) } +fn source_record(package: &lockfile::LockedPackage) -> Value { + match &package.source { + LockedSource::Path { requested, .. } => json!({"kind":"path","requested":requested}), + LockedSource::Git { + url, + branch, + tag, + rev, + commit, + .. + } => { + json!({"kind":"git","url":source::identity(url),"branch":branch,"tag":tag,"rev":rev,"commit":commit,"subdir":package.subdir}) + } + } +} + fn parse_version(value: Option<&str>, selected: &mut Option) -> Result<(), Error> { if selected.is_some() { return Err(Error::usage("--format-version may only be specified once")); @@ -99,7 +182,7 @@ fn parse_version(value: Option<&str>, selected: &mut Option) -> Result<(), } fn require_single_target(manifest: &Manifest) -> Result<&PackageTarget, Error> { - if manifest.targets.len() != 1 { + if manifest.targets.len() != 1 || manifest.format >= 4 || manifest.scope.is_some() { return Err(Error::resolution(format!( "metadata schema 1 cannot represent the targets of package `{}`\nhelp: use `vex metadata --format-version 2`", manifest.name @@ -124,6 +207,32 @@ fn package_record( "manifest_format":manifest.format, "compiler":manifest.compiler, "root":json_path(root)?, "manifest_path":json_path(manifest_path)?, "native":crate::native::configuration(manifest), "dependencies":dependencies}); + if version >= 2 { + value["features"] = json!(manifest.features); + } + if manifest.format >= 4 || manifest.scope.is_some() { + let identity_path = if let Some(scope) = &manifest.scope { + root.strip_prefix(scope.owner.parent().unwrap()) + .map_err(Error::resolution)? + .to_path_buf() + } else { + ".".into() + }; + let identity_path = if identity_path.as_os_str().is_empty() { + ".".into() + } else { + identity_path + }; + value["id"] = json!(lockfile::package_identity( + &manifest.name, + &manifest.version, + &LockedSource::Path { + requested: ".".into(), + resolved: identity_path + }, + None + )); + } if version == 1 { let target = require_single_target(manifest)?; value["kind"] = json!(kind_name(target.kind)); @@ -141,6 +250,7 @@ fn package_record( }) .collect::>()?, ); + value["tests"] = Value::Array(manifest.tests.iter().map(|target| Ok(json!({"name":target.name,"entry_path":json_path(&root.join(&target.path))?,"platform":platform_record(&target.platform)?}))).collect::>()?); value["default_run"] = json!(manifest.default_run); value["profiles"] = json!(manifest .profiles diff --git a/src/commands/mod.rs b/src/commands/mod.rs index 078ac7c..d4b9abe 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 pub mod build; pub mod check; pub mod fetch; @@ -12,3 +16,8 @@ pub mod clean; pub mod doctor; pub mod metadata; pub mod prune; + +pub mod cache; + +pub mod edit; +pub mod new; diff --git a/src/commands/new.rs b/src/commands/new.rs new file mode 100644 index 0000000..0c39934 --- /dev/null +++ b/src/commands/new.rs @@ -0,0 +1,131 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +use diagnostic::Error; +use std::{fs, path::PathBuf}; + +pub fn new(args: &[String]) -> Result<(), Error> { + let destination = args + .first() + .filter(|s| !s.starts_with('-')) + .ok_or_else(|| Error::usage("usage: vex new [--name ] [--lib] [--git]"))?; + let mut name = None; + let mut library = false; + let mut git = false; + let mut i = 1; + while i < args.len() { + match args[i].as_str() { + "--lib" if !library => library = true, + "--git" if !git => git = true, + "--name" if name.is_none() => { + i += 1; + name = Some( + args.get(i) + .filter(|s| !s.starts_with('-')) + .ok_or_else(|| Error::usage("--name requires a package name"))? + .clone(), + ); + } + other => { + return Err(Error::usage(format!( + "unknown or repeated new option `{other}`" + ))) + } + } + i += 1; + } + let destination = PathBuf::from(destination); + if fs::symlink_metadata(&destination).is_ok() { + return Err(Error::environment( + "destination already exists; preserving it", + )); + } + let inferred = destination + .file_name() + .and_then(|s| s.to_str()) + .ok_or_else(|| Error::usage("destination needs a UTF-8 package name; use --name"))?; + let name = name.as_deref().unwrap_or(inferred); + manifest::validate_package_name(name) + .map_err(|e| Error::usage(format!("{e}; choose an explicit valid --name")))?; + manifest::validate_target_name(name).map_err(Error::usage)?; + let parent = destination + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or(std::path::Path::new(".")) + .canonicalize() + .map_err(Error::environment)?; + let destination = parent.join( + destination + .file_name() + .ok_or_else(|| Error::usage("destination must name a directory"))?, + ); + // Exclusive directory creation never replaces even an empty destination. + // The existing scaffold journal recovers interrupted file publication. + fs::create_dir(&destination)?; + let stage = destination.clone(); + let previous = std::env::current_dir()?; + let result = (|| { + std::env::set_current_dir(&stage)?; + let guard = state::Guard::acquire(false, crate::ui::status).map_err(Error::environment)?; + let manifest = manifest::render_new_manifest(name, "unknown", library) + .replacen("format = 3", "format = 4", 1) + .replacen("version = 0.1.0", "version = \"0.1.0\"", 1); + let source = if library { + "pub fun greet() {\n println(\"Hello from library\");\n}\n" + } else { + "fun main() {\n println(\"Hello World\");\n}\n" + }; + let root = source::graph::Root { + manifest: "vex.ws".into(), + name: name.into(), + version: "0.1.0".into(), + edges: vec![], + features: Default::default(), + }; + let files = vec![ + ( + if library { + "src/lib.wave" + } else { + "src/main.wave" + }, + source.into(), + ), + ( + "vex.lock", + lockfile::encode(lockfile::Lockfile { + version: 4, + packages: vec![], + roots: vec![root], + }), + ), + (".gitignore", "/target/\n/.vex/\n".into()), + ("vex.ws", manifest), + ]; + state::initialize(&guard, &files).map_err(Error::environment)?; + drop(guard); + if git { + let mut command = resolver::project_git_command(); + command.args(["init", "--quiet"]); + command.current_dir(&stage); + let status = process::status( + &mut command, + Some(std::time::Duration::from_secs(120)), + false, + ) + .map_err(Error::environment)?; + if !status.success() { + return Err(Error::environment("git init failed")); + } + } + state::sync_dir(&parent)?; + Ok(()) + })(); + let _ = std::env::set_current_dir(previous); + // A failure preserves the new directory and journal for explicit recovery. + // Never recursively remove it: a user may have placed files in it. + result?; + diagnostic::outln!("created Wave project at {}", destination.display()); + Ok(()) +} diff --git a/src/commands/prune.rs b/src/commands/prune.rs index 7f8c0ff..2f8f93e 100644 --- a/src/commands/prune.rs +++ b/src/commands/prune.rs @@ -1,5 +1,8 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use diagnostic::Error; -use manifest::Manifest; const USAGE: &str = "usage: vex prune [--apply] [--dry-run]"; @@ -27,7 +30,7 @@ pub fn prune(args: &[String], selection: &crate::project::Selection) -> Result<( } } let _project = selection.enter()?; - let manifest = Manifest::load()?; + let manifest = _project.primary(); let applied = apply && !dry_run; let report = resolver::prune(&manifest, applied, crate::ui::status)?; for path in &report.removable { @@ -59,7 +62,7 @@ pub fn prune(args: &[String], selection: &crate::project::Selection) -> Result<( } if report.removed > 0 { diagnostic::outln!( - "No shared cache is kept. Restoring a removed dependency requires `vex fetch` and access to its source." + "Restoring a removed dependency requires `vex fetch`; network access may be needed if its exact commit is not cached." ); } Ok(()) diff --git a/src/commands/run.rs b/src/commands/run.rs index 93b26d9..a081e2d 100644 --- a/src/commands/run.rs +++ b/src/commands/run.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 pub fn run( args: &[String], runtime: &[std::ffi::OsString], diff --git a/src/commands/setup.rs b/src/commands/setup.rs index f3b7fd8..c8b448e 100644 --- a/src/commands/setup.rs +++ b/src/commands/setup.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use diagnostic::Error; pub fn setup(args: &[String]) -> Result<(), Error> { diff --git a/src/commands/tree.rs b/src/commands/tree.rs index d80bfc7..2b90952 100644 --- a/src/commands/tree.rs +++ b/src/commands/tree.rs @@ -1,8 +1,8 @@ -use diagnostic::Error; // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. // SPDX-License-Identifier: MPL-2.0 +use diagnostic::Error; use std::collections::BTreeMap; @@ -32,19 +32,22 @@ pub fn tree(args: &[String], selection: &crate::project::Selection) -> Result<() } let options = parse_options(args).map_err(Error::usage)?; let _project = selection.enter()?; - run_tree(options) + run_tree(options, selection.graph.clone(), _project.primary()) } -fn run_tree(options: TreeOptions) -> Result<(), Error> { - let manifest = Manifest::load()?; - let root_dependencies = manifest - .dependencies - .iter() - .map(|dependency| dependency.name.clone()) - .collect::>(); +fn run_tree( + options: TreeOptions, + graph: source::graph::Selection, + manifest: Manifest, +) -> Result<(), Error> { let resolution = resolve( &manifest, ResolveOptions { + requests: Vec::new(), + update_bindings: None, + force_bindings: false, + additional_contexts: Vec::new(), + selection: graph, dry_run: false, update: UpdatePolicy::ReuseLocked, locked: options.locked, @@ -52,18 +55,46 @@ fn run_tree(options: TreeOptions) -> Result<(), Error> { }, ui::status, )?; - diagnostic::out!( - "{}", - render_tree( - &manifest.name, - &manifest.version, - &root_dependencies, - resolution.packages(), - options.invert.as_deref(), - options.depth, - ) - .map_err(Error::resolution)? - ); + let mut found = options.invert.is_none(); + for view in resolution.views() { + let invert = if let Some(requested) = options.invert.as_deref() { + let matching: Vec<_> = view + .packages + .iter() + .filter(|p| { + p.name == requested + || p.import_name() == requested + || p.id.as_deref() == Some(requested) + }) + .collect(); + match matching.as_slice() { + [package] => { found = true; Some(package.name.as_str()) }, + [] if requested == view.root.name => { found = true; Some(requested) }, + [] => continue, + _ => return Err(Error::resolution("inverse query matches multiple bindings; select a binding key from metadata schema 2")), + } + } else { + None + }; + diagnostic::out!( + "{}", + render_tree( + &view.root.name, + &view.root.version, + &view.dependencies, + &view.packages, + invert, + options.depth + ) + .map_err(Error::resolution)? + ); + } + if !found { + return Err(Error::resolution(format!( + "package `{}` is not present in the selected dependency graph", + options.invert.as_deref().unwrap() + ))); + } Ok(()) } @@ -245,9 +276,14 @@ impl TreeRenderer<'_> { } fn package_label(package: &LockedPackage) -> String { + let name = if package.import_name() != package.package_name() { + format!("{} => {}", package.import_name(), package.package_name()) + } else { + package.import_name().to_owned() + }; match &package.source { LockedSource::Path { requested, .. } => { - format!("{} v{} (path {requested})", package.name, package.version) + format!("{} v{} (path {requested})", name, package.version) } LockedSource::Git { url, @@ -264,9 +300,14 @@ fn package_label(package: &LockedPackage) -> String { .or_else(|| rev.as_ref().map(|value| format!(" rev {value}"))) .unwrap_or_default(); let short_commit = &commit[..commit.len().min(7)]; + let subdir = package + .subdir + .as_ref() + .map(|p| format!(" subdir {p}")) + .unwrap_or_default(); format!( - "{} v{} (git {}{reference} @ {short_commit})", - package.name, + "{} v{} (git {}{reference}{subdir} @ {short_commit})", + name, package.version, source::identity(url) ) @@ -282,6 +323,12 @@ mod tests { fn path_package(name: &str, version: &str, dependencies: &[&str]) -> LockedPackage { LockedPackage { + package: None, + id: None, + import_name: None, + edges: Vec::new(), + features: Default::default(), + subdir: None, name: name.to_string(), version: version.to_string(), source: LockedSource::Path { @@ -299,6 +346,12 @@ mod tests { fn renders_sources_commits_and_shared_dependencies() { let packages = vec![ LockedPackage { + package: None, + id: None, + import_name: None, + edges: Vec::new(), + features: Default::default(), + subdir: None, name: "alpha".to_string(), version: "1.0.0".to_string(), source: LockedSource::Git { diff --git a/src/commands/update.rs b/src/commands/update.rs index 3880d77..b4d2f19 100644 --- a/src/commands/update.rs +++ b/src/commands/update.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 pub fn update( args: &[String], selection: &crate::project::Selection, diff --git a/src/main.rs b/src/main.rs index 42f757d..3c38628 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,9 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 mod cli; +mod command_spec; mod commands; mod messages; mod native; diff --git a/src/messages.rs b/src/messages.rs index 5acf62d..1f6c8dc 100644 --- a/src/messages.rs +++ b/src/messages.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 //! An opt-in event stream separate from compiler and runtime stdio. use diagnostic::Error; use serde_json::{json, Value}; @@ -112,6 +116,11 @@ impl Messages { } Ok(()) } + pub fn program_event(&mut self, value: Value) { + if let Err(error) = self.emit(value) { + crate::ui::warning(error); + } + } pub fn status(&mut self, phase: &str) -> Result<(), Error> { self.emit(json!({"event":"status", "phase":phase})) } diff --git a/src/native.rs b/src/native.rs index 4811b89..b697bc1 100644 --- a/src/native.rs +++ b/src/native.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 //! Manifest-owned native linking. Foreign sources and build scripts are never executed. use compiler::Compiler; use diagnostic::Error; @@ -120,21 +124,28 @@ fn named_library( /// Dependent libraries precede their dependencies, including diamonds. Preserve /// declaration order within a package because static archive order is significant. fn manifests(root: &Manifest, resolution: &Resolution) -> Result, Error> { - let mut values = BTreeMap::from([(root.name.clone(), root.clone())]); + let mut values = BTreeMap::from([( + root.name.clone(), + ( + root.clone(), + resolution.root_dependencies().to_vec(), + format!("root:{}", root.source_path.display()), + ), + )]); for package in resolution.packages() { - let directory = match &package.source { - lockfile::LockedSource::Git { resolved, .. } - | lockfile::LockedSource::Path { resolved, .. } => resolved, - }; values.insert( package.name.clone(), - Manifest::load_from(directory.join(manifest::MANIFEST_FILE))?, + ( + Manifest::load_from(package.directory().join(manifest::MANIFEST_FILE))?, + package.dependencies.clone(), + package.id.clone().unwrap_or_else(|| package.name.clone()), + ), ); } let mut incoming: BTreeMap<_, usize> = values.keys().map(|name| (name.clone(), 0)).collect(); - for manifest in values.values() { - for dependency in &manifest.dependencies { - *incoming.get_mut(&dependency.name).ok_or_else(|| { + for (_, dependencies, _) in values.values() { + for dependency in dependencies { + *incoming.get_mut(dependency).ok_or_else(|| { Error::resolution("incomplete native dependency graph; run vex fetch") })? += 1; } @@ -145,16 +156,19 @@ fn manifests(root: &Manifest, resolution: &Resolution) -> Result, .map(|(name, _)| name.clone()) .collect(); let mut result = Vec::new(); + let mut seen = BTreeSet::new(); while let Some(name) = ready.pop_first() { - let manifest = values.remove(&name).unwrap(); - for dependency in &manifest.dependencies { - let count = incoming.get_mut(&dependency.name).unwrap(); + let (manifest, dependencies, identity) = values.remove(&name).unwrap(); + for dependency in dependencies { + let count = incoming.get_mut(&dependency).unwrap(); *count -= 1; if *count == 0 { - ready.insert(dependency.name.clone()); + ready.insert(dependency); } } - result.push(manifest); + if seen.insert(identity) { + result.push(manifest); + } } if !values.is_empty() { return Err(Error::resolution("cycle in native dependency graph")); @@ -395,6 +409,11 @@ fn prepare_settings( .unwrap_or_else(|| PathBuf::from("target")) .join(triple) .join(profile); + let directory = if root.scope.is_some() { + directory.join("packages").join(&root.name) + } else { + directory + }; let output_directory = directory.join(if target.kind == TargetKind::Library { "lib" } else { @@ -835,7 +854,8 @@ mod tests { .category, diagnostic::Category::Environment ); - assert!(Path::new(&linker_path(&root, "rustc").unwrap()).is_absolute()); + // Git is available in target execution guests as well as build hosts. + assert!(Path::new(&linker_path(&root, "git").unwrap()).is_absolute()); #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; diff --git a/src/outcome.rs b/src/outcome.rs index 4a763c5..c848e5c 100644 --- a/src/outcome.rs +++ b/src/outcome.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use diagnostic::{Category, Error}; use std::process::ExitStatus; diff --git a/src/project.rs b/src/project.rs index a8fd609..17f4fb6 100644 --- a/src/project.rs +++ b/src/project.rs @@ -1,17 +1,33 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use diagnostic::Error; -use manifest::MANIFEST_FILE; +use manifest::{Manifest, WorkspaceContext, MANIFEST_FILE}; +use std::collections::BTreeSet; use std::path::{Path, PathBuf}; #[derive(Default)] pub struct Selection { + pub graph: source::graph::Selection, pub manifest_path: Option, + pub packages: Vec, + pub all_packages: bool, } pub struct Project { pub manifest_path: PathBuf, + pub owner: Manifest, + pub members: Vec, + pub selected: Vec, + pub workspace: bool, previous_directory: PathBuf, } - +impl Project { + pub fn primary(&self) -> Manifest { + self.selected[0].clone() + } +} impl Selection { pub fn enter(&self) -> Result { let previous_directory = std::env::current_dir().map_err(Error::environment)?; @@ -23,11 +39,7 @@ impl Selection { if path.file_name().is_none_or(|name| name != MANIFEST_FILE) { return Err(Error::usage("--manifest-path must name a vex.ws file")); } - let path = if path.is_absolute() { - path.clone() - } else { - start.join(path) - }; + let path = start.join(path); if !path.is_file() { return Err(Error::environment(format!( "manifest not found at `{}`", @@ -37,9 +49,10 @@ impl Selection { path } None => discover(&start)?, - }; - let manifest_path = selected.canonicalize().map_err(Error::environment)?; - if manifest_path + } + .canonicalize() + .map_err(Error::environment)?; + if selected .file_name() .is_none_or(|name| name != MANIFEST_FILE) { @@ -47,27 +60,120 @@ impl Selection { "the selected manifest must resolve to a vex.ws file", )); } - let root = manifest_path - .parent() - .ok_or_else(|| Error::environment("manifest has no parent directory"))?; - crate::ui::verbose(format!("project manifest: {}", manifest_path.display())); - crate::ui::trace(format!( - "project selection: {} from {}", - if self.manifest_path.is_some() { - "explicit manifest" + let nearest = Manifest::load_from(&selected) + .map_err(|error| error.context("invalid project manifest `vex.ws`"))?; + let mut workspace_owner = None; + for directory in selected.parent().unwrap().ancestors() { + let path = directory.join(MANIFEST_FILE); + let owner = if path == selected { + nearest.clone() } else { - "nearest real-path ancestor" - }, - start.display() - )); + if !path.is_file() { + continue; + } + // A malformed unrelated ancestor must not shadow a nearer project. + let Ok(actual) = path.canonicalize() else { + continue; + }; + if actual.parent() != Some(directory) { + continue; + } + let Ok(owner) = Manifest::load_from(&actual) else { + continue; + }; + owner + }; + let Some(spec) = &owner.workspace else { + continue; + }; + if spec.excluded(directory, selected.parent().unwrap()) && owner.source_path != selected + { + continue; + } + let paths = spec.member_paths(&owner)?; + if owner.source_path != selected && !paths.contains(&selected) { + return Err(Error::resolution(format!("package `{}` is inside a workspace but is not a member\nhelp: add its path to workspace.members or workspace.exclude in {}", nearest.name, owner.source_path.display()))); + } + if workspace_owner.is_some() { + return Err(Error::resolution("nested or overlapping workspace ownership is unsupported; exclude the independent workspace")); + } + workspace_owner = Some((owner, paths)); + } + let workspace = workspace_owner.is_some(); + let (owner, mut members) = match workspace_owner { + Some((owner, paths)) => { + let context = WorkspaceContext { + owner: owner.source_path.clone(), + members: paths, + selected: Vec::new(), + }; + let members = manifest::workspace::load_context(&context)?; + (owner, members) + } + None => (nearest.clone(), vec![nearest]), + }; + let defaults = if self.all_packages { + members.iter().map(|m| m.source_path.clone()).collect() + } else if !self.packages.is_empty() { + let names: BTreeSet<_> = self.packages.iter().collect(); + for name in &names { + if !members.iter().any(|member| &member.name == *name) { + return Err(Error::resolution(format!( + "unknown workspace package `{name}`" + ))); + } + } + members + .iter() + .filter(|m| names.contains(&m.name)) + .map(|m| m.source_path.clone()) + .collect() + } else if workspace && selected == owner.source_path { + owner + .workspace + .as_ref() + .unwrap() + .defaults(&owner, &members)? + } else { + vec![selected.clone()] + }; + for member in &mut members { + if let Some(scope) = &mut member.scope { + scope.selected = defaults.clone(); + } + } + let selected_members = members + .iter() + .filter(|m| defaults.contains(&m.source_path)) + .cloned() + .collect::>(); + if selected_members.is_empty() { + return Err(Error::resolution("no package selected")); + } + let root = owner.source_path.parent().unwrap(); + crate::ui::verbose(format!("project manifest: {}", selected.display())); + if workspace { + crate::ui::verbose(format!( + "workspace root: {}; selected {} package(s)", + root.display(), + selected_members.len() + )); + } std::env::set_current_dir(root).map_err(Error::environment)?; Ok(Project { - manifest_path, + manifest_path: if selected_members.len() == 1 { + selected_members[0].source_path.clone() + } else { + owner.source_path.clone() + }, + owner, + members, + selected: selected_members, + workspace, previous_directory, }) } } - fn discover(start: &Path) -> Result { for directory in start.ancestors() { let path = directory.join(MANIFEST_FILE); @@ -92,10 +198,8 @@ fn discover(start: &Path) -> Result { } Err(Error::environment(format!("could not find `{MANIFEST_FILE}` in `{}` or its ancestors\nhelp: run `vex init` to create a package", start.display()))) } - impl Drop for Project { fn drop(&mut self) { - // A command owns this scope until its compiler and user program exit. let _ = std::env::set_current_dir(&self.previous_directory); } } diff --git a/src/ui.rs b/src/ui.rs index 2bdbffd..e41ba57 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use std::sync::atomic::{AtomicU8, Ordering}; // 0: quiet, 1: normal, 2: verbose decisions, 3: diagnostic detail. @@ -25,6 +29,11 @@ pub fn status(action: &str, message: impl AsRef) { )); } +/// Command results stay visible in quiet mode, unlike progress. +pub fn result(message: impl AsRef) { + let _ = diagnostic::output::stderr(format_args!("{}\n", source::redact(message.as_ref()))); +} + pub fn verbose(message: impl AsRef) { status("Detail", message); } diff --git a/state/Cargo.toml b/state/Cargo.toml index 55176b9..4b43b9e 100644 --- a/state/Cargo.toml +++ b/state/Cargo.toml @@ -1,3 +1,7 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 [package] name = "state" version.workspace = true @@ -11,7 +15,7 @@ publish = false process.workspace = true serde_json.workspace = true serde = { version = "1.0", features = ["derive"] } -sha2 = "0.10" +sha2 = "0.11.1" [target.'cfg(unix)'.dependencies] libc = "0.2" diff --git a/state/src/artifacts.rs b/state/src/artifacts.rs index 9cd0798..42f233f 100644 --- a/state/src/artifacts.rs +++ b/state/src/artifacts.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 //! Conservative ownership of compiler outputs. All registry access is made //! while the caller owns the project guard; run leases outlive that guard. use crate::{atomic_rename, ensure_dir, inherit, reject_link, Guard}; @@ -190,7 +194,7 @@ fn fingerprint(path: &Path) -> Result, String> { } hash.update(&buffer[..count]); } - Ok(Some(format!("{:x}", hash.finalize()))) + Ok(Some(hex_digest(hash.finalize()))) } /// Kept alive during compilation and after releasing the project guard, through @@ -592,3 +596,18 @@ pub fn clean( } Ok(()) } +// Keep persisted IDs/checksums as zero-padded lowercase SHA-256 hex. The +// digest output type no longer implements LowerHex in sha2 0.11. +fn hex_digest(bytes: impl AsRef<[u8]>) -> String { + const DIGITS: &[u8; 16] = b"0123456789abcdef"; + bytes + .as_ref() + .iter() + .flat_map(|&byte| { + [ + char::from(DIGITS[(byte >> 4) as usize]), + char::from(DIGITS[(byte & 15) as usize]), + ] + }) + .collect() +} diff --git a/state/src/edit.rs b/state/src/edit.rs new file mode 100644 index 0000000..825a0ff --- /dev/null +++ b/state/src/edit.rs @@ -0,0 +1,174 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +//! A durable two-file edit. Uncommitted journals roll back, including after a crash. +use crate::{atomic_rename, reject_link, sync_dir, Guard}; +use serde::{Deserialize, Serialize}; +use std::{fs, io::Write, path::Path}; +const JOURNAL: &str = ".vex/edit.json"; +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Record { + version: u32, + manifest: String, + old: String, + new: String, + old_lock: Option, + new_lock: Option, + committed: bool, +} +fn read(root: &Path) -> Result, String> { + let path = root.join(JOURNAL); + reject_link(&path)?; + match fs::read_to_string(path) { + Ok(raw) => serde_json::from_str(&raw) + .map(Some) + .map_err(|e| e.to_string()), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(e.to_string()), + } +} +pub fn replace(path: &Path, text: &str) -> Result<(), String> { + reject_link(path)?; + let temporary = path.with_file_name(format!( + ".vex-edit-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_err(|e| e.to_string())? + .as_nanos() + )); + let result = (|| { + let mut options = fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let mut f = options.open(&temporary).map_err(|e| e.to_string())?; + f.write_all(text.as_bytes()).map_err(|e| e.to_string())?; + f.sync_all().map_err(|e| e.to_string())?; + drop(f); + atomic_rename(&temporary, path).map_err(|e| e.to_string()) + })(); + if result.is_err() { + let _ = fs::remove_file(&temporary); + } + result +} +fn store(root: &Path, record: &Record) -> Result<(), String> { + replace( + &root.join(JOURNAL), + &serde_json::to_string(record).map_err(|e| e.to_string())?, + ) +} +pub fn begin(guard: &Guard, manifest: &Path, new: String) -> Result<(), String> { + let root = guard.root(); + if read(root)?.is_some() { + return Err("dependency edit recovery is pending".into()); + } + let relative = manifest + .strip_prefix(root) + .map_err(|_| "manifest is outside project")?; + let manifest = relative + .to_str() + .ok_or("manifest path must be UTF-8")? + .replace('\\', "/"); + validate_path(&manifest)?; + let path = root.join(&manifest); + reject_link(&path)?; + reject_link(&root.join("vex.lock"))?; + let old = fs::read_to_string(&path).map_err(|e| e.to_string())?; + let old_lock = match fs::read_to_string(root.join("vex.lock")) { + Ok(v) => Some(v), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => None, + Err(e) => return Err(e.to_string()), + }; + let record = Record { + version: 1, + manifest, + old, + new, + new_lock: old_lock.clone(), + old_lock, + committed: false, + }; + store(root, &record)?; + replace(&path, &record.new) +} +pub fn expect_lock(root: &Path, content: String) -> Result<(), String> { + if let Some(mut record) = read(root)? { + record.new_lock = Some(content); + store(root, &record)?; + } + Ok(()) +} +pub fn commit(guard: &Guard) -> Result<(), String> { + let root = guard.root(); + let mut record = read(root)?.ok_or("missing dependency edit journal")?; + record.committed = true; + store(root, &record)?; + recover(root, false) +} +fn validate_path(path: &str) -> Result<(), String> { + if path + .split('/') + .any(|v| v.is_empty() || v == "." || v == ".." || v.contains(['\\', ':'])) + || Path::new(path).file_name().is_none_or(|v| v != "vex.ws") + { + return Err("invalid dependency edit journal path".into()); + } + Ok(()) +} +pub fn recover(root: &Path, readonly: bool) -> Result<(), String> { + let Some(record) = read(root)? else { + return Ok(()); + }; + if readonly { + return Err("dependency edit recovery pending; run vex fetch; read-only commands preserve the journal".into()); + } + if record.version != 1 { + return Err("unsupported dependency edit journal".into()); + } + validate_path(&record.manifest)?; + let path = root.join(&record.manifest); + let canonical_parent = path + .parent() + .unwrap() + .canonicalize() + .map_err(|e| e.to_string())?; + if !canonical_parent.starts_with(root) { + return Err("edit journal escapes project".into()); + } + reject_link(&path)?; + reject_link(&root.join("vex.lock"))?; + let manifest = fs::read_to_string(&path).map_err(|e| e.to_string())?; + let lock = match fs::read_to_string(root.join("vex.lock")) { + Ok(v) => Some(v), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => None, + Err(e) => return Err(e.to_string()), + }; + if (manifest != record.old && manifest != record.new) + || (lock != record.old_lock && lock != record.new_lock) + { + return Err( + "dependency edit files were modified; preserve .vex/edit.json for manual recovery" + .into(), + ); + } + if !record.committed { + replace(&path, &record.old)?; + if let Some(lock) = &record.old_lock { + replace(&root.join("vex.lock"), lock)?; + } else if lock.is_some() { + fs::remove_file(root.join("vex.lock")).map_err(|e| e.to_string())?; + sync_dir(root).map_err(|e| e.to_string())?; + } + } else if manifest != record.new || lock != record.new_lock { + return Err("committed dependency edit is incomplete; preserve journal".into()); + } + fs::remove_file(root.join(JOURNAL)).map_err(|e| e.to_string())?; + sync_dir(&root.join(".vex")).map_err(|e| e.to_string()) +} diff --git a/state/src/lib.rs b/state/src/lib.rs index dd2e067..3defc55 100644 --- a/state/src/lib.rs +++ b/state/src/lib.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 //! Project coordination. A guard is also an inheritable lease for synchronous //! Git/compiler children. Close it before spawning the user's program. use std::fs::{self, File, OpenOptions}; @@ -5,6 +9,7 @@ use std::io; use std::path::{Path, PathBuf}; pub mod artifacts; +pub mod edit; mod scaffold; pub use scaffold::initialize; @@ -66,6 +71,25 @@ impl Guard { } } +/// A persistent coordination inode, never an existence-based PID lock. +/// Callers acquire the project lease before a cache lease, never in reverse. +#[derive(Debug)] +pub struct FileGuard(File); +impl FileGuard { + pub fn exclusive(path: &Path, waiting: impl FnOnce()) -> Result { + reject_link(path)?; + let file = acquire_file(path, false, true, waiting).map_err(|e| e.to_string())?; + if !file.metadata().map_err(|e| e.to_string())?.is_file() { + return Err("coordination path must be a regular file".into()); + } + inherit(&file).map_err(|e| e.to_string())?; + Ok(Self(file)) + } + pub fn sync(&self) -> Result<(), String> { + self.0.sync_all().map_err(|e| e.to_string()) + } +} + pub fn reject_link(path: &Path) -> Result<(), String> { match fs::symlink_metadata(path) { Ok(metadata) => { diff --git a/state/src/scaffold.rs b/state/src/scaffold.rs index d367436..c65613f 100644 --- a/state/src/scaffold.rs +++ b/state/src/scaffold.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 //! Initialization publishes complete files without replacing existing entries. //! The manifest is the commit point; a durable journal owns only the new files. use crate::{atomic_rename, reject_link, sync_dir, Guard}; diff --git a/tests/build_artifact_integrity.rs b/tests/build_artifact_integrity.rs index edb82a4..0c2a33b 100644 --- a/tests/build_artifact_integrity.rs +++ b/tests/build_artifact_integrity.rs @@ -1,4 +1,9 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use serde_json::{json, Value}; +mod support; use std::fs; use std::path::PathBuf; use std::process::{Command, Output}; @@ -7,50 +12,7 @@ use std::sync::{ OnceLock, }; -const COMPILER_SOURCE: &str = r#" -use std::{env, fs, path::Path, process}; -fn quote(value: &str) -> String { - format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\"")) -} -fn main() { - let args: Vec<_> = env::args().collect(); - if args.iter().any(|arg| arg == "--version") { - println!("wavec 0.2.1-pre-beta"); - return; - } - if args.get(1).is_some_and(|arg| arg == "print") { - if args.get(2).is_some_and(|arg| arg == "supported-targets") { - println!("[\"x86_64-unknown-linux-gnu\",\"x86_64-pc-windows-msvc\"]"); - } else { - let triple = args.iter().find_map(|arg| arg.strip_prefix("--target=")) - .map(str::to_owned).unwrap_or_else(|| env::var("PLAN_TARGET").unwrap()); - let (os, format) = if triple.contains("windows") { ("windows", "coff") } else { ("linux", "elf") }; - println!("{{\"triple\":{},\"os\":{},\"object_format\":{},\"hosted\":true,\"supported\":true}}", quote(&triple), quote(os), quote(format)); - } - return; - } - if args.iter().any(|arg| arg == "--dry-run") { - println!("{}", env::var("PLAN").unwrap()); - return; - } - fs::write("compiled", "compiler started").unwrap(); - for path in env::var("OUTPUTS").unwrap_or_default().lines() { - let path = Path::new(path); - fs::create_dir_all(path.parent().unwrap()).unwrap(); - if env::var_os("DIRECTORY_OUTPUT").is_some() { - fs::create_dir(path).unwrap(); - } else { - fs::write(path, b"compiled artifact").unwrap(); - } - } - if env::var_os("FAIL_OWNERSHIP").is_some() { - fs::create_dir(".vex/artifacts.json").unwrap(); - } - let code = env::var("COMPILE_EXIT").unwrap_or_else(|_| "0".into()).parse().unwrap(); - if code != 0 { eprintln!("fixture compiler diagnostic"); } - process::exit(code); -} -"#; +const COMPILER_SOURCE: &str = include_str!("fixtures/artifact_wavec.rs"); struct Fixture { root: PathBuf, @@ -83,13 +45,7 @@ impl Fixture { let source = root.join("fake.rs"); fs::write(&source, COMPILER_SOURCE).unwrap(); let compiler = root.join(if cfg!(windows) { "wavec.exe" } else { "wavec" }); - assert!(Command::new("rustc") - .arg(source) - .arg("-o") - .arg(&compiler) - .status() - .unwrap() - .success()); + support::compile_fixture("artifact_wavec", &compiler); compiler }); let mut command = Command::new(env!("CARGO_BIN_EXE_vex")); diff --git a/tests/build_freshness.rs b/tests/build_freshness.rs new file mode 100644 index 0000000..364d59f --- /dev/null +++ b/tests/build_freshness.rs @@ -0,0 +1,270 @@ +#![cfg(target_os = "linux")] +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +mod support; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; +use std::sync::{ + atomic::{AtomicU64, Ordering}, + OnceLock, +}; +static ID: AtomicU64 = AtomicU64::new(0); +fn compiler() -> &'static Path { + static COMPILER: OnceLock = OnceLock::new(); + COMPILER.get_or_init(|| { + let root = std::env::temp_dir().join(format!("vex-fresh-compiler-{}", std::process::id())); + fs::create_dir_all(&root).unwrap(); + let path = root.join(if cfg!(windows) { + "target-wavec.exe" + } else { + "target-wavec" + }); + support::compile_fixture("target_wavec", &path); + path + }) +} +struct Fixture(PathBuf); +impl Fixture { + fn new() -> Self { + let root = std::env::temp_dir().join(format!( + "vex-ws-{}-{}", + std::process::id(), + ID.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&root).unwrap(); + let f = Self(root.canonicalize().unwrap()); + f.package( + "alpha", + "alpha", + "targets={lib={},bins=[{name=\"tool\",path=\"src/main.wave\"}]}", + ); + f.package("beta", "beta", "targets={bins=[{name=\"tool\",path=\"src/main.wave\"}]},dependencies=[{name=\"alpha\",path=\"../alpha\"}]"); + f.owner("workspace={members=[\"alpha\",\"beta\"],default_members=[\"beta\"]},profiles={fast={inherits=\"release\",opt_level=3}}"); + f + } + fn owner(&self, fields: &str) { + fs::write(self.0.join("vex.ws"), format!("{{format=4,{fields}}}")).unwrap(); + } + fn package(&self, directory: &str, name: &str, fields: &str) -> PathBuf { + let path = self.0.join(directory); + fs::create_dir_all(path.join("src/nested")).unwrap(); + for file in ["main.wave", "lib.wave"] { + fs::write(path.join("src").join(file), "fun main() {}\n").unwrap(); + } + fs::write( + path.join("vex.ws"), + format!("{{format=4,name=\"{name}\",version=\"1.0.0\",{fields}}}"), + ) + .unwrap(); + path + } + fn command(&self, cwd: &Path) -> Command { + let mut command = Command::new(env!("CARGO_BIN_EXE_vex")); + command + .current_dir(cwd) + .env("VEX_WAVEC", compiler()) + .env("TARGET_COMPILER_LOG", self.0.join("compiler.jsonl")) + .env("VEX_CACHE_HOME", self.0.join("cache")) + .env("NO_COLOR", "1"); + command + } + fn run(&self, args: &[&str]) -> Output { + self.command(&self.0).args(args).output().unwrap() + } + fn calls(&self) -> Vec> { + fs::read_to_string(self.0.join("compiler.jsonl")) + .unwrap_or_default() + .lines() + .map(|l| serde_json::from_str(l).unwrap()) + .collect() + } + fn builds(&self) -> Vec> { + self.calls() + .into_iter() + .filter(|a| a.iter().any(|a| a == "build") && !a.iter().any(|a| a == "--dry-run")) + .collect() + } +} +impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} +fn code(out: &Output, expected: i32) { + assert_eq!( + out.status.code(), + Some(expected), + "stdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); +} + +fn cache_command(f: &Fixture) -> Command { + let standard = f.0.join("standard"); + fs::create_dir_all(&standard).unwrap(); + if !standard.join("prelude.wave").exists() { + fs::write(standard.join("prelude.wave"), "// std1").unwrap(); + } + let mut command = f.command(&f.0); + command.env("TARGET_STD_PATH", standard).arg("-v"); + command +} +#[test] +fn hashes_source_dependency_std_features_profile_and_compiler_not_mtime() { + let f = Fixture::new(); + f.package("helper", "helper", r#"targets={lib={}}"#); + f.package( + "alpha", + "alpha", + r#"targets={lib={}},dependencies=[{name="helper",path="../helper"}],features={extra=[]}"#, + ); + let build = |args: &[&str]| { + let out = cache_command(&f) + .args(["-p", "alpha", "build", "--lib"]) + .args(args) + .output() + .unwrap(); + code(&out, 0); + out + }; + build(&[]); + assert_eq!(f.builds().len(), 1); + let hit = build(&[]); + assert!(String::from_utf8_lossy(&hit.stderr).contains("freshness: fresh")); + assert_eq!(f.builds().len(), 1); + let path = f.0.join("alpha/src/lib.wave"); + let bytes = fs::read(&path).unwrap(); + fs::write(&path, &bytes).unwrap(); + build(&[]); + assert_eq!(f.builds().len(), 1); + fs::write(&path, "pub fun changed() {}\n").unwrap(); + build(&[]); + assert_eq!(f.builds().len(), 2); + fs::write( + f.0.join("helper/src/lib.wave"), + "pub fun dependency_changed() {}\n", + ) + .unwrap(); + build(&[]); + assert_eq!(f.builds().len(), 3); + fs::write(f.0.join("standard/prelude.wave"), "// std2").unwrap(); + build(&[]); + assert_eq!(f.builds().len(), 4); + build(&["--features", "extra"]); + assert_eq!(f.builds().len(), 5); + build(&["--release"]); + assert_eq!(f.builds().len(), 6); + build(&["--target", "aarch64-unknown-linux-gnu"]); + assert_eq!(f.builds().len(), 7); + let changed = f.0.join("tools/target-wavec"); + fs::create_dir_all(changed.parent().unwrap()).unwrap(); + fs::copy(compiler(), &changed).unwrap(); + use std::io::Write; + fs::OpenOptions::new() + .append(true) + .open(&changed) + .unwrap() + .write_all(b"different compiler identity") + .unwrap(); + code( + &cache_command(&f) + .env("VEX_WAVEC", changed) + .args(["-p", "alpha", "build", "--lib"]) + .output() + .unwrap(), + 0, + ); + assert_eq!(f.builds().len(), 8); +} +#[test] +fn corrupt_or_partial_cache_is_a_miss_and_cleanup_owns_cache_files() { + let f = Fixture::new(); + f.package("alpha", "alpha", r#"targets={lib={}}"#); + let build = || { + code( + &cache_command(&f) + .args(["-p", "alpha", "build"]) + .output() + .unwrap(), + 0, + ); + }; + build(); + assert_eq!(f.builds().len(), 1); + let entry = fs::read_dir(f.0.join("target/.vex-cache")) + .unwrap() + .next() + .unwrap() + .unwrap() + .path(); + fs::write(entry.join("0"), "corrupted").unwrap(); + build(); + assert_eq!(f.builds().len(), 2); + assert_eq!(fs::read(entry.join("0")).unwrap(), b"corrupted"); + fs::write(entry.join("record.json"), "{").unwrap(); + build(); + assert_eq!(f.builds().len(), 3); + // Modified cache files are preserved by clean, alongside ordinary ownership rules. + code(&f.run(&["clean"]), 0); + assert!(entry.join("0").exists()); +} +#[test] +fn unknown_hosted_link_inputs_always_rebuild() { + let f = Fixture::new(); + for _ in 0..2 { + code( + &cache_command(&f) + .args(["-p", "beta", "build"]) + .output() + .unwrap(), + 0, + ); + } + assert_eq!(f.builds().len(), 2); +} + +#[test] +fn reused_run_artifacts_have_independent_inodes_and_program_always_executes() { + let f = Fixture::new(); + f.package( + "alpha", + "alpha", + r#"targets={lib={},bins=[{name="tool",path="src/main.wave"}]}"#, + ); + for _ in 0..2 { + let out = cache_command(&f) + .env("TARGET_LINK_PROGRAM", compiler()) + .env("TARGET_PROGRAM_EXIT", "0") + .env("TARGET_PROGRAM_LOG", f.0.join("runs")) + .args(["-p", "alpha", "run", "--target", "wasm32-unknown-unknown"]) + .output() + .unwrap(); + code(&out, 0); + } + assert_eq!(f.builds().len(), 1); + assert_eq!( + fs::read_to_string(f.0.join("runs")).unwrap(), + "tool\ntool\n" + ); + let paths = fs::read_dir(f.0.join("target/.vex-run")) + .unwrap() + .map(|e| { + e.unwrap() + .path() + .join("wasm32-unknown-unknown/dev/packages/alpha/bin/tool.wasm") + }) + .collect::>(); + assert_eq!(paths.len(), 2); + use std::os::unix::fs::MetadataExt; + assert_ne!( + fs::metadata(&paths[0]).unwrap().ino(), + fs::metadata(&paths[1]).unwrap().ino() + ); + let original = fs::read(&paths[1]).unwrap(); + fs::write(&paths[0], "changed old generation").unwrap(); + assert_eq!(fs::read(&paths[1]).unwrap(), original); +} diff --git a/tests/clean.rs b/tests/clean.rs index 4cb176b..af84d6d 100644 --- a/tests/clean.rs +++ b/tests/clean.rs @@ -1,3 +1,8 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +mod support; use std::fs; use std::io::{Read, Write}; use std::net::{TcpListener, TcpStream}; @@ -33,13 +38,7 @@ impl Fixture { fs::create_dir_all(&root).unwrap(); fs::write(root.join("fake.rs"), include_str!("fixtures/fake_wavec.rs")).unwrap(); let executable = root.join(if cfg!(windows) { "wavec.exe" } else { "wavec" }); - assert!(Command::new("rustc") - .arg(root.join("fake.rs")) - .arg("-o") - .arg(&executable) - .status() - .unwrap() - .success()); + support::compile_fixture("fake_wavec", &executable); executable }); let mut command = Command::new(env!("CARGO_BIN_EXE_vex")); diff --git a/tests/dependency_edit.rs b/tests/dependency_edit.rs new file mode 100644 index 0000000..c57ea2d --- /dev/null +++ b/tests/dependency_edit.rs @@ -0,0 +1,190 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +use std::{ + fs, + path::PathBuf, + process::{Command, Output}, + sync::atomic::{AtomicU64, Ordering}, +}; +static NEXT: AtomicU64 = AtomicU64::new(0); +struct F(PathBuf); +impl F { + fn new() -> Self { + let root = std::env::temp_dir().join(format!( + "vex-edit-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&root).unwrap(); + let f = Self(root); + f.cmd() + .args(["new", "app"]) + .output() + .map(|o| check(o, 0)) + .unwrap(); + f.cmd() + .args(["new", "dep", "--lib"]) + .output() + .map(|o| check(o, 0)) + .unwrap(); + f + } + fn cmd(&self) -> Command { + let mut c = Command::new(env!("CARGO_BIN_EXE_vex")); + c.current_dir(&self.0) + .env("VEX_CACHE_HOME", self.0.join("cache")); + c + } + fn app(&self) -> Command { + let mut c = self.cmd(); + c.current_dir(self.0.join("app")); + c + } + fn pair(&self) -> (String, String) { + ( + fs::read_to_string(self.0.join("app/vex.ws")).unwrap(), + fs::read_to_string(self.0.join("app/vex.lock")).unwrap(), + ) + } +} +impl Drop for F { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} +fn check(out: Output, code: i32) { + assert_eq!( + out.status.code(), + Some(code), + "{}\n{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); +} +#[test] +fn add_remove_preserve_comments_and_restore_failed_resolution() { + let f = F::new(); + let (raw, _) = f.pair(); + let raw = raw.replace("dependencies = []", "dependencies = [ /*owned comment*/ ]"); + fs::write(f.0.join("app/vex.ws"), &raw).unwrap(); + check( + f.app() + .args(["add", "dep", "--path", "../dep", "--offline"]) + .output() + .unwrap(), + 0, + ); + assert!(f.pair().0.contains("/*owned comment*/")); + check( + f.app() + .args(["fetch", "--locked", "--offline"]) + .output() + .unwrap(), + 0, + ); + let pair = f.pair(); + check( + f.app() + .args(["add", "missing", "--path", "../missing", "--offline"]) + .output() + .unwrap(), + 5, + ); + assert_eq!(pair, f.pair()); + check( + f.app() + .args(["remove", "dep", "--offline"]) + .output() + .unwrap(), + 0, + ); + assert_eq!(f.pair().0.replace("\n \n ", ""), raw); + check(f.app().args(["remove", "dep"]).output().unwrap(), 3); +} +#[test] +fn crash_recovery_is_readonly_until_normal_command() { + for phase in ["VEX_TEST_EDIT_CRASH_MANIFEST", "VEX_TEST_EDIT_CRASH_LOCK"] { + let f = F::new(); + let pair = f.pair(); + check( + f.app() + .env(phase, "1") + .args(["add", "dep", "--path", "../dep", "--offline"]) + .output() + .unwrap(), + 99, + ); + let modified = f.pair(); + check( + f.app() + .args(["metadata", "--format-version", "2"]) + .output() + .unwrap(), + 5, + ); + assert_eq!(modified, f.pair()); + check(f.app().args(["fetch", "--offline"]).output().unwrap(), 0); + assert_eq!(pair, f.pair()); + assert!(!f.0.join("app/.vex/edit.json").exists()); + } +} +#[test] +fn new_rejects_invalid_existing_and_preserves_unicode_destination() { + let f = F::new(); + check(f.cmd().args(["new", "invalid-name"]).output().unwrap(), 2); + assert!(!f.0.join("invalid-name").exists()); + check(f.cmd().args(["new", "app"]).output().unwrap(), 5); + check( + f.cmd() + .args(["new", "유니코드", "--name", "portable"]) + .output() + .unwrap(), + 0, + ); + assert!(f.0.join("유니코드/vex.ws").is_file()); + assert!(!f.0.join("유니코드/.git").exists()); + check( + f.cmd().args(["new", "git_app", "--git"]).output().unwrap(), + 0, + ); + assert!(f.0.join("git_app/.git").is_dir()); +} + +#[test] +fn cache_dry_run_preserves_message_file_contract() { + let f = F::new(); + check( + f.app() + .args([ + "--message-file", + "preview.jsonl", + "cache", + "prune", + "--dry-run", + ]) + .output() + .unwrap(), + 0, + ); + assert!(!f.0.join("app/preview.jsonl").exists()); + fs::write(f.0.join("app/preview.jsonl"), "existing").unwrap(); + check( + f.app() + .args([ + "--message-file", + "preview.jsonl", + "cache", + "prune", + "--dry-run", + ]) + .output() + .unwrap(), + 5, + ); + assert_eq!( + fs::read_to_string(f.0.join("app/preview.jsonl")).unwrap(), + "existing" + ); +} diff --git a/tests/doctor.rs b/tests/doctor.rs index 8c4f4ed..a7d73e0 100644 --- a/tests/doctor.rs +++ b/tests/doctor.rs @@ -1,4 +1,9 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use serde_json::{json, Value}; +mod support; use std::collections::BTreeMap; use std::fs; use std::path::{Path, PathBuf}; @@ -106,50 +111,9 @@ fn fake() -> &'static Path { let root = std::env::temp_dir().join(format!("vex-doctor-tools-{}", std::process::id())); fs::create_dir_all(&root).unwrap(); let source = root.join("fake.rs"); - fs::write(&source, r###" -use std::{env, fs::OpenOptions, io::Write}; -fn main() { - let args: Vec<_> = env::args().skip(1).collect(); - let kind = env::current_exe().unwrap().file_stem().unwrap().to_string_lossy().into_owned(); - if let Ok(path) = env::var("DOCTOR_LOG") { - writeln!(OpenOptions::new().create(true).append(true).open(path).unwrap(), "{kind}:{}", args.join(" ")).unwrap(); - } - if kind == "git" { - assert_eq!(args, ["--version"], "doctor must never fetch or access a remote"); - println!("git version 2.48.0"); return; - } - if args == ["--version"] { - assert!(env::var_os("NO_COLOR").is_some()); - println!("wavec 0.2.1-pre-beta"); return; - } - if args == ["print", "supported-targets", "--format=json"] { - println!("{}", env::var("DOCTOR_TARGETS").unwrap()); return; - } - let target = args.iter().find_map(|s| s.strip_prefix("--target=")).map(str::to_owned) - .unwrap_or_else(|| env::var("DOCTOR_HOST_TARGET").unwrap()); - if args.first().map(String::as_str) == Some("print") && args.get(1).map(String::as_str) == Some("target-spec") { - println!("{{\"triple\":{target:?},\"supported\":true,\"hosted\":true,\"object_format\":\"elf\",\"os\":\"linux\"}}"); return; - } - assert!(args.iter().any(|s| s == "--dry-run"), "doctor must not compile"); - assert!(!args.iter().any(|s| s == "--run"), "doctor must not run"); - if let Ok(error) = env::var("DOCTOR_ERROR") { eprintln!("{error}"); std::process::exit(env::var("DOCTOR_EXIT").ok().and_then(|s| s.parse().ok()).unwrap_or(1)); } - let schema = env::var("DOCTOR_SCHEMA").unwrap_or_else(|_| "1".into()); - let requested_output = args.windows(2).find(|pair| pair[0] == "-o").map(|pair| pair[1].clone()).unwrap_or_else(|| "target/main".into()); - let link_output = env::var("DOCTOR_LINK_OUTPUT").unwrap_or(requested_output.clone()); - let object = args.iter().any(|arg| arg == "--emit=obj"); - let emit = if object { "obj" } else { "bin" }; - let program = env::var("DOCTOR_LINK").unwrap_or_else(|_| env::current_exe().unwrap().to_string_lossy().into_owned()); - let link = if object { "null".into() } else { - format!("{{\"output\":{link_output:?},\"inputs\":[],\"program\":{program:?},\"args\":[]}}") - }; - let compile = if object { - format!("[{{\"input\":\"src/lib.wave\",\"kind\":\"wave\",\"output\":{requested_output:?},\"command\":\"wavec\"}}]") - } else { "[]".into() }; - println!("{{\"schema_version\":{schema},\"mode\":\"build\",\"target\":{target:?},\"emit\":{emit:?},\"emit_kinds\":[],\"control_mode\":null,\"forced_input_type\":null,\"inputs\":[],\"emit_jobs\":[],\"compile\":{compile},\"link\":{link},\"execute\":null}}"); -} -"###).unwrap(); + fs::write(&source, include_str!("fixtures/doctor_tools.rs")).unwrap(); let path = root.join(exe("fake")); - assert!(Command::new("rustc").args(["--edition=2021"]).arg(&source).arg("-o").arg(&path).status().unwrap().success()); + support::compile_fixture("doctor_tools", &path); path }) } diff --git a/tests/executable_tests.rs b/tests/executable_tests.rs new file mode 100644 index 0000000..cf8358e --- /dev/null +++ b/tests/executable_tests.rs @@ -0,0 +1,220 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +use serde_json::Value; +mod support; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; +use std::sync::{ + atomic::{AtomicU64, Ordering}, + OnceLock, +}; +static ID: AtomicU64 = AtomicU64::new(0); +fn compiler() -> &'static Path { + static COMPILER: OnceLock = OnceLock::new(); + COMPILER.get_or_init(|| { + let root = std::env::temp_dir().join(format!("vex-ws-compiler-{}", std::process::id())); + fs::create_dir_all(&root).unwrap(); + let path = root.join(if cfg!(windows) { + "target-wavec.exe" + } else { + "target-wavec" + }); + support::compile_fixture("target_wavec", &path); + path + }) +} +struct Fixture(PathBuf); +impl Fixture { + fn new() -> Self { + let root = std::env::temp_dir().join(format!( + "vex-ws-{}-{}", + std::process::id(), + ID.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&root).unwrap(); + let f = Self(root.canonicalize().unwrap()); + f.package( + "alpha", + "alpha", + "targets={lib={},bins=[{name=\"tool\",path=\"src/main.wave\"}]}", + ); + f.package("beta", "beta", "targets={bins=[{name=\"tool\",path=\"src/main.wave\"}]},dependencies=[{name=\"alpha\",path=\"../alpha\"}]"); + f.owner("workspace={members=[\"alpha\",\"beta\"],default_members=[\"beta\"]},profiles={fast={inherits=\"release\",opt_level=3}}"); + f + } + fn owner(&self, fields: &str) { + fs::write(self.0.join("vex.ws"), format!("{{format=4,{fields}}}")).unwrap(); + } + fn package(&self, directory: &str, name: &str, fields: &str) -> PathBuf { + let path = self.0.join(directory); + fs::create_dir_all(path.join("src/nested")).unwrap(); + for file in ["main.wave", "lib.wave"] { + fs::write(path.join("src").join(file), "fun main() {}\n").unwrap(); + } + fs::write( + path.join("vex.ws"), + format!("{{format=4,name=\"{name}\",version=\"1.0.0\",{fields}}}"), + ) + .unwrap(); + path + } + fn command(&self, cwd: &Path) -> Command { + let mut command = Command::new(env!("CARGO_BIN_EXE_vex")); + command + .current_dir(cwd) + .env("VEX_WAVEC", compiler()) + .env("TARGET_COMPILER_LOG", self.0.join("compiler.jsonl")) + .env("VEX_CACHE_HOME", self.0.join("cache")) + .env("NO_COLOR", "1"); + command + } + fn run(&self, args: &[&str]) -> Output { + self.command(&self.0).args(args).output().unwrap() + } + fn metadata(&self, cwd: &Path, options: &[&str]) -> Value { + let mut args = vec!["metadata", "--format-version", "2", "--locked"]; + args.extend_from_slice(options); + let out = self.command(cwd).args(args).output().unwrap(); + code(&out, 0); + serde_json::from_slice(&out.stdout).unwrap() + } + fn calls(&self) -> Vec> { + fs::read_to_string(self.0.join("compiler.jsonl")) + .unwrap_or_default() + .lines() + .map(|l| serde_json::from_str(l).unwrap()) + .collect() + } + fn builds(&self) -> Vec> { + self.calls() + .into_iter() + .filter(|a| a.iter().any(|a| a == "build")) + .collect() + } +} +impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} +fn code(out: &Output, expected: i32) { + assert_eq!( + out.status.code(), + Some(expected), + "stdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); +} +#[test] +fn executes_all_tests_and_keeps_first_program_failure_and_results() { + let f = Fixture::new(); + f.package("alpha","alpha",r#"targets={lib={},tests=[{name="zeta",path="src/main.wave"},{name="alpha",path="src/main.wave"}]}"#); + let out = f + .command(&f.0) + .env("TARGET_PROGRAM_EXIT_MAP", "alpha=7,zeta=9") + .env("TARGET_PROGRAM_LOG", f.0.join("runs")) + .args(["-p", "alpha", "--message-file", "results.jsonl", "test"]) + .output() + .unwrap(); + code(&out, 7); + assert!(String::from_utf8_lossy(&out.stderr).contains("test alpha::alpha ... FAILED (exit 7)")); + assert_eq!( + fs::read_to_string(f.0.join("runs")).unwrap(), + "alpha\nzeta\n" + ); + let records = fs::read_to_string(f.0.join("results.jsonl")) + .unwrap() + .lines() + .map(|l| serde_json::from_str::(l).unwrap()) + .collect::>(); + let results = records + .iter() + .filter(|e| e["event"] == "test_result") + .collect::>(); + assert_eq!(results.len(), 2); + assert_eq!(results[0]["exit_code"], 7); + assert_eq!(results[1]["exit_code"], 9); + assert_eq!(records.last().unwrap()["origin"], "program"); + fs::remove_file(f.0.join("runs")).unwrap(); + code( + &f.command(&f.0) + .env("TARGET_PROGRAM_EXIT", "0") + .env("TARGET_PROGRAM_LOG", f.0.join("runs")) + .args([ + "--quiet", + "-p", + "alpha", + "test", + "zet", + "--locked", + "--offline", + ]) + .output() + .unwrap(), + 0, + ); + assert_eq!(fs::read_to_string(f.0.join("runs")).unwrap(), "zeta\n"); +} +#[test] +fn test_dependencies_are_locked_but_not_built_or_propagated_normally() { + let f = Fixture::new(); + f.package("helper", "helper", r#"targets={lib={}}"#); + f.package("alpha","alpha",r#"targets={lib={},tests=[{name="smoke",path="src/main.wave"}]},test_dependencies=[{name="helper",path="../helper"}]"#); + code(&f.run(&["-p", "alpha", "fetch"]), 0); + let lock = fs::read(f.0.join("vex.lock")).unwrap(); + let normal = f.metadata(&f.0, &["-p", "alpha"]); + assert_eq!(normal["packages"].as_array().unwrap().len(), 0); + let tests = f.metadata(&f.0, &["-p", "alpha", "--include-tests"]); + assert_eq!(tests["packages"].as_array().unwrap().len(), 1); + let out = f + .command(&f.0) + .env("TARGET_PROGRAM_EXIT", "0") + .args(["-p", "alpha", "test", "--locked", "--offline"]) + .output() + .unwrap(); + code(&out, 0); + assert_eq!(fs::read(f.0.join("vex.lock")).unwrap(), lock); + assert!(f + .builds() + .iter() + .any(|args| args.iter().any(|s| s.starts_with("--dep=helper=")))); +} +#[test] +fn dry_run_and_late_logging_failure_do_not_run_early_or_replace_program_code() { + let f = Fixture::new(); + f.package("alpha","alpha",r#"targets={lib={},tests=[{name="one",path="src/main.wave"},{name="two",path="src/main.wave"}]}"#); + code(&f.run(&["-p", "alpha", "fetch"]), 0); + code( + &f.command(&f.0) + .args([ + "-p", + "alpha", + "--message-file", + "absent.jsonl", + "test", + "--dry-run", + ]) + .output() + .unwrap(), + 0, + ); + assert!(!f.0.join("absent.jsonl").exists()); + assert!(f + .builds() + .iter() + .all(|args| args.iter().any(|arg| arg == "--dry-run"))); + let out = f + .command(&f.0) + .env("TARGET_PROGRAM_EXIT", "8") + .env("TARGET_PROGRAM_LOG", f.0.join("runs")) + .env("VEX_TEST_MESSAGE_FAIL_EVENT", "test_result") + .args(["-p", "alpha", "--message-file", "broken.jsonl", "test"]) + .output() + .unwrap(); + code(&out, 8); + assert_eq!(fs::read_to_string(f.0.join("runs")).unwrap(), "one\ntwo\n"); +} diff --git a/tests/feature_graph.rs b/tests/feature_graph.rs new file mode 100644 index 0000000..4ddb034 --- /dev/null +++ b/tests/feature_graph.rs @@ -0,0 +1,194 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; +use std::sync::atomic::{AtomicU64, Ordering}; +static ID: AtomicU64 = AtomicU64::new(0); +struct Fixture(PathBuf); +impl Fixture { + fn new() -> Self { + let path = std::env::temp_dir().join(format!( + "vex-features-{}-{}", + std::process::id(), + ID.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&path).unwrap(); + Self(path) + } + fn package(&self, directory: &str, name: &str, version: &str, fields: &str) -> PathBuf { + let path = self.0.join(directory); + fs::create_dir_all(path.join("src")).unwrap(); + fs::write(path.join("src/lib.wave"), "pub fun marker() {}\n").unwrap(); + fs::write( + path.join("vex.ws"), + format!( + "{{format=4,name=\"{name}\",version=\"{version}\",targets={{lib={{}}}},{fields}}}" + ), + ) + .unwrap(); + path + } + fn vex(&self, project: &Path, args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_vex")) + .current_dir(project) + .env("VEX_CACHE_HOME", self.0.join("cache")) + .args(args) + .output() + .unwrap() + } + fn metadata(&self, project: &Path, options: &[&str]) -> serde_json::Value { + let mut args = vec!["metadata", "--format-version", "2", "--locked", "--offline"]; + args.extend_from_slice(options); + let out = self.vex(project, &args); + success(&out); + serde_json::from_slice(&out.stdout).unwrap() + } +} +impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} +fn success(out: &Output) { + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); +} +fn git(path: &Path, args: &[&str]) { + let out = Command::new("git") + .current_dir(path) + .args([ + "-c", + "user.name=Vex Test", + "-c", + "user.email=test@example.invalid", + ]) + .args(args) + .output() + .unwrap(); + success(&out); +} +mod support; +#[test] +fn target_union_locks_local_git_sources_and_switches_offline_without_writes() { + let f = Fixture::new(); + let one = f.package("one", "platform", "1.0.0", "dependencies=[]"); + let two = f.package("two", "platform", "2.0.0", "dependencies=[]"); + for source in [&one, &two] { + git(source, &["init", "--initial-branch=master"]); + git(source, &["add", "."]); + git(source, &["commit", "-m", "fixture"]); + } + let app = f.package("app", "app", "1.0.0", &format!("dependencies=[{{name=\"platform\",git=\"{}\",target={{os=\"linux\"}}}},{{name=\"platform\",git=\"{}\",target={{os=\"windows\"}}}}]", support::git_url(&one), support::git_url(&two))); + success(&f.vex(&app, &["fetch", "--target", "x86_64-unknown-linux-gnu"])); + let lock = fs::read(app.join("vex.lock")).unwrap(); + assert_eq!( + lockfile::decode(std::str::from_utf8(&lock).unwrap()) + .unwrap() + .packages + .len(), + 2 + ); + fs::rename(&one, one.with_extension("hidden")).unwrap(); + fs::rename(&two, two.with_extension("hidden")).unwrap(); + for (triple, version) in [ + ("x86_64-unknown-linux-gnu", "1.0.0"), + ("aarch64-pc-windows-msvc", "2.0.0"), + ] { + success(&f.vex( + &app, + &["fetch", "--target", triple, "--offline", "--locked"], + )); + let value = f.metadata(&app, &["--target", triple]); + assert_eq!(value["packages"].as_array().unwrap().len(), 1); + assert_eq!(value["packages"][0]["version"], version); + assert_eq!(value["union_bindings"].as_array().unwrap().len(), 2); + assert_eq!(value["selection"]["target"]["triple"], triple); + assert_eq!(fs::read(app.join("vex.lock")).unwrap(), lock); + } +} +#[test] +fn optional_defaults_transitive_forwarding_and_disabled_defaults_are_reproducible() { + let f = Fixture::new(); + f.package("leaf", "leaf", "1.0.0", "dependencies=[]"); + f.package("opt", "opt", "1.0.0", "dependencies=[{name=\"leaf\",path=\"../leaf\",optional=true}],features={extra=[\"dep:leaf\"]}"); + let app = f.package("app", "app", "1.0.0", "dependencies=[{name=\"opt\",path=\"../opt\",optional=true,default_features=false}],features={default=[\"fast\"],fast=[\"dep:opt\",\"opt/extra\"]}"); + success(&f.vex(&app, &["fetch", "--no-default-features"])); + let lock = fs::read(app.join("vex.lock")).unwrap(); + assert_eq!( + lockfile::decode(std::str::from_utf8(&lock).unwrap()) + .unwrap() + .packages + .len(), + 2 + ); + assert!(f.metadata(&app, &["--no-default-features"])["packages"] + .as_array() + .unwrap() + .is_empty()); + for flags in [vec![], vec!["--no-default-features", "--features", "fast"]] { + let value = f.metadata(&app, &flags); + assert_eq!(value["packages"].as_array().unwrap().len(), 2); + assert!(value["selected_features"] + .as_object() + .unwrap() + .values() + .any(|v| v.as_array().unwrap().contains(&serde_json::json!("extra")))); + assert_eq!(fs::read(app.join("vex.lock")).unwrap(), lock); + } +} +#[test] +fn aliases_of_one_concrete_package_unify_additive_features() { + let f = Fixture::new(); + for name in ["x", "y"] { + f.package(name, name, "1.0.0", "dependencies=[]"); + } + f.package("shared", "shared", "1.0.0", "dependencies=[{name=\"x\",path=\"../x\",optional=true},{name=\"y\",path=\"../y\",optional=true}],features={first=[\"dep:x\"],second=[\"dep:y\"]}"); + let app = f.package("app", "app", "1.0.0", "dependencies=[{name=\"one\",package=\"shared\",path=\"../shared\",features=[\"first\"],default_features=false},{name=\"two\",package=\"shared\",path=\"../shared\",features=[\"second\"],default_features=false}]"); + success(&f.vex(&app, &["fetch"])); + let value = f.metadata(&app, &[]); + let packages = value["packages"].as_array().unwrap(); + assert!(packages.iter().any(|v| v["name"] == "x")); + assert!(packages.iter().any(|v| v["name"] == "y")); + let shared: Vec<_> = packages.iter().filter(|v| v["name"] == "shared").collect(); + assert_eq!(shared.len(), 2); + assert_eq!(shared[0]["id"], shared[1]["id"]); + assert_eq!(shared[0]["dependencies"], shared[1]["dependencies"]); +} +#[test] +fn overlapping_predicates_and_unknown_features_never_publish_state() { + let f = Fixture::new(); + f.package("one", "lib", "1.0.0", "dependencies=[]"); + f.package("two", "lib", "2.0.0", "dependencies=[]"); + let app = f.package("app", "app", "1.0.0", "dependencies=[{name=\"lib\",path=\"../one\",target={os=\"linux\"}},{name=\"lib\",path=\"../two\",target={arch=\"x86_64\"}}]"); + let out = f.vex(&app, &["fetch", "--target", "x86_64-unknown-linux-gnu"]); + assert_eq!(out.status.code(), Some(3)); + assert!(String::from_utf8_lossy(&out.stderr).contains("multiple active")); + assert!(!app.join("vex.lock").exists()); + let out = f.vex(&app, &["fetch", "--features", "typo"]); + assert_eq!(out.status.code(), Some(3)); + assert!(String::from_utf8_lossy(&out.stderr).contains("unknown package feature")); + assert!(!app.join("vex.lock").exists()); + let untouched = f.package("untouched", "untouched", "1.0.0", "dependencies=[]"); + let out = f.vex(&untouched, &["fetch", "--features", "typo"]); + assert_eq!(out.status.code(), Some(3)); + assert!(!untouched.join(".vex").exists()); +} +#[test] +fn malformed_union_edges_fail_before_checkout_publication() { + let f = Fixture::new(); + let app = f.package("app", "app", "1.0.0", "dependencies=[]"); + success(&f.vex(&app, &["fetch"])); + let raw = fs::read_to_string(app.join("vex.lock")).unwrap().replace("edges = []", "edges = [{key=\"missing\",alias=\"missing\",optional=false,default_features=true,features=[],target=null}]"); + assert!(lockfile::decode(&raw).is_err()); + fs::write(app.join("vex.lock"), &raw).unwrap(); + let out = f.vex(&app, &["fetch", "--locked"]); + assert_eq!(out.status.code(), Some(3)); + assert_eq!(fs::read_to_string(app.join("vex.lock")).unwrap(), raw); + assert!(!app.join(".vex/transactions").exists()); +} diff --git a/tests/fixtures/artifact_wavec.rs b/tests/fixtures/artifact_wavec.rs new file mode 100644 index 0000000..d7aa043 --- /dev/null +++ b/tests/fixtures/artifact_wavec.rs @@ -0,0 +1,47 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 + +use std::{env, fs, path::Path, process}; +fn quote(value: &str) -> String { + format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\"")) +} +fn main() { + let args: Vec<_> = env::args().collect(); + if args.iter().any(|arg| arg == "--version") { + println!("wavec 0.2.1-pre-beta"); + return; + } + if args.get(1).is_some_and(|arg| arg == "print") { + if args.get(2).is_some_and(|arg| arg == "supported-targets") { + println!("[\"x86_64-unknown-linux-gnu\",\"x86_64-pc-windows-msvc\"]"); + } else { + let triple = args.iter().find_map(|arg| arg.strip_prefix("--target=")) + .map(str::to_owned).unwrap_or_else(|| env::var("PLAN_TARGET").unwrap()); + let (os, format) = if triple.contains("windows") { ("windows", "coff") } else { ("linux", "elf") }; + println!("{{\"triple\":{},\"os\":{},\"object_format\":{},\"hosted\":true,\"supported\":true}}", quote(&triple), quote(os), quote(format)); + } + return; + } + if args.iter().any(|arg| arg == "--dry-run") { + println!("{}", env::var("PLAN").unwrap()); + return; + } + fs::write("compiled", "compiler started").unwrap(); + for path in env::var("OUTPUTS").unwrap_or_default().lines() { + let path = Path::new(path); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + if env::var_os("DIRECTORY_OUTPUT").is_some() { + fs::create_dir(path).unwrap(); + } else { + fs::write(path, b"compiled artifact").unwrap(); + } + } + if env::var_os("FAIL_OWNERSHIP").is_some() { + fs::create_dir(".vex/artifacts.json").unwrap(); + } + let code = env::var("COMPILE_EXIT").unwrap_or_else(|_| "0".into()).parse().unwrap(); + if code != 0 { eprintln!("fixture compiler diagnostic"); } + process::exit(code); +} diff --git a/tests/fixtures/doctor_tools.rs b/tests/fixtures/doctor_tools.rs new file mode 100644 index 0000000..3beb88a --- /dev/null +++ b/tests/fixtures/doctor_tools.rs @@ -0,0 +1,45 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 + +use std::{env, fs::OpenOptions, io::Write}; +fn main() { + let args: Vec<_> = env::args().skip(1).collect(); + let kind = env::current_exe().unwrap().file_stem().unwrap().to_string_lossy().into_owned(); + if let Ok(path) = env::var("DOCTOR_LOG") { + writeln!(OpenOptions::new().create(true).append(true).open(path).unwrap(), "{kind}:{}", args.join(" ")).unwrap(); + } + if kind == "git" { + assert_eq!(args, ["--version"], "doctor must never fetch or access a remote"); + println!("git version 2.48.0"); return; + } + if args == ["--version"] { + assert!(env::var_os("NO_COLOR").is_some()); + println!("wavec 0.2.1-pre-beta"); return; + } + if args == ["print", "supported-targets", "--format=json"] { + println!("{}", env::var("DOCTOR_TARGETS").unwrap()); return; + } + let target = args.iter().find_map(|s| s.strip_prefix("--target=")).map(str::to_owned) + .unwrap_or_else(|| env::var("DOCTOR_HOST_TARGET").unwrap()); + if args.first().map(String::as_str) == Some("print") && args.get(1).map(String::as_str) == Some("target-spec") { + println!("{{\"triple\":{target:?},\"supported\":true,\"hosted\":true,\"object_format\":\"elf\",\"os\":\"linux\"}}"); return; + } + assert!(args.iter().any(|s| s == "--dry-run"), "doctor must not compile"); + assert!(!args.iter().any(|s| s == "--run"), "doctor must not run"); + if let Ok(error) = env::var("DOCTOR_ERROR") { eprintln!("{error}"); std::process::exit(env::var("DOCTOR_EXIT").ok().and_then(|s| s.parse().ok()).unwrap_or(1)); } + let schema = env::var("DOCTOR_SCHEMA").unwrap_or_else(|_| "1".into()); + let requested_output = args.windows(2).find(|pair| pair[0] == "-o").map(|pair| pair[1].clone()).unwrap_or_else(|| "target/main".into()); + let link_output = env::var("DOCTOR_LINK_OUTPUT").unwrap_or(requested_output.clone()); + let object = args.iter().any(|arg| arg == "--emit=obj"); + let emit = if object { "obj" } else { "bin" }; + let program = env::var("DOCTOR_LINK").unwrap_or_else(|_| env::current_exe().unwrap().to_string_lossy().into_owned()); + let link = if object { "null".into() } else { + format!("{{\"output\":{link_output:?},\"inputs\":[],\"program\":{program:?},\"args\":[]}}") + }; + let compile = if object { + format!("[{{\"input\":\"src/lib.wave\",\"kind\":\"wave\",\"output\":{requested_output:?},\"command\":\"wavec\"}}]") + } else { "[]".into() }; + println!("{{\"schema_version\":{schema},\"mode\":\"build\",\"target\":{target:?},\"emit\":{emit:?},\"emit_kinds\":[],\"control_mode\":null,\"forced_input_type\":null,\"inputs\":[],\"emit_jobs\":[],\"compile\":{compile},\"link\":{link},\"execute\":null}}"); +} diff --git a/tests/fixtures/fake_wavec.rs b/tests/fixtures/fake_wavec.rs index 7aa7536..d87d55f 100644 --- a/tests/fixtures/fake_wavec.rs +++ b/tests/fixtures/fake_wavec.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 // Standalone process fixture: rustc compiles this without Cargo dependencies. use std::env; use std::fs::{self, OpenOptions}; @@ -41,7 +45,7 @@ fn main() { let mut line = String::new(); std::io::stdin().read_line(&mut line).unwrap(); print!("PROGRAM_STDIN:{line}"); eprintln!("PROGRAM_STDERR"); } - println!("PROGRAM_CWD:{:?}", env::current_dir().unwrap()); + println!("PROGRAM_CWD:{:?}", env::current_dir().unwrap().canonicalize().unwrap()); #[cfg(unix)] if env::var_os("VEX_TEST_ARGUMENT_BYTES").is_some() { use std::os::unix::ffi::OsStrExt; @@ -65,6 +69,7 @@ fn main() { println!("{{\"triple\":{target:?},\"os\":{os:?},\"object_format\":{format:?},\"hosted\":true,\"supported\":true}}"); return; } + if args.get(1).is_some_and(|s|s=="std-path") { println!("null"); return; } assert_eq!(args, ["print", "supported-targets", "--format=json"]); println!("{}", env::var("FAKE_TARGETS").unwrap_or_else(|_| "[\"x86_64-unknown-linux-gnu\",\"aarch64-unknown-linux-gnu\"]".into())); return; diff --git a/tests/fixtures/native_wavec.rs b/tests/fixtures/native_wavec.rs new file mode 100644 index 0000000..5a2632c --- /dev/null +++ b/tests/fixtures/native_wavec.rs @@ -0,0 +1,74 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 + +use std::{env, fs, io::Write, path::PathBuf}; +fn quote(value: &str) -> String { + let mut text = String::from("\""); + for ch in value.chars() { + match ch { + '\\' => text.push_str("\\\\"), '"' => text.push_str("\\\""), + '\n' => text.push_str("\\n"), '\r' => text.push_str("\\r"), + '\t' => text.push_str("\\t"), + c if c.is_control() => text.push_str(&format!("\\u{:04x}", c as u32)), + c => text.push(c), + } + } + text.push('"'); text +} +fn list(values: &[String]) -> String { + format!("[{}]", values.iter().map(|s| quote(s)).collect::>().join(",")) +} +fn main() { + let args: Vec<_> = env::args().skip(1).collect(); + if !env::current_exe().unwrap().file_stem().unwrap().to_string_lossy().starts_with("fake-native-wavec") { + fs::write("program-started", list(&args)).unwrap(); + println!("native fixture program"); + std::process::exit(17); + } + if let Some(path) = env::var_os("NATIVE_COMPILER_LOG") { + let mut log = fs::OpenOptions::new().create(true).append(true).open(path).unwrap(); + writeln!(log, "{}", list(&args)).unwrap(); + } + if args.iter().any(|s| s == "--version") { println!("wavec 0.2.1-pre-beta"); return; } + let value = |flag: &str| args.iter().find_map(|s| s.strip_prefix(&format!("{flag}=")).map(str::to_owned)) + .or_else(|| args.iter().position(|s| s == flag).and_then(|i| args.get(i+1).cloned())); + let target = value("--target").unwrap_or_else(|| env::var("NATIVE_DEFAULT_TARGET").unwrap_or_else(|_| "x86_64-unknown-linux-gnu".into())); + if args.first().is_some_and(|s| s == "print") { + if args.get(1).is_some_and(|s| s == "supported-targets") { + println!("[\"x86_64-unknown-linux-gnu\",\"aarch64-unknown-linux-gnu\",\"x86_64-pc-windows-msvc\",\"aarch64-pc-windows-msvc\",\"x86_64-apple-darwin\",\"aarch64-apple-darwin\"]"); + } else if let Ok(bad) = env::var("NATIVE_BAD_SPEC") { println!("{bad}"); } + else { + let (os, format) = if target.contains("windows") { ("windows", "coff") } + else if target.contains("apple") { ("macos", "macho") } else { ("linux", "elf") }; + println!("{{\"triple\":{},\"supported\":true,\"hosted\":true,\"os\":{},\"object_format\":{}}}", quote(&target), quote(os), quote(format)); + } + return; + } + let check = args.iter().any(|s| s == "--emit=check"); + let object = args.iter().any(|s| s == "--emit=obj"); + let run = args.iter().any(|s| s == "--run"); + let input = args.iter().find(|s| s.ends_with(".wave")).unwrap(); + let output = value("-o").unwrap_or_else(|| "target/default-program".into()); + let intermediate = if object { output.clone() } + else { PathBuf::from(value("--target-dir").unwrap_or_else(|| "target".into())).join("native.o").to_string_lossy().into_owned() }; + if args.iter().any(|s| s == "--dry-run") { + let emit = if check { "check" } else if object { "obj" } else { "bin" }; + let compile = if check { "[]".into() } else { format!("[{{\"input\":{},\"kind\":\"wave\",\"output\":{},\"command\":\"fixture compile\"}}]", quote(input), quote(&intermediate)) }; + let native_args: Vec<_> = args.iter().filter_map(|arg| arg.strip_prefix("-Clink-arg=").map(str::to_owned)).collect(); + let link = if check || object { "null".into() } else { format!("{{\"output\":{},\"inputs\":[{}],\"program\":\"fixture linker\",\"args\":{}}}", quote(&output), quote(&intermediate), list(&native_args)) }; + let execute = if run { format!("{{\"program\":{},\"args\":[]}}", quote(&output)) } else { "null".into() }; + println!("{{\"schema_version\":1,\"mode\":{},\"target\":{},\"emit\":{},\"emit_kinds\":[],\"control_mode\":null,\"forced_input_type\":null,\"inputs\":[{{\"path\":{},\"kind\":\"wave\"}}],\"emit_jobs\":[],\"compile\":{},\"link\":{},\"execute\":{}}}", quote(if run { "build+run" } else { "build" }), quote(&target), quote(emit), quote(input), compile, link, execute); + return; + } + fs::write("compiler-started", list(&args)).unwrap(); + if !check { + for path in if object { vec![intermediate] } else { vec![intermediate, output.clone()] } { + let path = PathBuf::from(path); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, b"native artifact").unwrap(); + } + if output.contains(".vex-run") { fs::copy(env::current_exe().unwrap(), output).unwrap(); } + } +} diff --git a/tests/fixtures/target_wavec.rs b/tests/fixtures/target_wavec.rs index cec1da1..83344d3 100644 --- a/tests/fixtures/target_wavec.rs +++ b/tests/fixtures/target_wavec.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 // Independent compiler process fixture; compiled by rustc without dependencies. use std::{env, fs, io::Write, path::PathBuf}; @@ -39,6 +43,17 @@ fn host() -> &'static str { fn main() { let args: Vec = env::args().skip(1).collect(); if env::current_exe().unwrap().file_stem().unwrap() != "target-wavec" { + if let Some(directory) = env::var_os("TARGET_PROGRAM_EXPECT_CWD") { + assert_eq!(env::current_dir().unwrap().canonicalize().unwrap(), PathBuf::from(directory).canonicalize().unwrap()); + } + let name=env::current_exe().unwrap().file_stem().unwrap().to_string_lossy().into_owned(); + if let Some(log)=env::var_os("TARGET_PROGRAM_LOG") { + let mut file=fs::OpenOptions::new().create(true).append(true).open(log).unwrap(); + writeln!(file,"{name}").unwrap(); + } + if let Ok(codes)=env::var("TARGET_PROGRAM_EXIT_MAP") { + if let Some(code)=codes.split(',').find_map(|part|part.split_once('=').filter(|(key,_)|*key==name).map(|(_,value)|value.parse::().unwrap())) { env::set_var("TARGET_PROGRAM_EXIT",code.to_string()); } + } println!("TARGET_PROGRAM:{}", list(&args)); if let Ok(vex) = env::var("TARGET_PROGRAM_CHECK_LOCK_RELEASE") { let status = std::process::Command::new(vex) @@ -80,6 +95,9 @@ fn main() { }; let triple = value("--target").unwrap_or_else(|| host().into()); if args.first().is_some_and(|arg| arg == "print") { + if args.get(1).is_some_and(|arg|arg=="std-path") { + if let Ok(path)=env::var("TARGET_STD_PATH") { println!("{}",quote(&path)); return; } + } if args.get(1).is_some_and(|arg| arg == "supported-targets") { println!("[\"x86_64-unknown-linux-gnu\",\"aarch64-unknown-linux-gnu\",\"x86_64-pc-windows-msvc\",\"aarch64-pc-windows-msvc\",\"x86_64-apple-darwin\",\"aarch64-apple-darwin\",\"wasm32-unknown-unknown\",\"wasm32-wasip1\"]"); } else { @@ -135,7 +153,7 @@ fn main() { let link = if check || object { "null".into() } else { - format!("{{\"output\":{},\"inputs\":[{}],\"program\":\"target fixture linker\",\"args\":[]}}", quote(&output), quote(&intermediate)) + format!("{{\"output\":{},\"inputs\":[{}],\"program\":{},\"args\":[]}}", quote(&output), quote(&intermediate), quote(&env::var("TARGET_LINK_PROGRAM").unwrap_or_else(|_|"target fixture linker".into()))) }; let execute = if run { format!("{{\"program\":{},\"args\":[]}}", quote(&output)) diff --git a/tests/fixtures/version_probe.rs b/tests/fixtures/version_probe.rs new file mode 100644 index 0000000..fcacee3 --- /dev/null +++ b/tests/fixtures/version_probe.rs @@ -0,0 +1,16 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 + + fn main() { + if std::env::current_exe().unwrap().file_stem().unwrap() == "broken" { + eprintln!("missing compiler runtime"); + std::process::exit(7); + } + if std::env::var_os("NO_COLOR").is_some() { + println!("wavec 0.2.1-pre-beta (platform)\n backend: LLVM 21"); + } else { + println!("\x1b[32mwavec\x1b[0m \x1b[32m0.2.1-pre-beta\x1b[0m"); + } + } diff --git a/tests/git_lock_reproducibility.rs b/tests/git_lock_reproducibility.rs index c66d60b..175962a 100644 --- a/tests/git_lock_reproducibility.rs +++ b/tests/git_lock_reproducibility.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use std::fs; use std::path::{Path, PathBuf}; use std::process::{Command, Output}; @@ -107,11 +111,8 @@ fn git_lock_keeps_transitive_graph_until_explicit_update() { app.join(".vex/deps/pkg_9f91161f43433e49a6de6db680d79f60159f2e4ac9172621a12846428158440b"), ) .expect("managed leaf checkout must be removed for the offline test"); - let missing_offline = vex(&app, &["fetch", "--locked", "--offline"]); - assert_failure(&missing_offline, "offline fetch with a missing checkout"); - let missing_offline_stderr = String::from_utf8_lossy(&missing_offline.stderr); - assert!(missing_offline_stderr.contains("not available locally in offline mode")); - assert!(missing_offline_stderr.contains("run `vex fetch` while online")); + let restored_offline = vex(&app, &["fetch", "--locked", "--offline"]); + assert_success(&restored_offline, "offline restoration from shared cache"); assert_eq!(read_lock(&app), first_lock); let restored = vex(&app, &["fetch", "--locked"]); @@ -717,6 +718,7 @@ fn vex(path: &Path, args: &[&str]) -> Output { Command::new(env!("CARGO_BIN_EXE_vex")) .args(args) .current_dir(path) + .env("VEX_CACHE_HOME", path.join(".test-cache")) .output() .expect("vex command must start") } @@ -1288,6 +1290,16 @@ fn unadvertised_locked_object_is_fetched_exactly_and_pruned_object_never_substit fs::remove_dir_all(app.join(".vex/deps")).unwrap(); git(&["reflog", "expire", "--expire=now", "--all"]); git(&["gc", "--prune=now"]); + // Cached locked objects remain usable after the source prunes its history. + assert_success( + &vex(&app, &["fetch", "--locked", "--offline"]), + "retained cached object", + ); + fs::remove_dir_all(app.join(".vex/deps")).unwrap(); + assert_success( + &vex(&app, &["cache", "prune", "--apply"]), + "explicit cache cleanup", + ); let output = vex(&app, &["fetch", "--locked"]); assert_eq!(output.status.code(), Some(3)); let error = String::from_utf8_lossy(&output.stderr); @@ -1344,15 +1356,7 @@ fn fixture_compiler(root: &Path) -> PathBuf { let source = root.join("fake.rs"); let binary = root.join(if cfg!(windows) { "wavec.exe" } else { "wavec" }); fs::write(&source, include_str!("fixtures/fake_wavec.rs")).unwrap(); - assert_success( - &Command::new("rustc") - .arg(&source) - .arg("-o") - .arg(&binary) - .output() - .unwrap(), - "compile fixture", - ); + support::compile_fixture("fake_wavec", &binary); binary } diff --git a/tests/git_shared_cache.rs b/tests/git_shared_cache.rs new file mode 100644 index 0000000..a42cfb3 --- /dev/null +++ b/tests/git_shared_cache.rs @@ -0,0 +1,294 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; +use std::sync::atomic::{AtomicU64, Ordering}; +mod support; +use support::git_url; +static ID: AtomicU64 = AtomicU64::new(0); +struct Fixture(PathBuf); +impl Fixture { + fn new() -> Self { + let root = std::env::temp_dir().join(format!( + "vex-cache-{}-{}", + std::process::id(), + ID.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&root).unwrap(); + Self(root.canonicalize().unwrap()) + } + fn vex(&self, project: &Path, args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_vex")) + .current_dir(project) + .env("VEX_CACHE_HOME", self.0.join("cache")) + .args(args) + .output() + .unwrap() + } + fn source(&self, format: &str) -> PathBuf { + let source = self.0.join("source"); + package(&source.join("packages/dep"), "dep", ""); + git( + &source, + &[ + "init", + "--initial-branch=master", + &format!("--object-format={format}"), + ], + ); + git(&source, &["add", "."]); + git(&source, &["commit", "-m", "fixture"]); + source + } + fn app(&self, name: &str, source: &Path) -> PathBuf { + let app = self.0.join(name); + package( + &app, + "app", + &format!( + "{{name=\"dep\",git=\"{}\",subdir=\"packages/dep\"}}", + git_url(source) + ), + ); + app + } +} +impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} +fn package(path: &Path, name: &str, deps: &str) { + fs::create_dir_all(path.join("src")).unwrap(); + fs::write(path.join("src/lib.wave"), "pub fun marker() {}\n").unwrap(); + fs::write(path.join("vex.ws"), format!("{{format=4,name=\"{name}\",version=\"1.0.0\",targets={{lib={{}}}},dependencies=[{deps}]}}\n")).unwrap(); +} +fn git(path: &Path, args: &[&str]) -> String { + let out = Command::new("git") + .current_dir(path) + .args([ + "-c", + "user.name=Vex Test", + "-c", + "user.email=test@example.invalid", + ]) + .args(args) + .output() + .unwrap(); + success(&out); + String::from_utf8(out.stdout).unwrap().trim().to_owned() +} +fn success(out: &Output) { + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); +} + +#[test] +fn exact_cached_objects_restore_offline_and_survive_cache_prune() { + for format in ["sha1", "sha256"] { + let f = Fixture::new(); + let source = f.source(format); + let first = f.app("first", &source); + success(&f.vex(&first, &["fetch"])); + let bytes = fs::read(first.join("vex.lock")).unwrap(); + let lock = lockfile::decode(std::str::from_utf8(&bytes).unwrap()).unwrap(); + assert_eq!(lock.version, 4); + assert_eq!(lock.packages[0].subdir.as_deref(), Some("packages/dep")); + let second = f.app("second", &source); + fs::write(second.join("vex.lock"), &bytes).unwrap(); + fs::rename(&source, source.with_extension("hidden")).unwrap(); + success(&f.vex(&second, &["fetch", "--offline", "--locked"])); + assert_eq!(fs::read(second.join("vex.lock")).unwrap(), bytes); + let out = f.vex(&second, &["metadata", "--format-version", "2", "--locked"]); + success(&out); + let metadata: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap(); + assert!(Path::new(metadata["packages"][0]["root"].as_str().unwrap()) + .ends_with(Path::new("packages").join("dep"))); + success(&f.vex(&second, &["cache", "prune", "--apply"])); + success(&f.vex(&second, &["fetch", "--offline", "--locked"])); + let checkout = second.join(match &lock.packages[0].source { + lockfile::LockedSource::Git { resolved, .. } => resolved, + _ => panic!(), + }); + assert!(!checkout.join(".git/objects/info/alternates").exists()); + assert_eq!(git(&checkout, &["fsck", "--full", "--no-dangling"]), ""); + } +} + +#[test] +fn dry_run_never_restores_a_checkout_from_cache() { + let f = Fixture::new(); + let source = f.source("sha1"); + let app = f.app("app", &source); + success(&f.vex(&app, &["fetch"])); + fs::remove_dir_all(app.join(".vex/deps")).unwrap(); + let out = f.vex(&app, &["fetch", "--dry-run", "--offline", "--locked"]); + assert!(!out.status.success()); + assert!(!app.join(".vex/deps").exists()); +} + +#[test] +fn subdir_rejects_unsafe_syntax_and_escape_before_publication() { + let f = Fixture::new(); + let source = f.source("sha1"); + let app = f.app("app", &source); + for value in [ + "", "/etc", "a//b", "../dep", "a/../dep", "C:/dep", "a\\b", ".", + ] { + let raw = format!("{{format=4,name=\"app\",targets={{lib={{}}}},dependencies=[{{name=\"dep\",git=\"{}\",subdir={}}}]}}", git_url(&source), serde_json::to_string(value).unwrap()); + assert!( + manifest::decode(&raw, app.join("vex.ws")).is_err(), + "{value}" + ); + } + #[cfg(unix)] + { + std::os::unix::fs::symlink("../../../../", source.join("escape")).unwrap(); + git(&source, &["add", "."]); + git(&source, &["commit", "-m", "escape"]); + let raw = fs::read_to_string(app.join("vex.ws")) + .unwrap() + .replace("packages/dep", "escape"); + fs::write(app.join("vex.ws"), raw).unwrap(); + let out = f.vex(&app, &["fetch"]); + assert!(!out.status.success()); + assert!(!app.join("vex.lock").exists()); + assert!(!app.join(".vex/deps").exists()); + } +} + +#[test] +fn corrupted_cache_is_quarantined_and_live_project_is_preserved() { + let f = Fixture::new(); + let source = f.source("sha1"); + let first = f.app("first", &source); + success(&f.vex(&first, &["fetch"])); + let cache = fs::read_dir(f.0.join("cache/git")) + .unwrap() + .map(|e| e.unwrap().path()) + .find(|p| p.extension().is_some_and(|v| v == "git")) + .unwrap(); + fs::write(cache.join("config"), "not a git config\n").unwrap(); + let second = f.app("second", &source); + fs::copy(first.join("vex.lock"), second.join("vex.lock")).unwrap(); + let old = fs::read(first.join("vex.lock")).unwrap(); + let out = f.vex(&second, &["fetch", "--offline", "--locked"]); + assert!(!out.status.success()); + assert!(!second.join(".vex/deps").exists()); + assert_eq!(fs::read(first.join("vex.lock")).unwrap(), old); + assert!(fs::read_dir(f.0.join("cache/git")).unwrap().any(|e| e + .unwrap() + .path() + .to_string_lossy() + .contains("quarantine"))); + success(&f.vex(&second, &["fetch", "--locked"])); + success(&f.vex(&first, &["fetch", "--locked", "--offline"])); +} + +#[test] +fn concurrent_projects_publish_one_cache_and_keep_isolated_worktrees() { + let f = Fixture::new(); + let source = f.source("sha1"); + let first = f.app("first", &source); + let second = f.app("second", &source); + let children: Vec<_> = [&first, &second] + .into_iter() + .map(|project| { + Command::new(env!("CARGO_BIN_EXE_vex")) + .current_dir(project) + .env("VEX_CACHE_HOME", f.0.join("cache")) + .arg("fetch") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap() + }) + .collect(); + for child in children { + success(&child.wait_with_output().unwrap()); + } + assert_eq!( + fs::read(first.join("vex.lock")).unwrap(), + fs::read(second.join("vex.lock")).unwrap() + ); + assert_eq!( + fs::read_dir(f.0.join("cache/git")) + .unwrap() + .filter(|e| e + .as_ref() + .unwrap() + .path() + .extension() + .is_some_and(|v| v == "git")) + .count(), + 1 + ); +} + +#[test] +fn extending_cache_bundles_staged_objects_and_keeps_old_pins_independent() { + for format in ["sha1", "sha256"] { + let f = Fixture::new(); + let source = f.source(format); + let old = git(&source, &["rev-parse", "HEAD"]); + let first = f.app("first", &source); + success(&f.vex(&first, &["fetch"])); + let old_lock = fs::read(first.join("vex.lock")).unwrap(); + // Replace the remote history. The new checkout cannot provide the old + // objects, so extending a cache must retain its independently pinned set. + git(&source, &["checkout", "--orphan", "replacement"]); + fs::write( + source.join("packages/dep/src/lib.wave"), + "pub fun changed() {}\n", + ) + .unwrap(); + git(&source, &["add", "."]); + git(&source, &["commit", "-m", "replacement history"]); + git(&source, &["branch", "-D", "master"]); + git(&source, &["reflog", "expire", "--expire=now", "--all"]); + git(&source, &["gc", "--prune=now"]); + let new = git(&source, &["rev-parse", "HEAD"]); + assert_ne!(old, new); + let trace = f.0.join("cache-transfer.trace"); + let output = Command::new(env!("CARGO_BIN_EXE_vex")) + .current_dir(&first) + .env("VEX_CACHE_HOME", f.0.join("cache")) + .env("GIT_TRACE", support::git_path(&trace)) + .args(["update", "dep"]) + .output() + .unwrap(); + success(&output); + let trace = fs::read_to_string(trace).unwrap().replace('\\', "/"); + assert!(trace.contains("bundle create"), "{trace}"); + assert!(trace.contains("bundle unbundle"), "{trace}"); + assert!( + !trace + .lines() + .any(|line| line.contains("fetch --no-tags --") + && line.contains("/.vex/transactions/")), + "cache must not serve a deep staged checkout: {trace}" + ); + assert!(fs::read_to_string(first.join("vex.lock")) + .unwrap() + .contains(&new)); + let second = f.app("second", &source); + fs::write(second.join("vex.lock"), &old_lock).unwrap(); + fs::rename(&source, source.with_extension("hidden")).unwrap(); + success(&f.vex(&second, &["fetch", "--locked", "--offline"])); + assert_eq!(fs::read(second.join("vex.lock")).unwrap(), old_lock); + success(&f.vex(&first, &["fetch", "--locked", "--offline"])); + assert!(fs::read_dir(f.0.join("cache/git")) + .unwrap() + .all(|entry| entry + .unwrap() + .path() + .extension() + .is_none_or(|ext| ext != "bundle"))); + } +} diff --git a/tests/git_targeted_update.rs b/tests/git_targeted_update.rs index 570cc51..2a2ba46 100644 --- a/tests/git_targeted_update.rs +++ b/tests/git_targeted_update.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use std::fs; use std::path::{Path, PathBuf}; use std::process::{Command, Output}; diff --git a/tests/initial_clone_fetch.rs b/tests/initial_clone_fetch.rs index 0293007..2d2bd74 100644 --- a/tests/initial_clone_fetch.rs +++ b/tests/initial_clone_fetch.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use std::fs; use std::path::{Path, PathBuf}; use std::process::{Command, Output}; @@ -139,7 +143,7 @@ fn a_reference_missing_from_clone_is_fetched_before_reporting_resolution_failure } #[test] -fn restoring_a_locked_unadvertised_object_still_uses_exact_fetch() { +fn restoring_a_locked_unadvertised_object_reuses_the_cached_exact_object() { let fixture = Fixture::new(); let (source, expected) = fixture.source("sha1"); let app = fixture.0.join("app"); @@ -159,8 +163,8 @@ fn restoring_a_locked_unadvertised_object_still_uses_exact_fetch() { let (output, commands) = traced_vex(&app, &["fetch", "--locked"]); success(&output); - assert_commands(&commands, "clone", 1); - assert_commands(&commands, "fetch", 1); + assert_commands(&commands, "clone", 0); + assert_commands(&commands, "fetch", 0); assert_commands(&commands, "ls-remote", 0); assert_eq!(locked_commit(&app), expected); assert_eq!(fs::read(app.join("vex.lock")).unwrap(), lock); @@ -250,9 +254,10 @@ fn traced_vex(app: &Path, args: &[&str]) -> (Output, Vec) { .current_dir(app) .args(args) .env("GIT_TRACE2_EVENT", git_path(&trace)) + .env("VEX_CACHE_HOME", app.join(".test-cache")) .output() .unwrap(); - let commands = fs::read_to_string(&trace) + let events = fs::read_to_string(&trace) .unwrap_or_else(|error| { panic!( "missing Git trace {}: {error}; stderr: {}", @@ -262,6 +267,28 @@ fn traced_vex(app: &Path, args: &[&str]) -> (Output, Vec) { }) .lines() .map(|line| serde_json::from_str::(line).unwrap()) + .collect::>(); + // Count source acquisition, not local cache maintenance subprocesses. + let cache_sessions: Vec<_> = events + .iter() + .filter(|event| { + event["event"] == "start" + && event["argv"].as_array().is_some_and(|args| { + args.iter() + .any(|arg| arg.as_str().is_some_and(|arg| arg.contains(".test-cache"))) + }) + }) + .filter_map(|event| event["sid"].as_str().map(str::to_owned)) + .collect(); + let commands = events + .into_iter() + .filter(|event| { + !cache_sessions.iter().any(|sid| { + event["sid"] + .as_str() + .is_some_and(|value| value.starts_with(sid)) + }) + }) .filter(|event| event["event"] == "cmd_name") .map(|event| event["name"].as_str().unwrap().to_owned()) .collect(); diff --git a/tests/native_build.rs b/tests/native_build.rs index 974a07d..5d47c6d 100644 --- a/tests/native_build.rs +++ b/tests/native_build.rs @@ -1,4 +1,9 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use serde_json::{json, Value}; +mod support; use std::collections::BTreeMap; use std::fs; use std::path::{Path, PathBuf}; @@ -10,77 +15,7 @@ use std::sync::{ // An independent process boundary: this fixture accepts compiler arguments and // reports their actual outputs; it does not depend on Vex's native model. -const COMPILER_SOURCE: &str = r#" -use std::{env, fs, io::Write, path::PathBuf}; -fn quote(value: &str) -> String { - let mut text = String::from("\""); - for ch in value.chars() { - match ch { - '\\' => text.push_str("\\\\"), '"' => text.push_str("\\\""), - '\n' => text.push_str("\\n"), '\r' => text.push_str("\\r"), - '\t' => text.push_str("\\t"), - c if c.is_control() => text.push_str(&format!("\\u{:04x}", c as u32)), - c => text.push(c), - } - } - text.push('"'); text -} -fn list(values: &[String]) -> String { - format!("[{}]", values.iter().map(|s| quote(s)).collect::>().join(",")) -} -fn main() { - let args: Vec<_> = env::args().skip(1).collect(); - if !env::current_exe().unwrap().file_stem().unwrap().to_string_lossy().starts_with("fake-native-wavec") { - fs::write("program-started", list(&args)).unwrap(); - println!("native fixture program"); - std::process::exit(17); - } - if let Some(path) = env::var_os("NATIVE_COMPILER_LOG") { - let mut log = fs::OpenOptions::new().create(true).append(true).open(path).unwrap(); - writeln!(log, "{}", list(&args)).unwrap(); - } - if args.iter().any(|s| s == "--version") { println!("wavec 0.2.1-pre-beta"); return; } - let value = |flag: &str| args.iter().find_map(|s| s.strip_prefix(&format!("{flag}=")).map(str::to_owned)) - .or_else(|| args.iter().position(|s| s == flag).and_then(|i| args.get(i+1).cloned())); - let target = value("--target").unwrap_or_else(|| env::var("NATIVE_DEFAULT_TARGET").unwrap_or_else(|_| "x86_64-unknown-linux-gnu".into())); - if args.first().is_some_and(|s| s == "print") { - if args.get(1).is_some_and(|s| s == "supported-targets") { - println!("[\"x86_64-unknown-linux-gnu\",\"aarch64-unknown-linux-gnu\",\"x86_64-pc-windows-msvc\",\"aarch64-pc-windows-msvc\",\"x86_64-apple-darwin\",\"aarch64-apple-darwin\"]"); - } else if let Ok(bad) = env::var("NATIVE_BAD_SPEC") { println!("{bad}"); } - else { - let (os, format) = if target.contains("windows") { ("windows", "coff") } - else if target.contains("apple") { ("macos", "macho") } else { ("linux", "elf") }; - println!("{{\"triple\":{},\"supported\":true,\"hosted\":true,\"os\":{},\"object_format\":{}}}", quote(&target), quote(os), quote(format)); - } - return; - } - let check = args.iter().any(|s| s == "--emit=check"); - let object = args.iter().any(|s| s == "--emit=obj"); - let run = args.iter().any(|s| s == "--run"); - let input = args.iter().find(|s| s.ends_with(".wave")).unwrap(); - let output = value("-o").unwrap_or_else(|| "target/default-program".into()); - let intermediate = if object { output.clone() } - else { PathBuf::from(value("--target-dir").unwrap_or_else(|| "target".into())).join("native.o").to_string_lossy().into_owned() }; - if args.iter().any(|s| s == "--dry-run") { - let emit = if check { "check" } else if object { "obj" } else { "bin" }; - let compile = if check { "[]".into() } else { format!("[{{\"input\":{},\"kind\":\"wave\",\"output\":{},\"command\":\"fixture compile\"}}]", quote(input), quote(&intermediate)) }; - let native_args: Vec<_> = args.iter().filter_map(|arg| arg.strip_prefix("-Clink-arg=").map(str::to_owned)).collect(); - let link = if check || object { "null".into() } else { format!("{{\"output\":{},\"inputs\":[{}],\"program\":\"fixture linker\",\"args\":{}}}", quote(&output), quote(&intermediate), list(&native_args)) }; - let execute = if run { format!("{{\"program\":{},\"args\":[]}}", quote(&output)) } else { "null".into() }; - println!("{{\"schema_version\":1,\"mode\":{},\"target\":{},\"emit\":{},\"emit_kinds\":[],\"control_mode\":null,\"forced_input_type\":null,\"inputs\":[{{\"path\":{},\"kind\":\"wave\"}}],\"emit_jobs\":[],\"compile\":{},\"link\":{},\"execute\":{}}}", quote(if run { "build+run" } else { "build" }), quote(&target), quote(emit), quote(input), compile, link, execute); - return; - } - fs::write("compiler-started", list(&args)).unwrap(); - if !check { - for path in if object { vec![intermediate] } else { vec![intermediate, output.clone()] } { - let path = PathBuf::from(path); - fs::create_dir_all(path.parent().unwrap()).unwrap(); - fs::write(path, b"native artifact").unwrap(); - } - if output.contains(".vex-run") { fs::copy(env::current_exe().unwrap(), output).unwrap(); } - } -} -"#; +const COMPILER_SOURCE: &str = include_str!("fixtures/native_wavec.rs"); struct Fixture { root: PathBuf, @@ -128,14 +63,7 @@ impl Fixture { } else { "fake-native-wavec" }); - let output = Command::new("rustc") - .args(["--edition=2021"]) - .arg(&source) - .arg("-o") - .arg(&compiler) - .output() - .unwrap(); - code(&output, 0); + support::compile_fixture("native_wavec", &compiler); compiler }); let mut command = Command::new(env!("CARGO_BIN_EXE_vex")); diff --git a/tests/native_interop.py b/tests/native_interop.py index 0861015..11d95ad 100644 --- a/tests/native_interop.py +++ b/tests/native_interop.py @@ -1,4 +1,7 @@ #!/usr/bin/env python3 +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. # SPDX-License-Identifier: MPL-2.0 """Native C ABI acceptance against a verified Wave release on the current host. @@ -17,8 +20,10 @@ import tempfile -def run(command, cwd, env, expected=0): +def run(command, cwd, env, expected=0, *, native_tool=False): command = list(map(str, command)) + if env.get("VEX_TEST_TARGET_RUNNER") and not native_tool: + command.insert(0, env["VEX_TEST_TARGET_RUNNER"]) print("$", " ".join(command), flush=True) result = subprocess.run(command, cwd=cwd, env=env, text=True, capture_output=True, timeout=300) @@ -77,10 +82,10 @@ class NativeTools: def __init__(self, root, env, spec): self.windows = spec["os"] == "windows" self.env = msvc_environment(root, env, spec["arch"]) if self.windows else env - self.cc = required_tool("cl.exe" if self.windows else "cc", self.env) - self.cxx = self.cc if self.windows else required_tool("c++", self.env) - self.ar = required_tool("lib.exe" if self.windows else "ar", self.env) - self.rustc = required_tool("rustc", self.env) + self.cc = required_tool("cl.exe" if self.windows else self.env.get("CC", "cc"), self.env) + self.cxx = self.cc if self.windows else required_tool(self.env.get("CXX", "c++"), self.env) + self.ar = required_tool("lib.exe" if self.windows else self.env.get("AR", "ar"), self.env) + self.rustc = required_tool(self.env.get("RUSTC", "rustc"), self.env) self.object_extension = ".obj" if self.windows else ".o" def archive(self, root, name, source, cpp=False): @@ -93,8 +98,8 @@ def archive(self, root, name, source, cpp=False): path, "/Fo" + str(obj)], root, self.env) run([self.ar, "/NOLOGO", "/OUT:" + str(archive), obj], root, self.env) else: - run([self.cxx if cpp else self.cc, "-fPIC", "-c", path, "-o", obj], root, self.env) - run([self.ar, "rcs", archive, obj], root, self.env) + run([self.cxx if cpp else self.cc, "-fPIC", "-c", path, "-o", obj], root, self.env, native_tool=True) + run([self.ar, "rcs", archive, obj], root, self.env, native_tool=True) return archive def rust_object(self, root): @@ -104,7 +109,7 @@ def rust_object(self, root): '-> i32 { a.wrapping_add(b) }\n', encoding="utf-8") obj = root / ("native_rust" + self.object_extension) run([self.rustc, "--edition=2021", "--crate-type=lib", "--emit=obj", - "-C", "panic=abort", source, "-o", obj], root, self.env) + "-C", "panic=abort", source, "-o", obj], root, self.env, native_tool=True) return obj def consume(self, root, library, shared=False): @@ -123,7 +128,7 @@ def consume(self, root, library, shared=False): args = [self.cc, source, library, "-o", executable] if shared: args.append("-Wl,-rpath," + str(library.parent)) - run(args, root, self.env) + run(args, root, self.env, native_tool=True) env = dict(self.env) if shared and self.windows: # This is the external consumer's loader setup, not a Vex policy. diff --git a/tests/output_pipes.rs b/tests/output_pipes.rs index 04035d2..0403f1c 100644 --- a/tests/output_pipes.rs +++ b/tests/output_pipes.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use std::fs; use std::path::PathBuf; use std::process::{Command, Stdio}; diff --git a/tests/output_policy.rs b/tests/output_policy.rs index 49d9ed9..a30c053 100644 --- a/tests/output_policy.rs +++ b/tests/output_policy.rs @@ -3,6 +3,7 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. // SPDX-License-Identifier: MPL-2.0 +mod support; use std::collections::BTreeMap; use std::fs; use std::io::Write; @@ -36,14 +37,7 @@ impl Fixture { include_str!("fixtures/fake_wavec.rs"), ) .unwrap(); - success( - &Command::new("rustc") - .arg(self.root.join("fake.rs")) - .arg("-o") - .arg(&self.compiler) - .output() - .unwrap(), - ); + support::compile_fixture("fake_wavec", &self.compiler); } fn command(&self, args: &[&str]) -> Command { diff --git a/tests/package_identity.rs b/tests/package_identity.rs new file mode 100644 index 0000000..000f3a8 --- /dev/null +++ b/tests/package_identity.rs @@ -0,0 +1,148 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; +use std::sync::atomic::{AtomicU64, Ordering}; +static ID: AtomicU64 = AtomicU64::new(0); +struct Fixture(PathBuf); +impl Fixture { + fn new() -> Self { + let path = std::env::temp_dir().join(format!( + "vex-identity-{}-{}", + std::process::id(), + ID.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&path).unwrap(); + Self(path) + } + fn package(&self, directory: &str, name: &str, version: &str, dependencies: &str) -> PathBuf { + let path = self.0.join(directory); + fs::create_dir_all(path.join("src")).unwrap(); + fs::write(path.join("src/lib.wave"), "pub fun marker() {}\n").unwrap(); + fs::write(path.join("vex.ws"), format!("{{format=4,name=\"{name}\",version=\"{version}\",targets={{lib={{}}}},dependencies=[{dependencies}]}}")).unwrap(); + path + } + fn vex(&self, project: &Path, args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_vex")) + .current_dir(project) + .env("VEX_CACHE_HOME", self.0.join("cache")) + .args(args) + .output() + .unwrap() + } +} +impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} +fn success(out: &Output) { + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); +} +#[test] +fn aliases_and_two_versions_have_concrete_identity_and_locked_metadata() { + let f = Fixture::new(); + f.package("one", "math", "1.2.3", ""); + f.package("two", "math", "2.0.0", ""); + let app = f.package("app", "app", "1.0.0", "{name=\"old_math\",package=\"math\",path=\"../one\",version_req=\"^1.2\"},{name=\"new_math\",package=\"math\",path=\"../two\",version_req=\"^2\"}"); + success(&f.vex(&app, &["fetch"])); + let bytes = fs::read(app.join("vex.lock")).unwrap(); + let lock = lockfile::decode(std::str::from_utf8(&bytes).unwrap()).unwrap(); + assert_eq!(lock.packages.len(), 2); + assert!(lock.packages.iter().all(|p| p.package_name() == "math")); + assert_ne!(lock.packages[0].id, lock.packages[1].id); + success(&f.vex(&app, &["fetch", "--locked", "--offline"])); + assert_eq!(fs::read(app.join("vex.lock")).unwrap(), bytes); + let out = f.vex(&app, &["tree", "--locked", "--offline"]); + success(&out); + let tree = String::from_utf8(out.stdout).unwrap(); + assert!(tree.contains("new_math => math v2.0.0")); + assert!(tree.contains("old_math => math v1.2.3")); + let out = f.vex(&app, &["metadata", "--format-version", "2", "--locked"]); + success(&out); + let data: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap(); + assert_eq!(data["packages"][0]["name"], "math"); + assert!(data["packages"][0]["alias"].is_string()); + assert!(data["packages"][0]["id"].is_string()); +} +#[test] +fn compatible_transitive_requirements_share_an_alias_and_mismatch_preserves_lock() { + let f = Fixture::new(); + f.package("shared", "shared", "1.5.0", ""); + f.package( + "left", + "left", + "1.0.0", + "{name=\"shared\",path=\"../shared\",version_req=\"^1.2\"}", + ); + f.package( + "right", + "right", + "1.0.0", + "{name=\"shared\",path=\"../shared\",version_req=\">=1.3, <2\"}", + ); + let app = f.package( + "app", + "app", + "1.0.0", + "{name=\"left\",path=\"../left\"},{name=\"right\",path=\"../right\"}", + ); + success(&f.vex(&app, &["fetch"])); + let old = fs::read(app.join("vex.lock")).unwrap(); + f.package( + "right", + "right", + "1.0.0", + "{name=\"shared\",path=\"../shared\",version_req=\"^2\"}", + ); + let out = f.vex(&app, &["fetch"]); + assert_eq!(out.status.code(), Some(3)); + assert!(String::from_utf8_lossy(&out.stderr).contains("^2")); + assert_eq!(fs::read(app.join("vex.lock")).unwrap(), old); +} +#[test] +fn scoped_alias_conflicts_explain_compiler_limit_before_publication() { + let f = Fixture::new(); + f.package("one", "math", "1.0.0", ""); + f.package("two", "math", "2.0.0", ""); + f.package("left", "left", "1.0.0", "{name=\"math\",path=\"../one\"}"); + f.package("right", "right", "1.0.0", "{name=\"math\",path=\"../two\"}"); + let app = f.package( + "app", + "app", + "1.0.0", + "{name=\"left\",path=\"../left\"},{name=\"right\",path=\"../right\"}", + ); + let out = f.vex(&app, &["fetch"]); + assert_eq!(out.status.code(), Some(3)); + let error = String::from_utf8_lossy(&out.stderr); + assert!( + error.contains("scoped compiler dependency mappings"), + "{error}" + ); + assert!(!app.join("vex.lock").exists()); +} +#[test] +fn locked_legacy_file_is_never_silently_migrated() { + let f = Fixture::new(); + let app = f.package("app", "app", "1.0.0", ""); + let old = b"{version=3,package=[]}\n"; + fs::write(app.join("vex.lock"), old).unwrap(); + let out = f.vex(&app, &["fetch", "--locked"]); + assert_eq!(out.status.code(), Some(3)); + assert_eq!(fs::read(app.join("vex.lock")).unwrap(), old); + success(&f.vex(&app, &["fetch"])); + assert_eq!( + lockfile::decode(&fs::read_to_string(app.join("vex.lock")).unwrap()) + .unwrap() + .version, + 4 + ); +} diff --git a/tests/package_targets.rs b/tests/package_targets.rs index 1214810..acc39eb 100644 --- a/tests/package_targets.rs +++ b/tests/package_targets.rs @@ -1,4 +1,9 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use serde_json::{json, Value}; +mod support; use std::collections::BTreeMap; use std::fs; use std::path::{Path, PathBuf}; @@ -28,14 +33,7 @@ fn compiler() -> &'static Path { } else { "target-wavec" }); - let output = Command::new("rustc") - .args(["--edition=2021"]) - .arg(Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/target_wavec.rs")) - .arg("-o") - .arg(&compiler) - .output() - .unwrap(); - code(&output, 0); + support::compile_fixture("target_wavec", &compiler); compiler }) } @@ -492,3 +490,53 @@ fn project_selection_errors_precede_missing_compiler() { assert!(!f.app.join(".vex").exists()); } } + +#[test] +fn only_active_dependency_compiler_requirements_gate_a_build() { + let f = Fixture::new("targets={bins=[{name=\"app\",path=\"src/main.wave\"}]}"); + f.package("extra", "targets={lib={}},compiler=\"9.0.0\""); + fs::write(f.app.join("vex.ws"), "{format=4,name=\"app\",targets={bins=[{name=\"app\",path=\"src/main.wave\"}]},dependencies=[{name=\"extra\",path=\"../extra\",optional=true}]}").unwrap(); + code(&f.run(&["fetch"]), 0); + let lock = fs::read(f.app.join("vex.lock")).unwrap(); + code(&f.run(&["build", "--locked", "--offline"]), 0); + assert!(f + .build_calls() + .iter() + .all(|args| !args.iter().any(|arg| arg.starts_with("--dep=extra=")))); + let calls = f.build_calls().len(); + code( + &f.run(&["build", "--features=extra", "--locked", "--offline"]), + 3, + ); + assert_eq!(f.build_calls().len(), calls); + assert_eq!(fs::read(f.app.join("vex.lock")).unwrap(), lock); +} + +#[test] +fn every_selected_mode_is_validated_before_any_compiler_execution() { + let f = Fixture::new("targets={bins=[{name=\"app\",path=\"src/main.wave\"}]}"); + f.package("extra", "targets={lib={}},compiler=\"9.0.0\""); + fs::write(f.app.join("vex.ws"), "{format=4,name=\"app\",targets={bins=[{name=\"host\",path=\"src/main.wave\",mode=\"hosted\"},{name=\"bare\",path=\"src/bin/admin.wave\",mode=\"freestanding\",startup=\"none\",entry=\"_start\"}]},dependencies=[{name=\"extra\",path=\"../extra\",target={mode=\"freestanding\"}}]}").unwrap(); + code( + &f.run(&["fetch", "--target", "x86_64-unknown-linux-gnu"]), + 0, + ); + code( + &f.run(&[ + "build", + "--bin", + "host", + "--target", + "x86_64-unknown-linux-gnu", + ]), + 0, + ); + let calls = f.build_calls().len(); + let lock = fs::read(f.app.join("vex.lock")).unwrap(); + code( + &f.run(&["build", "--target", "x86_64-unknown-linux-gnu"]), + 3, + ); + assert_eq!(f.build_calls().len(), calls); + assert_eq!(fs::read(f.app.join("vex.lock")).unwrap(), lock); +} diff --git a/tests/project_metadata.rs b/tests/project_metadata.rs index 2b3af8c..e077f9a 100644 --- a/tests/project_metadata.rs +++ b/tests/project_metadata.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use std::collections::BTreeMap; use std::fs; use std::path::{Path, PathBuf}; diff --git a/tests/project_state.rs b/tests/project_state.rs index 24a77da..2ea39b5 100644 --- a/tests/project_state.rs +++ b/tests/project_state.rs @@ -1,3 +1,8 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +mod support; use std::fs; use std::io::{BufRead, BufReader, Read, Write}; use std::net::{TcpListener, TcpStream}; @@ -24,13 +29,7 @@ impl Fixture { fs::write(root.join("vex.lock"), "{version=2,package=[]}\n").unwrap(); fs::write(root.join("fake.rs"), include_str!("fixtures/fake_wavec.rs")).unwrap(); let compiler = root.join(if cfg!(windows) { "wavec.exe" } else { "wavec" }); - assert!(Command::new("rustc") - .arg(root.join("fake.rs")) - .arg("-o") - .arg(&compiler) - .status() - .unwrap() - .success()); + support::compile_fixture("fake_wavec", &compiler); Self { root, compiler } } fn command(&self, args: &[&str]) -> Command { diff --git a/tests/prune.rs b/tests/prune.rs index fea2ccb..7f2626c 100644 --- a/tests/prune.rs +++ b/tests/prune.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use std::collections::BTreeMap; use std::fs; use std::path::{Path, PathBuf}; diff --git a/tests/support/mod.rs b/tests/support/mod.rs index 52030a1..c3fd4ce 100644 --- a/tests/support/mod.rs +++ b/tests/support/mod.rs @@ -2,10 +2,47 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. // SPDX-License-Identifier: MPL-2.0 +#![allow(dead_code)] // Each integration test uses a different subset of helpers. use std::fmt::Write; use std::path::Path; +/// Cross CI copies verified target executables; native tests compile the same +/// source locally. A missing/stale prebuilt fixture must never fall back to an +/// emulated compiler and silently change the acceptance lane. +#[allow(dead_code)] +pub fn compile_fixture(name: &str, output: &Path) { + let source = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures") + .join(format!("{name}.rs")); + compile_fixture_from(name, &source, output); +} + +pub fn compile_fixture_from(name: &str, source: &Path, output: &Path) { + if let Some(directory) = std::env::var_os("VEX_TEST_FIXTURE_DIR") { + let directory = std::path::PathBuf::from(directory); + assert_eq!( + std::fs::read(source).unwrap(), + std::fs::read(directory.join(format!("{name}.rs"))).unwrap(), + "prebuilt fixture source differs from this checkout" + ); + std::fs::copy(directory.join(name), output).unwrap(); + } else { + let result = std::process::Command::new("rustc") + .arg("--edition=2021") + .arg(source) + .arg("-o") + .arg(output) + .output() + .unwrap(); + assert!( + result.status.success(), + "{}", + String::from_utf8_lossy(&result.stderr) + ); + } +} + /// Git's trace destinations and command-line paths do not accept Rust's /// verbatim Windows prefix. Keep filesystem spelling (not URL escaping). pub fn git_path(path: &Path) -> String { diff --git a/tests/target_metadata.rs b/tests/target_metadata.rs index abe1a27..59e6d11 100644 --- a/tests/target_metadata.rs +++ b/tests/target_metadata.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use std::collections::BTreeMap; use std::fs; use std::path::{Path, PathBuf}; diff --git a/tests/tooling/test_ci_cross.py b/tests/tooling/test_ci_cross.py new file mode 100644 index 0000000..a16646c --- /dev/null +++ b/tests/tooling/test_ci_cross.py @@ -0,0 +1,117 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 +import importlib.util +import json +import struct +from pathlib import Path +import tempfile +from types import SimpleNamespace +import unittest +from unittest.mock import patch +from tools import ci_cross, repository_checks + + +def elf(machine): + return b'\x7fELF\x02\x01' + bytes(12) + struct.pack(' 1 and command[0] != 'meson' and command[1] == 'setup': + home = Path(env['VEX_TOOLCHAIN_HOME']) + (home/'current').write_text('wavec') + (home/'wavec').write_bytes(b'compiler fixture') + + release = dict(draft=False, tag_name='v'+ci.WAVE_VERSION, id=1, + assets=[dict(id=2, name=f'wave-v{ci.WAVE_VERSION}-{target["wave_target"]}.tar.gz')]) + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + (root/'dist').mkdir() + with (patch.dict(os.environ, GH_TOKEN='host-api-secret', GITHUB_TOKEN='never-forward'), + patch.object(ci, 'ROOT', root), patch.object(ci, 'run', side_effect=host_run), + patch('sys.argv', ['ci_platform.py', target['id'], '--cross-config', '/cross/config']), + patch.object(ci.ci_cross, 'load', return_value=config), + patch.object(ci.ci_cross, 'validate_build') as validate, + patch.object(ci.ci_cross, 'verify_doctest_runner') as doctest, + patch.object(ci.ci_cross, 'check_elf') as check_elf, + patch.object(ci.ci_cross, 'execution_identity', return_value=dict(os='QEMU Linux', libc=['glibc', '2.41'], machine='riscv64')), + patch.object(ci.ci_cross, 'run_target', side_effect=guest_run), + patch.object(ci.urllib.request, 'urlopen', return_value=io.BytesIO(json.dumps(release).encode())) as request): + ci.main() + setup = next(args for args, _ in native if args[:2] == ('meson', 'setup')) + self.assertIn('-Dcargo=cargo', setup) + self.assertIn('-Dallow_unverified=false', setup) + validate.assert_called_once_with(config, target) + doctest.assert_called_once_with(config) + self.assertEqual(check_elf.call_count, 3) # debug Vex, release Vex, public Wave + self.assertEqual(request.call_args.args[0].get_header('Authorization'), 'Bearer host-api-secret') + self.assertTrue(any(args[:2] == ('meson', 'test') and '--suite' in args and 'rust' in args for args, _ in native)) + for phase in ['test-compile', 'build-release']: + self.assertTrue(any(args[:2] == ('meson', 'compile') and args[-1] == phase for args, _ in native)) + interop = next(env for args, env in native if len(args) > 1 and args[1] == 'tests/native_interop.py') + self.assertEqual(Path(interop['CC']), Path('/cross/tools')/'cc') + self.assertEqual(Path(interop['VEX_TEST_TARGET_RUNNER']), Path('/cross/tools')/'runner') + self.assertTrue(any(command[:2] == ('meson', 'test') and 'tooling' in command for command, _ in guest)) + self.assertTrue(any(command[:2] == ('meson', 'compile') and command[-1] == 'package' for command, _ in guest)) + for script in ['tools/cli_reference.py', 'tests/wave_compatibility.py']: + self.assertTrue(any(len(command) > 1 and command[1] == script for command, _ in guest)) + self.assertFalse(any(command[0] in ['cargo', 'rustc'] for command, _ in guest)) + report = json.loads((root/'dist/acceptance-linux-riscv64.json').read_text()) + self.assertEqual((report['build_host'], report['execution_arch']), ('x86_64-unknown-linux-gnu', 'riscv64')) + + def test_native_api_token_is_not_inherited_by_builds_or_smoke(self): + calls = [] + def run(*args, env=None, capture=False): + self.assertNotIn('GH_TOKEN', os.environ) + self.assertNotIn('GITHUB_TOKEN', os.environ) + calls.append((args, env)) + if len(args) > 1 and args[0] != 'meson' and args[1] == 'setup': + self.assertEqual(env['GH_TOKEN'], 'test-api-token') + home = Path(env['VEX_TOOLCHAIN_HOME']) + (home / 'current').write_text('wavec') + (home / 'wavec').write_bytes(b'compiler fixture') + elif env is not None: + self.assertNotIn('GH_TOKEN', env) + self.assertNotIn('GITHUB_TOKEN', env) + return SimpleNamespace(stdout='host: x86_64-unknown-linux-gnu\n' if args[0] == 'rustc' else 'a' * 40) + + release = {'draft': False, 'tag_name': 'v' + ci.WAVE_VERSION, 'id': 1, + 'assets': [{'id': 2, 'name': f'wave-v{ci.WAVE_VERSION}-x86_64-linux-gnu.tar.gz'}]} + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + (root / 'dist').mkdir() + with (patch.dict(os.environ, GH_TOKEN='test-api-token', GITHUB_TOKEN='unused-token'), + patch.object(ci, 'ROOT', root), patch.object(ci, 'run', side_effect=run), + patch('sys.argv', ['ci_platform.py', 'linux-amd64']), + patch.object(ci.urllib.request, 'urlopen', return_value=io.BytesIO(json.dumps(release).encode())) as request): + ci.main() + self.assertEqual(request.call_args.args[0].get_header('Authorization'), 'Bearer test-api-token') + self.assertEqual(sum(env is not None and 'GH_TOKEN' in env for _, env in calls), 1) + self.assertTrue((root / 'dist/acceptance-linux-amd64.json').is_file()) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/xpy/test_dependency_audit.py b/tests/tooling/test_dependency_audit.py similarity index 91% rename from tests/xpy/test_dependency_audit.py rename to tests/tooling/test_dependency_audit.py index d9aef70..5a65498 100644 --- a/tests/xpy/test_dependency_audit.py +++ b/tests/tooling/test_dependency_audit.py @@ -1,3 +1,7 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 import datetime as dt import importlib.util import json diff --git a/tests/tooling/test_meson.py b/tests/tooling/test_meson.py new file mode 100644 index 0000000..56a3667 --- /dev/null +++ b/tests/tooling/test_meson.py @@ -0,0 +1,192 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 +"""Exercise actual Meson/Ninja scheduling without rebuilding Rust in each test.""" +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import tomllib +import unittest +from unittest.mock import patch +from tools import automation_step + +ROOT = Path(__file__).resolve().parents[2] + + +class CargoEnvironmentTests(unittest.TestCase): + def test_riscv_linker_override_is_preserved_and_missing_linker_fails(self): + key = 'CARGO_TARGET_RISCV64GC_UNKNOWN_LINUX_GNU_LINKER' + with patch.dict(os.environ, {key: '/explicit/linker'}): + with patch.object(automation_step.shutil, 'which', return_value=None): + self.assertEqual(automation_step.environment(['cargo', 'build', '--target=riscv64gc-unknown-linux-gnu'])[key], '/explicit/linker') + env = dict(os.environ) + env.pop(key, None) + with patch.dict(os.environ, env, clear=True): + with patch.object(automation_step.shutil, 'which', return_value='/sdk/riscv64-linux-gnu-gcc'): + self.assertEqual(automation_step.environment(['cargo', 'build', '--target', 'riscv64gc-unknown-linux-gnu'])[key], '/sdk/riscv64-linux-gnu-gcc') + with patch.object(automation_step.shutil, 'which', return_value=None): + with self.assertRaisesRegex(ValueError, 'RISC-V builds require'): + automation_step.environment(['cargo', 'build', '--target', 'riscv64gc-unknown-linux-gnu']) + + +class MesonAutomationTests(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory(prefix='vex meson ') + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) + for name in ['meson.build', 'meson.options', 'Cargo.toml', 'rust-toolchain.toml', 'platforms.json']: + shutil.copy2(ROOT / name, self.root / name) + shutil.copytree(ROOT / 'tools', self.root / 'tools', ignore=shutil.ignore_patterns('__pycache__')) + self.log = self.root / 'cargo.jsonl' + fake = self.root / 'fake cargo.py' + fake.write_text('''import json, os, pathlib, sys +with open(os.environ['VEX_MESON_TEST_LOG'], 'a') as log: + log.write(json.dumps(dict(args=sys.argv[1:], toolchain=os.environ.get('RUSTUP_TOOLCHAIN'))) + '\\n') +if os.environ.get('VEX_MESON_TEST_FAIL') in sys.argv[1:]: + sys.exit(7) +''') + self.env = dict(os.environ, VEX_MESON_TEST_LOG=str(self.log)) + self.env.pop('VEX_MESON_TEST_FAIL', None) + self.cargo = '-Dcargo=' + json.dumps([sys.executable, str(fake)]) + + def run_meson(self, *args, success=True): + result = subprocess.run(['meson', *map(str, args)], cwd=self.root, + env=self.env, text=True, capture_output=True) + if success: + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + else: + self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) + return result + + def setup(self, *options): + return self.run_meson('setup', 'build', self.cargo, + '-Drelease_targets=x86_64-unknown-linux-gnu', *options) + + def calls(self): + return [json.loads(line) for line in self.log.read_text().splitlines()] if self.log.exists() else [] + + def test_default_compile_builds_the_cargo_workspace(self): + self.setup() + self.run_meson('compile', '-C', 'build') + self.assertEqual([call['args'] for call in self.calls()], [['build', '--workspace', '--locked']]) + + def test_repeated_build_and_source_change_always_reach_cargo(self): + self.setup() + self.run_meson('compile', '-C', 'build', 'build-release') + self.run_meson('compile', '-C', 'build', 'build-release') + (self.root / 'src').mkdir() + (self.root / 'src/main.rs').write_text('fn main() {}\n') + self.run_meson('compile', '-C', 'build', 'build-release') + self.assertEqual(len(self.calls()), 3) + for call in self.calls(): + self.assertEqual(call['args'], ['build', '--locked', '--release', '--target', 'x86_64-unknown-linux-gnu']) + self.assertEqual(call['toolchain'], tomllib.loads((ROOT / 'rust-toolchain.toml').read_text())['toolchain']['channel']) + # A previous successful stamp must not conceal a later failed build. + self.env['VEX_MESON_TEST_FAIL'] = 'build' + self.run_meson('compile', '-C', 'build', 'build-release', success=False) + self.assertFalse((self.root / 'build/build-x86_64-unknown-linux-gnu.stamp').exists()) + + def test_check_stops_before_tests_when_formatting_fails(self): + self.setup() + self.env['VEX_MESON_TEST_FAIL'] = 'fmt' + self.run_meson('compile', '-C', 'build', 'check', success=False) + self.assertEqual([c['args'] for c in self.calls()], [['fmt', '--check']]) + self.assertFalse((self.root / 'build/check-tooling.stamp').exists()) + + def test_release_source_gate_precedes_every_cargo_command(self): + self.setup() + subprocess.run(['git', 'init', '--quiet', str(self.root)], check=True) + result = self.run_meson('compile', '-C', 'build', 'release', success=False) + self.assertIn('official releases require a clean Git working tree', result.stdout + result.stderr) + self.assertEqual(self.calls(), []) + + def test_release_rejects_development_verifier_override(self): + self.setup('-Dallow_unverified=true') + result = self.run_meson('compile', '-C', 'build', 'release', success=False) + self.assertIn('official releases require -Dallow_unverified=false', result.stdout + result.stderr) + self.assertEqual(self.calls(), []) + + def test_unknown_target_fails_configuration_without_cargo(self): + result = self.run_meson('setup', 'build', self.cargo, + '-Drelease_targets=imaginary-target', success=False) + self.assertIn('Unsupported release target: imaginary-target', result.stdout) + self.assertEqual(self.calls(), []) + + def minimal_tooling_suite(self): + suite = self.root / 'tests/tooling' + suite.mkdir(parents=True) + (suite / 'test_fixture.py').write_text( + "import pathlib, unittest\nclass Fixture(unittest.TestCase):\n" + " def test_marker(self): pathlib.Path('tooling-marker').touch()\n") + + def test_successful_check_runs_the_complete_ordered_suite(self): + self.minimal_tooling_suite() + self.setup() + self.run_meson('compile', '-C', 'build', 'check') + self.assertTrue((self.root / 'tooling-marker').is_file()) + self.assertEqual([call['args'][0] for call in self.calls()], ['fmt', 'test', 'clippy', 'build']) + for call in self.calls()[1:]: + self.assertIn('--workspace', call['args']) + self.assertIn('--locked', call['args']) + + def test_tagged_release_runs_checks_before_release_build_and_preserves_archive_on_failure(self): + self.minimal_tooling_suite() + self.setup() + (self.root / '.gitignore').write_text('/build/\n/cargo.jsonl\n/tooling-marker\n/dist/\n') + def git(*args): + return subprocess.run(['git', '-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid', + '-c', 'commit.gpgsign=false', '-c', 'tag.gpgsign=false', *args], + cwd=self.root, check=True, capture_output=True) + git('init', '--quiet') + git('add', '.') + git('commit', '--quiet', '-m', 'fixture') + version = tomllib.loads((self.root / 'Cargo.toml').read_text())['workspace']['package']['version'] + git('tag', '-a', 'v' + version, '-m', 'fixture release') + (self.root / 'dist').mkdir() + archive = self.root / 'dist/previous-archive' + archive.write_bytes(b'preserve') + self.env['VEX_MESON_TEST_FAIL'] = '--release' + self.run_meson('compile', '-C', 'build', 'release', success=False) + self.assertEqual([call['args'][0] for call in self.calls()], ['fmt', 'test', 'clippy', 'build', 'build']) + self.assertIn('--release', self.calls()[-1]['args']) + self.assertEqual(archive.read_bytes(), b'preserve') + + def test_multiple_targets_are_ordered_deduplicated_and_fail_fast(self): + self.setup('-Drelease_targets=x86_64-unknown-linux-gnu,aarch64-unknown-linux-gnu,x86_64-unknown-linux-gnu') + self.run_meson('compile', '-C', 'build', 'build-release') + self.assertEqual([call['args'][-1] for call in self.calls()], + ['x86_64-unknown-linux-gnu', 'aarch64-unknown-linux-gnu']) + self.env['VEX_MESON_TEST_FAIL'] = 'x86_64-unknown-linux-gnu' + self.run_meson('compile', '-C', 'build', 'build-release', success=False) + self.assertEqual(len(self.calls()), 3) + + def test_clean_cleans_cargo_before_removing_distribution(self): + self.setup() + (self.root / 'dist').mkdir() + (self.root / 'dist/owned-archive').write_text('fixture') + self.env['VEX_MESON_TEST_FAIL'] = 'clean' + self.run_meson('compile', '-C', 'build', 'clean-artifacts', success=False) + self.assertTrue((self.root / 'dist/owned-archive').is_file()) + self.env.pop('VEX_MESON_TEST_FAIL') + self.run_meson('compile', '-C', 'build', 'clean-artifacts') + self.assertFalse((self.root / 'dist').exists()) + self.assertEqual([call['args'] for call in self.calls()], [['clean'], ['clean']]) + + def test_manifest_version_change_regenerates_configuration(self): + self.setup() + manifest = self.root / 'Cargo.toml' + version = tomllib.loads(manifest.read_text())['workspace']['package']['version'] + manifest.write_text(manifest.read_text().replace('version = ' + json.dumps(version), 'version = "9.8.7-rc.1"')) + result = self.run_meson('compile', '-C', 'build', 'version') + self.assertIn('Cargo version', result.stdout) + self.assertIn('9.8.7-rc.1', result.stdout) + self.assertEqual(self.calls(), []) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/xpy/test_release_gate.py b/tests/tooling/test_release_gate.py similarity index 100% rename from tests/xpy/test_release_gate.py rename to tests/tooling/test_release_gate.py diff --git a/tests/xpy/test_release_tool.py b/tests/tooling/test_release_tool.py similarity index 96% rename from tests/xpy/test_release_tool.py rename to tests/tooling/test_release_tool.py index f7a4dc8..215735b 100644 --- a/tests/xpy/test_release_tool.py +++ b/tests/tooling/test_release_tool.py @@ -28,9 +28,9 @@ root_manifest = tomllib.load(manifest_file) EXPECTED_VERSION = root_manifest["workspace"]["package"]["version"] MODULE_NAME = "vex_release_tool" -SPEC = importlib.util.spec_from_file_location(MODULE_NAME, ROOT / "x.py") +SPEC = importlib.util.spec_from_file_location(MODULE_NAME, ROOT / "tools/release_artifacts.py") if SPEC is None or SPEC.loader is None: # pragma: no cover - import setup failure - raise RuntimeError("could not load x.py") + raise RuntimeError("could not load release_artifacts.py") release_tool = importlib.util.module_from_spec(SPEC) sys.modules[MODULE_NAME] = release_tool SPEC.loader.exec_module(release_tool) @@ -295,7 +295,7 @@ def test_release_workflow_covers_targets_and_creates_the_upstream_tag(self) -> N for target in release_tool.SUPPORTED_TARGETS: self.assertIn(f"target: {target}", workflow) self.assertGreaterEqual(workflow.count(target), 2) - self.assertIn("python x.py checksum", workflow) + self.assertIn("meson compile -C build checksum", workflow) self.assertIn("--draft", workflow) self.assertIn("--generate-notes", workflow) self.assertIn('--target "$RELEASE_COMMIT"', workflow) @@ -394,10 +394,8 @@ def test_missing_verifier_preserves_archive_and_development_report_is_explicit(s self.assertEqual(report["archive"], archive.name) def test_official_release_does_not_accept_unverified_opt_in(self) -> None: - parser = release_tool.create_parser("0.0.1") - self.assertTrue(parser.parse_args(["package", "--allow-unverified"]).allow_unverified) with self.assertRaises(SystemExit) as result: - parser.parse_args(["release", "--allow-unverified"]) + release_tool.main(["verify-source", "--allow-unverified"]) self.assertEqual(result.exception.code, 2) workflow = (ROOT / ".github/workflows/release.yml").read_text() self.assertNotIn("--allow-unverified", workflow) @@ -486,29 +484,28 @@ def make_package_inputs(root: Path, target: object, binary: bytes) -> None: class ReleaseToolCliTests(unittest.TestCase): - def run_xpy(self, *arguments: str) -> subprocess.CompletedProcess[str]: + def run_config(self, *arguments: str) -> subprocess.CompletedProcess[str]: return subprocess.run( - [sys.executable, str(ROOT / "x.py"), *arguments], - cwd=ROOT, - check=False, - text=True, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, + [sys.executable, str(ROOT / "tools/build_config.py"), *arguments], + cwd=ROOT, check=False, text=True, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) def test_version_output_uses_manifest_version(self) -> None: - result = self.run_xpy("--version") + result = self.run_config("version") self.assertEqual(result.returncode, 0) - self.assertEqual(result.stdout.strip(), f"x.py {EXPECTED_VERSION}") + self.assertEqual(result.stdout.strip(), EXPECTED_VERSION) def test_list_targets_reports_all_supported_targets(self) -> None: - result = self.run_xpy("list-targets") + result = self.run_config("targets") self.assertEqual(result.returncode, 0) - for target in release_tool.SUPPORTED_TARGETS: - self.assertIn(target, result.stdout) + self.assertEqual(set(result.stdout.splitlines()), set(release_tool.SUPPORTED_TARGETS)) def test_unknown_target_is_actionable(self) -> None: - result = self.run_xpy("build", "imaginary-target") + result = subprocess.run( + [sys.executable, str(ROOT / "tools/release_artifacts.py"), "package", "imaginary-target"], + cwd=ROOT, text=True, capture_output=True, + ) self.assertEqual(result.returncode, 1) self.assertIn("error: unsupported target: imaginary-target", result.stderr) self.assertIn("Known targets:", result.stderr) diff --git a/tests/xpy/test_repository_contracts.py b/tests/tooling/test_repository_contracts.py similarity index 96% rename from tests/xpy/test_repository_contracts.py rename to tests/tooling/test_repository_contracts.py index 7134664..34e6e24 100644 --- a/tests/xpy/test_repository_contracts.py +++ b/tests/tooling/test_repository_contracts.py @@ -1,3 +1,6 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. # SPDX-License-Identifier: MPL-2.0 import io import json diff --git a/tests/tooling/test_source_policy.py b/tests/tooling/test_source_policy.py new file mode 100644 index 0000000..f993543 --- /dev/null +++ b/tests/tooling/test_source_policy.py @@ -0,0 +1,73 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 +import importlib.util +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[2] +def load(name): + spec = importlib.util.spec_from_file_location(name, ROOT/'tools'/f'{name}.py') + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module +policy = load('source_policy') +dco = load('check_dco') + +class SourcePolicyTests(unittest.TestCase): + def test_headers_and_line_endings(self): + text = ('\n'.join('# '+line for line in policy.NOTICE.splitlines())+'\n# '+policy.SPDX+'\n').encode() + policy.check_file(Path('tools/sample.py'), text) + with self.assertRaises(ValueError): policy.check_file(Path('tools/sample.py'), b'print(1)\n') + with self.assertRaises(ValueError): policy.check_file(Path('tools/sample.py'), text.replace(b'\n',b'\r\n')) + policy.check_file(Path('tests/fixtures/vex.ws'), b'{format=4}\n') + self.assertFalse(policy.needs_header(Path('docs/completions/vex.bash'))) + self.assertFalse(policy.needs_header(Path('Cargo.lock'))) + policy.check_file(Path('image.png'), b'\r\n\0') + + def test_meson_headers_and_deleted_source_files(self): + for name in ['meson.build', 'meson.options']: + self.assertTrue(policy.needs_header(Path(name))) + with self.assertRaises(ValueError): + policy.check_file(Path(name), b"project('fixture')\n") + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + subprocess.run(['git', 'init', '--quiet', str(root)], check=True) + source = root / 'removed.py' + source.write_text('old contents') + subprocess.run(['git', 'add', 'removed.py'], cwd=root, check=True) + source.unlink() + policy.validate(root) + + def test_dco_contribution_range_and_no_bot_or_merge_exemption(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + subprocess.run(['git','init','--quiet',str(root)],check=True) + def git(*args): return subprocess.check_output(['git','-c','user.name=Author','-c','user.email=author@example.invalid',*args],cwd=root,text=True).strip() + def commit(message): + git('commit','--quiet','--allow-empty','-m',message) + return git('rev-parse','HEAD') + base = commit('old unsigned base') + signed = commit('change\n\nSigned-off-by: Author ') + self.assertEqual(dco.validate(base,signed,cwd=root),1) + unsigned = commit('bot update\n\nSigned-off-by: Someone Else ') + with self.assertRaisesRegex(ValueError,'amend -s'): dco.validate(base,unsigned,cwd=root) + self.assertFalse(dco.has_signoff('bot[bot]','bot@example.invalid','no certification',cwd=root)) + self.assertFalse(dco.has_signoff('Author','author@example.invalid','Signed-off-by: Author \n\nThis is not a trailer',cwd=root)) + git('reset','--hard',signed) + git('branch','side') + main = commit('main change\n\nSigned-off-by: Author ') + git('checkout','--quiet','side') + side = commit('side change\n\nSigned-off-by: Author ') + git('checkout','--quiet','--detach',main) + subprocess.run(['git','-c','user.name=Author','-c','user.email=author@example.invalid','merge','--no-ff','--quiet',side,'-m','GitHub merge'],cwd=root,check=True,env={**os.environ,'GIT_COMMITTER_NAME':'GitHub','GIT_COMMITTER_EMAIL':'noreply@github.com'}) + merge = git('rev-parse','HEAD') + with self.assertRaises(ValueError): dco.validate(signed,merge,cwd=root,verify_merge=lambda _:False) + self.assertEqual(dco.validate(signed,merge,cwd=root,verify_merge=lambda _:True),3) + with self.assertRaises(ValueError): dco.validate('master',signed,cwd=root) + +if __name__ == '__main__': unittest.main() diff --git a/tests/wave_compatibility.py b/tests/wave_compatibility.py index a54f276..d90276a 100644 --- a/tests/wave_compatibility.py +++ b/tests/wave_compatibility.py @@ -118,6 +118,115 @@ def snapshot(): print("Format 3 targets, output layout, custom profiles, self-import and metadata passed.", flush=True) +def package_identity_smoke(vex, root, env): + for directory, version, symbol, value in (("alias_one", "1.2.3", "old_value", 11), ("alias_two", "2.0.0", "new_value", 22)): + package = root / directory + (package / "src").mkdir(parents=True) + (package / "vex.ws").write_text( + '{format=4,name="math",version="' + version + '",targets={lib={}}}', encoding="utf-8") + (package / "src/lib.wave").write_text( + f"pub fun {symbol}() -> i32 {{ return {value}; }}\n", encoding="utf-8") + app = root / "alias_app" + (app / "src").mkdir(parents=True) + (app / "vex.ws").write_text( + '{format=4,name="app",targets={bins=[{name="app",path="src/main.wave"}]},dependencies=[' + '{name="old_math",package="math",path="../alias_one",version_req="^1"},' + '{name="new_math",package="math",path="../alias_two",version_req="^2"}]}', encoding="utf-8") + (app / "src/main.wave").write_text( + 'import("old_math")::{old_value};\nimport("new_math")::{new_value};\n' + 'fun main() { println("{}", old_value() + new_value()); }\n', encoding="utf-8") + run([vex, "fetch"], app, env) + result = run([vex, "run", "--locked", "--offline"], app, env) + if result.stdout.strip() != "33": + raise RuntimeError("two package versions were not imported through their explicit aliases") + + +def feature_graph_smoke(vex, root, env, host_target): + for directory, name, version in (("feature_active", "platform", "1.0.0"), ("feature_inactive", "platform", "2.0.0"), ("feature_extra", "extras", "1.0.0")): + package = root / directory + (package / "src").mkdir(parents=True) + compiler = ',compiler="9.0.0"' if directory == "feature_inactive" else "" + (package / "vex.ws").write_text( + '{format=4,name="' + name + '",version="' + version + '",targets={lib={}}' + compiler + '}', encoding="utf-8") + (package / "src/lib.wave").write_text('pub fun value() -> i32 { return 11; }\n', encoding="utf-8") + app = root / "feature_app" + (app / "src").mkdir(parents=True) + other = "wasm32-unknown-unknown" + (app / "vex.ws").write_text( + '{format=4,name="app",targets={bins=[{name="app",path="src/main.wave"}]},dependencies=[' + '{name="platform",path="../feature_active",target={triple="' + host_target + '"}},' + '{name="platform",path="../feature_inactive",target={triple="' + other + '"}},' + '{name="extras",path="../feature_extra",optional=true}],features={default=["dep:extras"]}}', encoding="utf-8") + (app / "src/main.wave").write_text('import("platform")::{value};\nfun main() { println("{}", value()); }\n', encoding="utf-8") + run([vex, "fetch", "--target", host_target], app, env) + locked = (app / "vex.lock").read_bytes() + for flags in ([], ["--no-default-features"]): + result = run([vex, "run", "--locked", "--offline", *flags], app, env) + if result.stdout.strip() != "11": + raise RuntimeError("selected target/feature graph did not execute correctly") + result = run([vex, "metadata", "--format-version", "2", "--target", other, "--locked"], app, env) + packages = json.loads(result.stdout)["packages"] + if not any(package["name"] == "platform" and package["version"] == "2.0.0" for package in packages): + raise RuntimeError("offline target selection did not expose its locked platform package") + if (app / "vex.lock").read_bytes() != locked: + raise RuntimeError("target or feature selection rewrote the union lockfile") + + +def workspace_smoke(vex, root, env): + workspace = root / "workspace" + workspace.mkdir() + (workspace / "vex.ws").write_text( + '{format=4,compiler="0.2.1-pre-beta",workspace={members=["alpha","beta"],default_members=["beta"]}}', encoding="utf-8") + for directory, value in (("one", 11), ("two", 22)): + package = workspace / directory + (package / "src").mkdir(parents=True) + (package / "vex.ws").write_text('{format=4,name="common",version="1.0.0",targets={lib={}}}', encoding="utf-8") + (package / "src/lib.wave").write_text(f"pub fun value() -> i32 {{ return {value}; }}\n", encoding="utf-8") + for name, source in (("alpha", "one"), ("beta", "two")): + package = workspace / name + (package / "src").mkdir(parents=True) + library = "lib={}," if name == "alpha" else "" + (package / "vex.ws").write_text( + '{format=4,name="' + name + '",targets={' + library + 'bins=[{name="tool",path="src/main.wave"}]},dependencies=[{name="common",path="../' + source + '"}]}', encoding="utf-8") + if name == "alpha": + (package / "src/lib.wave").write_text('pub fun own() -> i32 { return 100; }\n', encoding="utf-8") + own = 'import("alpha")::{own};\n' if name == "alpha" else "" + expression = "own() + value()" if name == "alpha" else "value()" + (package / "src/main.wave").write_text( + 'import("common")::{value};\n' + own + 'fun main() { println("{}", ' + expression + '); }\n', encoding="utf-8") + run([vex, "fetch", "--workspace"], workspace, env) + locked = (workspace / "vex.lock").read_bytes() + run([vex, "build", "--workspace", "--locked", "--offline"], workspace, env) + for name, expected in (("alpha", "111"), ("beta", "22")): + result = run([vex, "run", "-p", name, "--locked", "--offline"], workspace, env) + if result.stdout.strip() != expected: + raise RuntimeError("workspace compiler mapping or isolated output failed for " + name) + result = run([vex, "metadata", "--format-version", "2", "--workspace", "--locked"], workspace, env) + metadata = json.loads(result.stdout) + if metadata["root"]["kind"] != "workspace" or len(metadata["workspace_members"]) != 2: + raise RuntimeError("workspace metadata did not describe both members") + if (workspace / "vex.lock").read_bytes() != locked or any((workspace / name / ".vex").exists() for name in ("alpha", "beta")): + raise RuntimeError("workspace command wrote member state or changed its locked graph") + + +def executable_test_smoke(vex, root, env): + helper = root / "test_helper" + (helper / "src").mkdir(parents=True) + (helper / "vex.ws").write_text('{format=4,name="helper",targets={lib={}}}', encoding="utf-8") + (helper / "src/lib.wave").write_text('pub fun value() -> i32 { return 42; }\n', encoding="utf-8") + app = root / "test_app" + (app / "tests").mkdir(parents=True) + (app / "vex.ws").write_text('{format=4,name="tests",targets={tests=[{name="smoke",path="tests/smoke.wave"}]},test_dependencies=[{name="helper",path="../test_helper"}]}', encoding="utf-8") + (app / "tests/smoke.wave").write_text('import("helper")::{value};\nfun main() { println("{}", value()); }\n', encoding="utf-8") + run([vex, "fetch"], app, env) + result = run([vex, "--message-file", "results.jsonl", "test", "--locked", "--offline"], app, env) + if result.stdout.strip() != "42": + raise RuntimeError("explicit test executable did not import its test dependency") + events = [json.loads(line) for line in (app / "results.jsonl").read_text(encoding="utf-8").splitlines()] + if not any(event.get("event") == "test_result" and event.get("exit_code") == 0 for event in events): + raise RuntimeError("missing executable test result") + + def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--vex", type=Path, required=True) @@ -137,6 +246,7 @@ def main(): env["PATH"] = str(args.wavec_bin.resolve()) + os.pathsep + env.get("PATH", "") with tempfile.TemporaryDirectory(prefix="vex-wave-compat-") as temporary: root = Path(temporary) + env["VEX_CACHE_HOME"] = str(root / "cache") # Python's Windows executable search does not use a replacement env PATH. # Probe this exact compiler; Vex itself still selects it through PATH. version = run([str(compiler), "--version"], root, dict(env, NO_COLOR="1")) @@ -168,6 +278,10 @@ def main(): if command == "build": host_target = plan["target"] target_profile_smoke(vex, root, env, host_target) + package_identity_smoke(vex, root, env) + feature_graph_smoke(vex, root, env, host_target) + workspace_smoke(vex, root, env) + executable_test_smoke(vex, root, env) run([vex, "check", "--target", host_target, "--locked", "--offline"], nested, env) rejected = run([vex, "build", "--emit=obj"], app, env, succeeds=False) if "unknown Vex option" not in rejected.stderr: diff --git a/tests/wavec_contract.rs b/tests/wavec_contract.rs index 166175e..399ff96 100644 --- a/tests/wavec_contract.rs +++ b/tests/wavec_contract.rs @@ -3,6 +3,7 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. // SPDX-License-Identifier: MPL-2.0 +mod support; use std::env; use std::fs; use std::path::{Path, PathBuf}; @@ -188,14 +189,7 @@ fn compile_fake_wavec(root: &Path) -> PathBuf { } else { "fake-wavec" }); - let compile = Command::new("rustc") - .args(["--edition=2021"]) - .arg(&source) - .arg("-o") - .arg(&binary) - .output() - .expect("rustc for fake wavec must start"); - assert_success(&compile, "compile fake wavec"); + support::compile_fixture("fake_wavec", &binary); binary } @@ -278,7 +272,14 @@ fn capability_preflight_rejects_targets_before_state_and_queries_once_per_invoca assert_success(&out, command); } let logged = fs::read_to_string(log).unwrap(); - assert_eq!(logged.lines().count(), 8); + assert_eq!(logged.lines().count(), 9); + assert_eq!( + logged + .lines() + .filter(|line| line.starts_with("print std-path")) + .count(), + 1 + ); assert_eq!( logged .lines() diff --git a/tests/workspace.rs b/tests/workspace.rs new file mode 100644 index 0000000..3c69c69 --- /dev/null +++ b/tests/workspace.rs @@ -0,0 +1,392 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +use serde_json::Value; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; +use std::sync::{ + atomic::{AtomicU64, Ordering}, + OnceLock, +}; +static ID: AtomicU64 = AtomicU64::new(0); +fn compiler() -> &'static Path { + static COMPILER: OnceLock = OnceLock::new(); + COMPILER.get_or_init(|| { + let root = std::env::temp_dir().join(format!("vex-ws-compiler-{}", std::process::id())); + fs::create_dir_all(&root).unwrap(); + let path = root.join(if cfg!(windows) { + "target-wavec.exe" + } else { + "target-wavec" + }); + support::compile_fixture("target_wavec", &path); + path + }) +} +struct Fixture(PathBuf); +impl Fixture { + fn new() -> Self { + let root = std::env::temp_dir().join(format!( + "vex-ws-{}-{}", + std::process::id(), + ID.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&root).unwrap(); + let f = Self(root.canonicalize().unwrap()); + f.package( + "alpha", + "alpha", + "targets={lib={},bins=[{name=\"tool\",path=\"src/main.wave\"}]}", + ); + f.package("beta", "beta", "targets={bins=[{name=\"tool\",path=\"src/main.wave\"}]},dependencies=[{name=\"alpha\",path=\"../alpha\"}]"); + f.owner("workspace={members=[\"alpha\",\"beta\"],default_members=[\"beta\"]},profiles={fast={inherits=\"release\",opt_level=3}}"); + f + } + fn owner(&self, fields: &str) { + fs::write(self.0.join("vex.ws"), format!("{{format=4,{fields}}}")).unwrap(); + } + fn package(&self, directory: &str, name: &str, fields: &str) -> PathBuf { + let path = self.0.join(directory); + fs::create_dir_all(path.join("src/nested")).unwrap(); + for file in ["main.wave", "lib.wave"] { + fs::write(path.join("src").join(file), "fun main() {}\n").unwrap(); + } + fs::write( + path.join("vex.ws"), + format!("{{format=4,name=\"{name}\",version=\"1.0.0\",{fields}}}"), + ) + .unwrap(); + path + } + fn command(&self, cwd: &Path) -> Command { + let mut command = Command::new(env!("CARGO_BIN_EXE_vex")); + command + .current_dir(cwd) + .env("VEX_WAVEC", compiler()) + .env("TARGET_COMPILER_LOG", self.0.join("compiler.jsonl")) + .env("VEX_CACHE_HOME", self.0.join("cache")) + .env("NO_COLOR", "1"); + command + } + fn run(&self, args: &[&str]) -> Output { + self.command(&self.0).args(args).output().unwrap() + } + fn metadata(&self, cwd: &Path, options: &[&str]) -> Value { + let mut args = vec!["metadata", "--format-version", "2", "--locked"]; + args.extend_from_slice(options); + let out = self.command(cwd).args(args).output().unwrap(); + code(&out, 0); + serde_json::from_slice(&out.stdout).unwrap() + } + fn calls(&self) -> Vec> { + fs::read_to_string(self.0.join("compiler.jsonl")) + .unwrap_or_default() + .lines() + .map(|l| serde_json::from_str(l).unwrap()) + .collect() + } + fn builds(&self) -> Vec> { + self.calls() + .into_iter() + .filter(|a| a.iter().any(|a| a == "build")) + .collect() + } + fn triple() -> &'static str { + if cfg!(windows) { + "x86_64-pc-windows-msvc" + } else if cfg!(target_os = "macos") { + "x86_64-apple-darwin" + } else { + "x86_64-unknown-linux-gnu" + } + } + fn artifact(&self, package: &str) -> PathBuf { + self.0 + .join("target") + .join(Self::triple()) + .join("dev/packages") + .join(package) + .join("bin") + .join(if cfg!(windows) { "tool.exe" } else { "tool" }) + } +} +impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} +fn code(out: &Output, expected: i32) { + assert_eq!( + out.status.code(), + Some(expected), + "stdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); +} +fn selected(value: &Value) -> Vec<&str> { + value["workspace_members"] + .as_array() + .unwrap() + .iter() + .filter(|p| p["selected"] == true) + .map(|p| p["name"].as_str().unwrap()) + .collect() +} + +#[test] +fn discovery_defaults_explicit_members_and_shared_lock_are_deterministic() { + let f = Fixture::new(); + let legacy = b"{version=3,package=[]}\n"; + fs::write(f.0.join("alpha/vex.lock"), legacy).unwrap(); + code(&f.run(&["fetch"]), 0); + let bytes = fs::read(f.0.join("vex.lock")).unwrap(); + let lock = lockfile::decode(std::str::from_utf8(&bytes).unwrap()).unwrap(); + assert_eq!(lock.roots.len(), 2); + assert_eq!(selected(&f.metadata(&f.0, &[])), ["beta"]); + assert_eq!( + selected(&f.metadata(&f.0.join("alpha/src/nested"), &[])), + ["alpha"] + ); + assert_eq!( + selected(&f.metadata(&f.0, &["--workspace"])), + ["alpha", "beta"] + ); + assert_eq!( + selected(&f.metadata( + &f.0.join("alpha"), + &["--manifest-path", f.0.join("beta/vex.ws").to_str().unwrap()] + )), + ["beta"] + ); + assert_eq!(fs::read(f.0.join("vex.lock")).unwrap(), bytes); + assert_eq!(fs::read(f.0.join("alpha/vex.lock")).unwrap(), legacy); + assert!(!f.0.join("alpha/.vex").exists()); + assert!(!f.0.join("beta/.vex").exists()); + code(&f.run(&["metadata"]), 3); + code(&f.run(&["build", "-p", "typo"]), 3); +} +#[test] +fn batch_plans_every_member_and_namespaces_equal_artifact_names() { + let f = Fixture::new(); + code(&f.run(&["fetch"]), 0); + let dry = f.run(&["build", "--workspace", "--dry-run", "--locked"]); + code(&dry, 0); + let value: Value = serde_json::from_slice(&dry.stdout).unwrap(); + assert_eq!(value["plans"].as_array().unwrap().len(), 3); + assert!(!f.0.join("target").exists()); + code(&f.run(&["build", "--workspace", "--locked"]), 0); + assert!(f.artifact("alpha").is_file()); + assert!(f.artifact("beta").is_file()); + assert!(!f.0.join("alpha/target").exists()); + code(&f.run(&["build", "-p", "beta", "--profile", "fast"]), 0); + assert!(f.builds().iter().any(|args| args.contains(&"-O3".into()))); +} +#[test] +fn last_member_preflight_failure_prevents_all_compiler_execution() { + let f = Fixture::new(); + code(&f.run(&["fetch"]), 0); + let out = f + .command(&f.0) + .args(["build", "--workspace"]) + .env("TARGET_PLAN_FAIL_INPUT", "beta/src/main.wave") + .output() + .unwrap(); + code(&out, 4); + assert!(!f.0.join("target").exists()); + assert!(f + .builds() + .iter() + .all(|args| args.contains(&"--dry-run".into()))); + fs::remove_file(f.0.join("beta/src/main.wave")).unwrap(); + let calls = f.calls().len(); + code(&f.run(&["build", "--workspace"]), 3); + assert_eq!(f.calls().len(), calls); +} +#[test] +fn member_run_uses_member_directory_and_releases_workspace_lease() { + let f = Fixture::new(); + code(&f.run(&["fetch"]), 0); + let out = f + .command(&f.0) + .args([ + "run", + "-p", + "beta", + "--locked", + "--offline", + "--", + "argument with spaces", + ]) + .env("TARGET_PROGRAM_EXIT", "29") + .env("TARGET_PROGRAM_EXPECT_CWD", f.0.join("beta")) + .env( + "TARGET_PROGRAM_CHECK_LOCK_RELEASE", + env!("CARGO_BIN_EXE_vex"), + ) + .output() + .unwrap(); + code(&out, 29); + assert!(String::from_utf8_lossy(&out.stdout).contains("argument with spaces")); + code(&f.run(&["run", "--workspace"]), 3); +} +#[test] +fn workspace_members_unify_features_but_keep_compiler_alias_maps_separate() { + let f = Fixture::new(); + for name in ["x", "y"] { + f.package(name, name, "targets={lib={}}"); + } + f.package("shared", "shared", "targets={lib={}},dependencies=[{name=\"x\",path=\"../x\",optional=true},{name=\"y\",path=\"../y\",optional=true}],features={x=[\"dep:x\"],y=[\"dep:y\"]}"); + f.package("alpha","alpha","targets={bins=[{name=\"tool\",path=\"src/main.wave\"}]},dependencies=[{name=\"shared\",path=\"../shared\"}],features={a=[\"shared/x\"]}"); + f.package("beta","beta","targets={bins=[{name=\"tool\",path=\"src/main.wave\"}]},dependencies=[{name=\"shared\",path=\"../shared\"}],features={b=[\"shared/y\"]}"); + code( + &f.run(&["fetch", "--workspace", "--features", "alpha/a,beta/b"]), + 0, + ); + let value = f.metadata(&f.0, &["--workspace", "--features", "alpha/a,beta/b"]); + for name in ["x", "y"] { + assert!(value["packages"] + .as_array() + .unwrap() + .iter() + .any(|p| p["name"] == name)); + } + assert_eq!(value["selections"].as_array().unwrap().len(), 2); + code(&f.run(&["fetch", "--workspace", "--features", "a"]), 3); + f.package("one", "common", "targets={lib={}}"); + f.package("two", "common", "targets={lib={}}"); + f.package("alpha","alpha","targets={bins=[{name=\"tool\",path=\"src/main.wave\"}]},dependencies=[{name=\"common\",path=\"../one\"}]"); + f.package("beta","beta","targets={bins=[{name=\"tool\",path=\"src/main.wave\"}]},dependencies=[{name=\"common\",path=\"../two\"}]"); + code(&f.run(&["build", "--workspace"]), 0); +} + +#[test] +fn exclusions_nested_ownership_duplicate_names_and_escapes_are_explicit() { + let f = Fixture::new(); + f.package( + "alpha", + "alpha", + "targets={lib={}},workspace={members=[\"sub\"]}", + ); + f.package("alpha/sub", "sub", "targets={lib={}}"); + code(&f.run(&["fetch"]), 3); + assert!(!f.0.join(".vex").exists()); + f.owner( + "workspace={members=[\"alpha\",\"beta\"],exclude=[\"alpha\"],default_members=[\"beta\"]}", + ); + code(&f.run(&["fetch"]), 0); + let value = f.metadata(&f.0, &[]); + assert_eq!(value["root"]["members"], serde_json::json!(["beta"])); + let out = f.command(&f.0.join("alpha")).arg("fetch").output().unwrap(); + code(&out, 0); + assert!(f.0.join("alpha/vex.lock").exists()); + let other = Fixture::new(); + other.package("beta", "ALPHA", "targets={lib={}}"); + code(&other.run(&["fetch"]), 3); + assert!(!other.0.join(".vex").exists()); + for member in ["../outside", "/absolute", "alpha/*", "alpha//src"] { + other.owner(&format!( + "workspace={{members=[{}]}}", + serde_json::to_string(member).unwrap() + )); + code(&other.run(&["fetch"]), 3); + assert!(!other.0.join(".vex").exists()); + } +} + +mod support; +fn git(path: &Path, args: &[&str]) -> String { + let out = Command::new("git") + .current_dir(path) + .args([ + "-c", + "user.name=Vex Test", + "-c", + "user.email=test@example.invalid", + ]) + .args(args) + .output() + .unwrap(); + code(&out, 0); + String::from_utf8(out.stdout).unwrap().trim().into() +} +fn commit(path: &Path) -> String { + git(path, &["add", "."]); + git(path, &["commit", "-m", "fixture"]); + git(path, &["rev-parse", "HEAD"]) +} +fn commits(f: &Fixture) -> std::collections::BTreeMap { + lockfile::decode(&fs::read_to_string(f.0.join("vex.lock")).unwrap()) + .unwrap() + .packages + .iter() + .filter_map(|p| match &p.source { + lockfile::LockedSource::Git { commit, .. } => { + Some((p.import_name().to_owned(), commit.clone())) + } + _ => None, + }) + .collect() +} +#[test] +fn selected_member_update_preserves_unrelated_bindings_in_the_same_repository() { + let f = Fixture::new(); + for directory in ["repo/one", "repo/two"] { + f.package(directory, "common", "targets={lib={}}"); + } + let repo = f.0.join("repo"); + git(&repo, &["init", "--initial-branch=master"]); + let old = commit(&repo); + let url = support::git_url(&repo); + for (member, alias, subdir) in [("alpha", "one", "one"), ("beta", "two", "two")] { + f.package(member,member,&format!("targets={{bins=[{{name=\"tool\",path=\"src/main.wave\"}}]}},dependencies=[{{name=\"{alias}\",package=\"common\",git=\"{url}\",branch=\"master\",subdir=\"{subdir}\"}}]")); + } + code(&f.run(&["fetch", "--workspace"]), 0); + assert!(commits(&f).values().all(|value| value == &old)); + fs::write(repo.join("one/revision"), "new").unwrap(); + let new = commit(&repo); + code(&f.run(&["update", "one", "-p", "alpha"]), 0); + let pins = commits(&f); + assert_eq!(pins["one"], new); + assert_eq!(pins["two"], old); + code(&f.run(&["update", "one", "-p", "beta"]), 3); + assert_eq!(commits(&f), pins); + code(&f.run(&["update", "-p", "beta"]), 0); + assert!(commits(&f).values().all(|value| value == &new)); + let bytes = fs::read(f.0.join("vex.lock")).unwrap(); + fs::rename(&repo, repo.with_extension("hidden")).unwrap(); + code( + &f.run(&["fetch", "--workspace", "--locked", "--offline"]), + 0, + ); + assert_eq!(fs::read(f.0.join("vex.lock")).unwrap(), bytes); +} + +#[cfg(unix)] +#[test] +fn metadata_rejects_unrepresentable_member_paths_without_panicking_or_writing() { + use std::os::unix::{ffi::OsStringExt, fs::symlink}; + let f = Fixture::new(); + code(&f.run(&["fetch"]), 0); + let bytes = fs::read(f.0.join("vex.lock")).unwrap(); + let invalid = f.0.join(std::ffi::OsString::from_vec(vec![b'x', 0xff])); + if let Err(error) = fs::rename(f.0.join("alpha"), &invalid) { + // APFS rejects ill-formed UTF-8 filenames with EILSEQ before Vex can + // see them. Still exercise the Vex rejection on filesystems that permit + // this fixture; other filesystem errors must remain test failures. + if cfg!(target_os = "macos") && error.raw_os_error() == Some(92) { + assert!(f.0.join("alpha/vex.ws").is_file()); + assert_eq!(fs::read(f.0.join("vex.lock")).unwrap(), bytes); + eprintln!("filesystem rejected the non-UTF-8 filename (EILSEQ)"); + return; + } + panic!("cannot prepare non-UTF-8 fixture: {error}"); + } + symlink(&invalid, f.0.join("alpha")).unwrap(); + let out = f.run(&["metadata", "--format-version", "2"]); + code(&out, 3); + assert!(String::from_utf8_lossy(&out.stderr).contains("non-UTF-8")); + assert_eq!(fs::read(f.0.join("vex.lock")).unwrap(), bytes); +} diff --git a/tests/wson_compatibility.rs b/tests/wson_compatibility.rs index 5ff2afa..f1a37a5 100644 --- a/tests/wson_compatibility.rs +++ b/tests/wson_compatibility.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use std::fs; use std::path::PathBuf; use std::process::Command; diff --git a/tests/xpy/test_ci_platform.py b/tests/xpy/test_ci_platform.py deleted file mode 100644 index 3858ad7..0000000 --- a/tests/xpy/test_ci_platform.py +++ /dev/null @@ -1,51 +0,0 @@ -# SPDX-License-Identifier: MPL-2.0 -import importlib.util -import io -import json -import os -from pathlib import Path -import tempfile -from types import SimpleNamespace -import unittest -from unittest.mock import patch - -ROOT = Path(__file__).resolve().parents[2] -spec = importlib.util.spec_from_file_location('ci_platform', ROOT / 'tools/ci_platform.py') -ci = importlib.util.module_from_spec(spec) -spec.loader.exec_module(ci) - - -class PlatformAcceptanceTests(unittest.TestCase): - def test_native_api_token_is_not_inherited_by_builds_or_smoke(self): - calls = [] - def run(*args, env=None, capture=False): - self.assertNotIn('GH_TOKEN', os.environ) - self.assertNotIn('GITHUB_TOKEN', os.environ) - calls.append((args, env)) - if len(args) > 1 and args[1] == 'setup': - self.assertEqual(env['GH_TOKEN'], 'test-api-token') - home = Path(env['VEX_TOOLCHAIN_HOME']) - (home / 'current').write_text('wavec') - (home / 'wavec').write_bytes(b'compiler fixture') - elif env is not None: - self.assertNotIn('GH_TOKEN', env) - self.assertNotIn('GITHUB_TOKEN', env) - return SimpleNamespace(stdout='host: x86_64-unknown-linux-gnu\n' if args[0] == 'rustc' else 'a' * 40) - - release = {'draft': False, 'tag_name': 'v' + ci.WAVE_VERSION, 'id': 1, - 'assets': [{'id': 2, 'name': f'wave-v{ci.WAVE_VERSION}-x86_64-linux-gnu.tar.gz'}]} - with tempfile.TemporaryDirectory() as temporary: - root = Path(temporary) - (root / 'dist').mkdir() - with (patch.dict(os.environ, GH_TOKEN='test-api-token', GITHUB_TOKEN='unused-token'), - patch.object(ci, 'ROOT', root), patch.object(ci, 'run', side_effect=run), - patch('sys.argv', ['ci_platform.py', 'linux-amd64']), - patch.object(ci.urllib.request, 'urlopen', return_value=io.BytesIO(json.dumps(release).encode())) as request): - ci.main() - self.assertEqual(request.call_args.args[0].get_header('Authorization'), 'Bearer test-api-token') - self.assertEqual(sum(env is not None and 'GH_TOKEN' in env for _, env in calls), 1) - self.assertTrue((root / 'dist/acceptance-linux-amd64.json').is_file()) - - -if __name__ == '__main__': - unittest.main() diff --git a/toolchain/Cargo.toml b/toolchain/Cargo.toml index 3649e79..b0ccdca 100644 --- a/toolchain/Cargo.toml +++ b/toolchain/Cargo.toml @@ -1,3 +1,7 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 [package] name = "toolchain" version.workspace = true @@ -13,6 +17,6 @@ serde_json.workspace = true flate2 = "1" process.workspace = true semver = "1" -sha2 = "0.10" +sha2 = "0.11.1" tar = "0.4" zip = { version = "9", default-features = false, features = ["deflate"] } diff --git a/toolchain/src/artifact.rs b/toolchain/src/artifact.rs index 08b448f..e12dbf8 100644 --- a/toolchain/src/artifact.rs +++ b/toolchain/src/artifact.rs @@ -1,3 +1,10 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +#[cfg(test)] +#[path = "../../tests/support/mod.rs"] +mod test_support; use flate2::read::GzDecoder; use serde_json::Value; use sha2::{Digest, Sha256}; @@ -575,7 +582,7 @@ fn verify_checksum(path: &Path, expected: &str) -> Result<(), String> { } hasher.update(&buffer[..size]); } - if format!("{:x}", hasher.finalize()) != expected { + if hex_digest(hasher.finalize()) != expected { return Err(error( "archive SHA-256 mismatch; existing installation preserved", )); @@ -720,6 +727,22 @@ fn sync_tree(root: &Path) -> Result<(), String> { state::sync_dir(root).map_err(error) } +// Keep persisted IDs/checksums as zero-padded lowercase SHA-256 hex. The +// digest output type no longer implements LowerHex in sha2 0.11. +fn hex_digest(bytes: impl AsRef<[u8]>) -> String { + const DIGITS: &[u8; 16] = b"0123456789abcdef"; + bytes + .as_ref() + .iter() + .flat_map(|&byte| { + [ + char::from(DIGITS[(byte >> 4) as usize]), + char::from(DIGITS[(byte & 15) as usize]), + ] + }) + .collect() +} + #[cfg(test)] mod tests { use super::*; @@ -756,31 +779,17 @@ mod tests { let source = fixture.0.join("compiler.rs"); fs::write( &source, - r#" - fn main() { - if std::env::current_exe().unwrap().file_stem().unwrap() == "broken" { - eprintln!("missing compiler runtime"); - std::process::exit(7); - } - if std::env::var_os("NO_COLOR").is_some() { - println!("wavec 0.2.1-pre-beta (platform)\n backend: LLVM 21"); - } else { - println!("\x1b[32mwavec\x1b[0m \x1b[32m0.2.1-pre-beta\x1b[0m"); - } - } - "#, + include_str!("../../tests/fixtures/version_probe.rs"), ) .unwrap(); let binary = fixture .0 .join(if cfg!(windows) { "wavec.exe" } else { "wavec" }); - assert!(Command::new("rustc") - .arg(source) - .arg("-o") - .arg(&binary) - .status() - .unwrap() - .success()); + super::test_support::compile_fixture_from( + "version_probe", + &Path::new(env!("CARGO_MANIFEST_DIR")).join("../tests/fixtures/version_probe.rs"), + &binary, + ); verify_binary_version(&binary, "0.2.1-pre-beta").unwrap(); let mismatch = verify_binary_version(&binary, "0.2.0-pre-beta").unwrap_err(); assert!(mismatch.contains("does not match") && mismatch.contains("0.2.1-pre-beta")); @@ -932,7 +941,7 @@ mod tests { let name = format!("{package}.{extension}"); let archive = stage.join("archive"); fake_archive(&archive, &package, zip, failure != "payload"); - let digest = format!("{:x}", Sha256::digest(fs::read(&archive).unwrap())); + let digest = hex_digest(Sha256::digest(fs::read(&archive).unwrap())); let result = (|| -> Result { let release = fake_release(if failure == "missing" { "wrong-asset" diff --git a/toolchain/src/lib.rs b/toolchain/src/lib.rs index 6cb9be0..1a89938 100644 --- a/toolchain/src/lib.rs +++ b/toolchain/src/lib.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use std::env; use std::fs::{self, File, OpenOptions}; use std::io; diff --git a/toolchain/src/unix.rs b/toolchain/src/unix.rs index 1fe6ced..9085088 100644 --- a/toolchain/src/unix.rs +++ b/toolchain/src/unix.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use std::fs; use std::process::{Command, Stdio}; diff --git a/toolchain/src/windows.rs b/toolchain/src/windows.rs index 0890d42..166c8c2 100644 --- a/toolchain/src/windows.rs +++ b/toolchain/src/windows.rs @@ -1,3 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 use std::fs; use std::process::{Command, Stdio}; diff --git a/tools/automation_step.py b/tools/automation_step.py new file mode 100644 index 0000000..6ba67a6 --- /dev/null +++ b/tools/automation_step.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python3 +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 + +"""Execute one Meson step; record success only after the command succeeds.""" +import argparse +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tomllib + +ROOT = Path(__file__).resolve().parents[1] + + +def environment(arguments): + env = dict(os.environ) + with (ROOT / 'rust-toolchain.toml').open('rb') as source: + env['RUSTUP_TOOLCHAIN'] = tomllib.load(source)['toolchain']['channel'] + targets = [arg.split('=', 1)[1] for arg in arguments if arg.startswith('--target=')] + targets += [arguments[i+1] for i, arg in enumerate(arguments[:-1]) if arg == '--target'] + if 'riscv64gc-unknown-linux-gnu' in targets: + key = 'CARGO_TARGET_RISCV64GC_UNKNOWN_LINUX_GNU_LINKER' + if key not in env: + linker = shutil.which('riscv64-linux-gnu-gcc') + if linker is None: + raise ValueError(f'RISC-V builds require riscv64-linux-gnu-gcc or {key}') + env[key] = linker + return env + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--stamp', type=Path) + parser.add_argument('command', nargs=argparse.REMAINDER) + args = parser.parse_args() + command = args.command[1:] if args.command[:1] == ['--'] else args.command + if not command: + parser.error('a command is required') + try: + if args.stamp: + args.stamp.unlink(missing_ok=True) + result = subprocess.run(command, cwd=ROOT, env=environment(command), check=False) + if result.returncode == 0 and args.stamp: + args.stamp.touch() + return result.returncode + except (OSError, ValueError) as error: + print(f'error: {error}', file=sys.stderr) + return 1 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tools/build_config.py b/tools/build_config.py new file mode 100644 index 0000000..dc6e5a4 --- /dev/null +++ b/tools/build_config.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 + +"""Read build configuration from the existing Cargo/platform sources of truth.""" +import argparse +import sys +from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from tools.release_artifacts import (PLATFORMS, SUPPORTED_TARGETS, ReleaseError, + detect_host_target, load_version) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('query', choices=['version', 'host', 'targets', 'platforms', 'list-targets']) + args = parser.parse_args() + try: + if args.query == 'version': + print(load_version()) + elif args.query == 'host': + print(detect_host_target()) + elif args.query == 'targets': + print('\n'.join(SUPPORTED_TARGETS)) + elif args.query == 'list-targets': + try: + host = detect_host_target() + except ReleaseError: + host = '' + print(f'Host: {host}\nSupported release targets:') + for target in SUPPORTED_TARGETS.values(): + marker = ' (native default)' if target.triple == host else '' + print(f' {target.triple:<36} {target.platform:<8} {target.architecture:<13} {target.archive}{marker}') + else: + print('\n'.join(row['id'] for row in PLATFORMS)) + except ReleaseError as error: + print(f'error: {error}', file=sys.stderr) + return 1 + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tools/check_dco.py b/tools/check_dco.py new file mode 100644 index 0000000..6655d20 --- /dev/null +++ b/tools/check_dco.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 +"""Validate only contribution commits in base..head; never modify Git or GitHub.""" +import argparse +from email.utils import parseaddr +import json +import os +import re +import subprocess +import urllib.request + + +def git(*args, cwd=None, input=None): + return subprocess.check_output(['git', *args], cwd=cwd, input=input, text=True, encoding='utf-8') + + +def github_merge(sha): + repository = os.environ.get('GITHUB_REPOSITORY', '') + token = os.environ.get('GITHUB_TOKEN') + if not token or not re.fullmatch(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+', repository): + return False + request = urllib.request.Request(f'https://api.github.com/repos/{repository}/commits/{sha}', + headers={'Authorization': 'Bearer ' + token, 'Accept': 'application/vnd.github+json', 'User-Agent': 'Vex-DCO-check'}) + with urllib.request.urlopen(request, timeout=30) as response: + value = json.load(response) + return (value.get('sha') == sha and len(value.get('parents', [])) > 1 + and (value.get('committer') or {}).get('login') == 'web-flow' + and value.get('commit', {}).get('verification', {}).get('verified') is True) + + +def has_signoff(name, email, message, cwd=None): + trailers = git('interpret-trailers', '--parse', cwd=cwd, input=message) + for line in trailers.splitlines(): + key, separator, value = line.partition(':') + if separator and key.lower() == 'signed-off-by': + signed_name, signed_email = parseaddr(value.strip()) + if signed_name == name and signed_email.casefold() == email.casefold(): + return True + return False + + +def validate(base, head, cwd=None, verify_merge=github_merge): + for value in [base, head]: + if not re.fullmatch(r'[0-9a-f]{40}|[0-9a-f]{64}', value): + raise ValueError('DCO requires exact base/head commit IDs') + git('cat-file', '-e', value + '^{commit}', cwd=cwd) + commits = git('rev-list', '--reverse', f'{base}..{head}', cwd=cwd).splitlines() + failures = [] + for sha in commits: + raw = git('show', '-s', '--format=%P%x00%an%x00%ae%x00%cn%x00%ce%x00%B', sha, cwd=cwd) + parents, name, email, committer, committer_email, message = raw.split('\0', 5) + if (len(parents.split()) > 1 and committer == 'GitHub' + and committer_email == 'noreply@github.com' and verify_merge(sha)): + continue + # Bots and ordinary merges follow the same author sign-off contract. + if not has_signoff(name, email, message, cwd=cwd): + failures.append(f'{sha}: missing author Signed-off-by: {name!r} <{email}>') + if failures: + raise ValueError('\n'.join(failures) + '\nAdd your own certification with git commit --amend -s, or rebase the affected contribution commits with sign-off; then push your contribution branch.') + return len(commits) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--base', required=True) + parser.add_argument('--head', required=True) + args = parser.parse_args() + print(f'Verified DCO for {validate(args.base, args.head)} contribution commits.') diff --git a/tools/check_links.py b/tools/check_links.py index 6cd82ee..7405676 100644 --- a/tools/check_links.py +++ b/tools/check_links.py @@ -1,4 +1,7 @@ #!/usr/bin/env python3 +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. # SPDX-License-Identifier: MPL-2.0 """Check tracked Markdown file links and local heading anchors without a network.""" import re diff --git a/tools/ci_cross.Dockerfile b/tools/ci_cross.Dockerfile new file mode 100644 index 0000000..9c81f54 --- /dev/null +++ b/tools/ci_cross.Dockerfile @@ -0,0 +1,9 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 +FROM debian@sha256:4876fdea29cac1a33a3195f1eb1952feb1fca7dd6dd00be3e2f1879cf20d34d2 +ARG GNU_TARGET +RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ + gcc-${GNU_TARGET} g++-${GNU_TARGET} binutils-${GNU_TARGET} \ + && rm -rf /var/lib/apt/lists/* diff --git a/tools/ci_cross.py b/tools/ci_cross.py new file mode 100644 index 0000000..d52ee0b --- /dev/null +++ b/tools/ci_cross.py @@ -0,0 +1,253 @@ +#!/usr/bin/env python3 +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 +"""Compile on amd64; run complete target process trees in pinned QEMU guests.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import platform +import shlex +import shutil +import struct +import subprocess +import sys +import tempfile +import uuid + +ROOT = Path(__file__).resolve().parents[1] +TARGETS = {'linux-riscv64': ('riscv64-linux-gnu', 243, 'riscv64'), + 'linux-loongarch64': ('loongarch64-linux-gnu', 258, 'loongarch64')} +FIXTURES = ('fake_wavec', 'target_wavec', 'native_wavec', 'artifact_wavec', 'doctor_tools', 'version_probe') + + +def call(*args, **kwargs): + print('+', shlex.join(map(str, args)), flush=True) + try: + return subprocess.run(list(map(str, args)), check=True, **kwargs) + except subprocess.CalledProcessError as error: + if error.stdout: + print(error.stdout, end='', flush=True) + if error.stderr: + print(error.stderr, end='', file=sys.stderr, flush=True) + raise + + +def load(path): + config = json.loads(Path(path).read_text()) + if config.get('schema_version') != 1 or config.get('platform') not in TARGETS: + raise ValueError('invalid cross execution configuration') + return config + + +def check_elf(path, machine): + with Path(path).open('rb') as binary: + header = binary.read(20) + if (len(header) != 20 or header[:6] != b'\x7fELF\x02\x01' + or struct.unpack(' 2 and sys.argv[1] in {'run', 'tool'}: + mode, path, *args = sys.argv[1:] + config = load(path) + if mode == 'run': + check_elf(args[0], TARGETS[config['platform']][1]) + os.execvp('docker', guest_command(config, args, os.environ)) + tool, *arguments = args + if tool == 'rustc': + command = [config['rustc'], '--target', config['target'], '-C', + f'linker={Path(config["bin"])/"cc"}', *arguments] + else: + program = config['gnu_target']+{'cc': '-gcc', 'c++': '-g++', 'ar': '-ar'}[tool] + command = ['docker', 'exec', '--workdir', str(Path.cwd()), config['sdk'], program, *arguments] + os.execvp(command[0], command) + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('platform', choices=TARGETS) + orchestrate(parser.parse_args().platform, api_token) + + +if __name__ == '__main__': + main() diff --git a/tools/ci_guest.sh b/tools/ci_guest.sh index 4ab4629..9652316 100644 --- a/tools/ci_guest.sh +++ b/tools/ci_guest.sh @@ -1,24 +1,32 @@ #!/bin/sh +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. # SPDX-License-Identifier: MPL-2.0 set -eu export CARGO_BUILD_JOBS=2 export RUST_TEST_THREADS=2 case "$(uname -s)" in Linux) - vex_guest_python=python3 - apt-get update - DEBIAN_FRONTEND=noninteractive apt-get install -y ca-certificates curl git python3 build-essential pkg-config gh procps + echo 'QEMU Linux acceptance uses tools/ci_cross.py on amd64' >&2 + exit 2 ;; FreeBSD) vex_guest_python=python3.11 - pkg install -y ca_root_nss curl git python311 gmake pkgconf gh + pkg install -y ca_root_nss curl git python311 ninja gmake pkgconf gh ;; *) echo 'unsupported guest OS' >&2; exit 1;; esac +# python311 ships ensurepip and its bundled wheels; venv bootstraps pip +# without requiring a separately packaged Python-flavor pip. +"$vex_guest_python" -m venv /tmp/vex-meson +/tmp/vex-meson/bin/python -m pip install -r tools/requirements-build.txt +export PATH="/tmp/vex-meson/bin:$PATH" curl --proto '=https' --tlsv1.2 -fsSL https://sh.rustup.rs -o /tmp/vex-rustup.sh sh /tmp/vex-rustup.sh -y --profile minimal --default-toolchain 1.96.0 -export PATH="$HOME/.cargo/bin:/usr/local/bin:$PATH" +export PATH="$HOME/.cargo/bin:/tmp/vex-meson/bin:/usr/local/bin:$PATH" # The whole process tree (Git, fake compiler, real compiler, user programs) # executes in this target environment through binfmt or the FreeBSD kernel. git config --global --add safe.directory "$(pwd)" -"$vex_guest_python" tools/ci_platform.py "$1" +meson setup build -Drelease_targets=x86_64-unknown-freebsd -Dacceptance_platform="$1" +meson compile -C build acceptance diff --git a/tools/ci_platform.py b/tools/ci_platform.py index 8dd000e..eac2a93 100644 --- a/tools/ci_platform.py +++ b/tools/ci_platform.py @@ -1,4 +1,7 @@ #!/usr/bin/env python3 +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. # SPDX-License-Identifier: MPL-2.0 """Execute the complete acceptance lane inside the target OS/architecture.""" import argparse @@ -14,6 +17,8 @@ import urllib.error ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +from tools import ci_cross PLATFORMS = json.loads((ROOT / 'platforms.json').read_text())['platforms'] WAVE_PIN = json.loads((ROOT / 'tools/wave-release.json').read_text()) WAVE_VERSION = WAVE_PIN['version'] @@ -32,17 +37,53 @@ def main(): os.environ.pop('GITHUB_TOKEN', None) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('platform', choices=[p['id'] for p in PLATFORMS]) + parser.add_argument('--cross-config', type=Path) args = parser.parse_args() target = next(p for p in PLATFORMS if p['id'] == args.platform) + cross = ci_cross.load(args.cross_config) if args.cross_config else None host = run('rustc', '-vV', capture=True).stdout - if f"host: {target['rust_target']}\n" not in host: - raise RuntimeError('acceptance must execute inside the target environment, not a cross-build host') - run(sys.executable, '-m', 'unittest', 'discover', '-s', 'tests/xpy', '-v') - run('cargo', 'test', '--workspace', '--locked') - run(sys.executable, 'tools/cli_reference.py', '--vex', ROOT/'target/debug'/('vex.exe' if target['os'] == 'windows' else 'vex')) - run(sys.executable, 'x.py', 'build', target['rust_target']) - run(sys.executable, 'x.py', 'package', target['rust_target']) + if cross: + ci_cross.validate_build(cross, target) + if f"host: {cross['build_host']}\n" not in host or target['executor'] != 'qemu': + raise RuntimeError('cross acceptance requires its recorded amd64 compiler host') + identity = ci_cross.execution_identity(cross) + else: + if f"host: {target['rust_target']}\n" not in host: + raise RuntimeError('acceptance must execute inside the target environment, not a cross-build host') + identity = dict(os=platform.platform(), libc=platform.libc_ver(), machine=platform.machine()) + + def execute(*command, env=None): + if cross: + return ci_cross.run_target(cross, command, env, cwd=ROOT) + return run(*command, env=env) + + python = 'python3' if cross else sys.executable + build_dir = ROOT / 'build' / ('acceptance-' + target['id']) + guest_dir = ROOT / 'build' / ('acceptance-' + target['id'] + '-guest') if cross else build_dir + # Reused local configurations must not weaken acceptance with a development + # Cargo substitute or an unverified-package opt-in. + options = ['-Drelease_targets=' + target['rust_target'], + '-Dcargo=cargo', '-Dallow_unverified=false', '-Dacceptance_platform='] + run('meson', 'setup', '--reconfigure', build_dir, ROOT, *options, + '-Dtest_target=' + (target['rust_target'] if cross else '')) + if cross: + execute('meson', 'setup', '--reconfigure', guest_dir, ROOT, *options) + execute('meson', 'test', '-C', guest_dir, '--no-rebuild', '--suite', 'tooling', '--print-errorlogs', '--verbose') + if cross: + ci_cross.verify_doctest_runner(cross) + debug = ROOT/'target'/target['rust_target']/'debug/vex' if cross else ROOT/'target/debug'/('vex.exe' if target['os'] == 'windows' else 'vex') + if cross: + run('meson', 'compile', '-C', build_dir, 'test-compile') + ci_cross.check_elf(debug, ci_cross.TARGETS[target['id']][1]) + run('meson', 'test', '-C', build_dir, '--no-rebuild', '--suite', 'rust', '--print-errorlogs', '--verbose') + execute(python, 'tools/cli_reference.py', '--vex', debug) + run('meson', 'compile', '-C', build_dir, 'build-release') binary = ROOT / 'target' / target['rust_target'] / 'release' / ('vex.exe' if target['os'] == 'windows' else 'vex') + if cross: + ci_cross.check_elf(binary, ci_cross.TARGETS[target['id']][1]) + # Packaging runs inside the target userspace; the Rust compiler stays on amd64. + package_env = dict(os.environ, VEX_RELEASE_HOST=target['rust_target']) if cross else None + execute('meson', 'compile', '-C', guest_dir, 'package', env=package_env) # Authentication changes API rate limits, never public-release acceptance. url = f'https://api.github.com/repos/wavefnd/Wave/releases/tags/v{WAVE_VERSION}' headers = {'User-Agent': 'Vex-release-acceptance'} @@ -64,23 +105,31 @@ def main(): with tempfile.TemporaryDirectory(prefix='vex-compiler-acceptance-') as temporary: env = dict(os.environ, VEX_TOOLCHAIN_HOME=temporary, VEX_WAVEC_ARCHIVE_SHA256=WAVE_PIN['archives'][target['id']]) env.pop('VEX_WAVEC', None) - setup_env = dict(env, GH_TOKEN=api_token) if api_token else env - run(binary, 'setup', 'wavec', '--version', WAVE_VERSION, env=setup_env) + setup_env = dict(env, GH_TOKEN=api_token) if api_token and not cross else env + execute(binary, 'setup', 'wavec', '--version', WAVE_VERSION, env=setup_env) compiler = Path(temporary) / (Path(temporary) / 'current').read_text().strip() + if cross: + ci_cross.check_elf(compiler, ci_cross.TARGETS[target['id']][1]) compiler_hash = hashlib.sha256(compiler.read_bytes()).hexdigest() - run(sys.executable, 'tests/wave_compatibility.py', '--vex', binary, + execute(python, 'tests/wave_compatibility.py', '--vex', binary, '--wavec-bin', compiler.parent, '--reexports', '--expected-version', WAVE_VERSION, '--expected-sha256', compiler_hash, env=env) + interop_env = ci_cross.interop_environment(cross, dict(env, PATH=str(compiler.parent)+os.pathsep+env.get('PATH', ''))) if cross else env run(sys.executable, 'tests/native_interop.py', '--vex', binary, '--wavec-bin', compiler.parent, '--expected-version', WAVE_VERSION, - '--expected-sha256', compiler_hash, env=env) + '--expected-sha256', compiler_hash, env=interop_env) report = dict(schema_version=1, platform=target['id'], rust_target=target['rust_target'], executor=target['executor'], source=run('git', 'rev-parse', 'HEAD', capture=True).stdout.strip(), - os=platform.platform(), libc=platform.libc_ver(), wave_version=WAVE_VERSION, + os=identity['os'], libc=identity['libc'], wave_version=WAVE_VERSION, wave_release_id=release['id'], wave_asset_id=assets[0]['id'], wave_archive_digest='sha256:'+WAVE_PIN['archives'][target['id']], compiler_sha256=compiler_hash, native_interop=['c', 'cpp-c-abi', 'rust-c-abi', 'wave-object', 'wave-shared'], status='passed') + if cross: + report.update(build_method='cross', build_host=cross['build_host'], execution_arch=identity['machine'], + sdk_image=cross['sdk_image'], cross_compiler=cross['cross_compiler'], + runtime_image=cross['runtime_image'], + cross_packages=cross['cross_packages'], fixtures=cross['fixtures']) (ROOT / 'dist' / f"acceptance-{target['id']}.json").write_text(json.dumps(report, indent=2)+'\n') diff --git a/tools/ci_qemu.Dockerfile b/tools/ci_qemu.Dockerfile new file mode 100644 index 0000000..c7e0a48 --- /dev/null +++ b/tools/ci_qemu.Dockerfile @@ -0,0 +1,14 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 +# RUNTIME_IMAGE comes only from the immutable platform table. +ARG RUNTIME_IMAGE=debian@sha256:e3b4cb1b0056896c4b43e17472b906b10007ab94bc533d37a47e9a5795eebbc0 +FROM ${RUNTIME_IMAGE} +RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y \ + ca-certificates curl git python3 python3-venv ninja-build build-essential pkg-config gh procps \ + && rm -rf /var/lib/apt/lists/* +COPY requirements-build.txt /tmp/requirements-build.txt +RUN python3 -m venv /opt/vex-meson \ + && /opt/vex-meson/bin/pip install --no-cache-dir -r /tmp/requirements-build.txt \ + && ln -s /opt/vex-meson/bin/meson /usr/local/bin/meson diff --git a/tools/cli_reference.py b/tools/cli_reference.py index b21ac1c..cf31f50 100644 --- a/tools/cli_reference.py +++ b/tools/cli_reference.py @@ -1,12 +1,16 @@ #!/usr/bin/env python3 +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. # SPDX-License-Identifier: MPL-2.0 """Generate or verify the command reference against the actual CLI help.""" import argparse +import json from pathlib import Path import subprocess ROOT = Path(__file__).resolve().parents[1] -COMMANDS = ['', 'init', 'build', 'check', 'run', 'fetch', 'update', 'info', 'tree', 'metadata', 'doctor', 'clean', 'prune', 'setup'] +COMMANDS = [''] + [command['name'] for command in json.loads((ROOT/'tools/command-spec.json').read_text(encoding='utf-8'))['commands']] def render(binary): @@ -25,6 +29,19 @@ def render(binary): parser.add_argument('--write', action='store_true') args = parser.parse_args() text = render(args.vex.resolve()) + for shell in ['bash', 'zsh', 'fish', 'powershell']: + artifact = ROOT/'docs/completions'/f'vex.{shell}' + generated = subprocess.check_output([str(args.vex.resolve()), 'completions', shell], text=True) + if args.write: + artifact.parent.mkdir(parents=True, exist_ok=True) + artifact.write_text(generated, encoding='utf-8') + elif artifact.read_text(encoding='utf-8') != generated: + raise SystemExit(f'completion drift: {artifact}') + manual = subprocess.check_output([str(args.vex.resolve()), 'manpage'], text=True) + if args.write: + (ROOT/'docs/vex.1').write_text(manual, encoding='utf-8') + elif (ROOT/'docs/vex.1').read_text(encoding='utf-8') != manual: + raise SystemExit('manual drift; regenerate CLI references') path = ROOT/'docs/commands.md' if args.write: path.write_text(text, encoding='utf-8') diff --git a/tools/command-spec.json b/tools/command-spec.json new file mode 100644 index 0000000..1688f51 --- /dev/null +++ b/tools/command-spec.json @@ -0,0 +1,105 @@ +{ + "globals": "[-q|--quiet] [-v|--verbose] [--message-file ] [--manifest-path ] [-p|--package |--workspace] [--features ] [--no-default-features] [--include-tests]", + "commands": [ + { + "name": "init", + "usage": "init [--lib]", + "description": "Manage init" + }, + { + "name": "build", + "usage": "build [--lib] [--bin ] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline]", + "description": "Compile selected package targets" + }, + { + "name": "run", + "usage": "run [--bin ] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline] [-- ]", + "description": "Compile and execute one binary" + }, + { + "name": "check", + "usage": "check [--lib] [--bin ] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline]", + "description": "Check selected package targets" + }, + { + "name": "test", + "usage": "test [filter] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline] [-- ]", + "description": "Compile and execute explicit main-based tests; run every selected test and return the first failure" + }, + { + "name": "fetch", + "usage": "fetch [--locked] [--offline] [--target ]", + "description": "Manage fetch" + }, + { + "name": "update", + "usage": "update [...] [--target ]", + "description": "Manage update" + }, + { + "name": "info", + "usage": "info", + "description": "Manage info" + }, + { + "name": "metadata", + "usage": "metadata [--format=json] [--format-version <1|2>] [--locked] [--offline] [--target ]", + "description": "Manage metadata" + }, + { + "name": "tree", + "usage": "tree [--invert ] [--depth ] [--locked] [--offline] [--target ]", + "description": "Manage tree" + }, + { + "name": "clean", + "usage": "clean [--dry-run]", + "description": "Manage clean" + }, + { + "name": "prune", + "usage": "prune [--apply] [--dry-run]", + "description": "Manage prune" + }, + { + "name": "doctor", + "usage": "doctor [--format=json] [--target ]", + "description": "Manage doctor" + }, + { + "name": "setup", + "usage": "setup wavec [--version ] [--script-fallback]", + "description": "Manage setup" + }, + { + "name": "new", + "usage": "new [--name ] [--lib] [--git]", + "description": "Create a new project without overwriting data" + }, + { + "name": "add", + "usage": "add (--git |--path ) [--branch |--tag |--rev ] [--version ] [--version-req ] [--package-name ] [--subdir ] [--offline]", + "description": "Add a direct dependency preserving comments and formatting" + }, + { + "name": "remove", + "usage": "remove [--offline]", + "description": "Remove a direct dependency preserving comments and formatting" + }, + { + "name": "cache", + "usage": "cache prune [--apply] [--dry-run]", + "description": "Explicitly prune shared Git objects" + }, + { + "name": "completions", + "usage": "completions ", + "description": "Print shell completion script" + }, + { + "name": "manpage", + "usage": "manpage", + "description": "Print the vex(1) manual" + } + ] +} diff --git a/tools/dependency_audit.py b/tools/dependency_audit.py index dc828e2..87b4aa7 100644 --- a/tools/dependency_audit.py +++ b/tools/dependency_audit.py @@ -1,3 +1,7 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 """Audit exact Cargo.lock versions against OSV; findings=1, audit failure=2.""" from __future__ import annotations diff --git a/tools/dependency_notices.py b/tools/dependency_notices.py index 4d1fbcf..98b8004 100644 --- a/tools/dependency_notices.py +++ b/tools/dependency_notices.py @@ -1,3 +1,7 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 """Collect notices from the exact Cargo.lock graph, including all platforms. Run cargo metadata --locked --format-version 1 into a temporary JSON file, then diff --git a/tools/install.py b/tools/install.py index bedd30b..9650eb2 100644 --- a/tools/install.py +++ b/tools/install.py @@ -1,4 +1,7 @@ #!/usr/bin/env python3 +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. # SPDX-License-Identifier: MPL-2.0 """Install an exact, provenance-verified Vex release without administrator access.""" import argparse diff --git a/x.py b/tools/release_artifacts.py old mode 100755 new mode 100644 similarity index 76% rename from x.py rename to tools/release_artifacts.py index f36fd26..9c30f95 --- a/x.py +++ b/tools/release_artifacts.py @@ -31,7 +31,8 @@ tomllib = None -ROOT = Path(__file__).resolve().parent +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) TARGET_DIR = ROOT / "target" DIST_DIR = ROOT / "dist" BINARY_NAME = "vex" @@ -45,7 +46,7 @@ CHECKSUM_FILE = "SHA256SUMS" MINIMUM_ZIP_EPOCH = 315532800 # 1980-01-01T00:00:00Z MAXIMUM_ZIP_EPOCH = 4354819198 # 2107-12-31T23:59:58Z -from tools.release_version import VERSION_PATTERN, valid_version +from tools.release_version import valid_version ANSI_ESCAPE = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]") @@ -174,37 +175,6 @@ def select_targets(names: Sequence[str]) -> list[Target]: return selected -def build_environment(target: Target) -> dict[str, str]: - environment = os.environ.copy() - if target.triple == "riscv64gc-unknown-linux-gnu": - variable = "CARGO_TARGET_RISCV64GC_UNKNOWN_LINUX_GNU_LINKER" - if variable not in environment: - linker = shutil.which("riscv64-linux-gnu-gcc") - if linker is None: - raise ReleaseError( - "RISC-V builds require `riscv64-linux-gnu-gcc` in PATH or " - f"an explicit `{variable}`" - ) - environment[variable] = linker - return environment - - -def build_targets(targets: Iterable[Target]) -> None: - for target in targets: - status("Building", target.triple) - run_command( - [ - "cargo", - "build", - "--locked", - "--release", - "--target", - target.triple, - ], - env=build_environment(target), - ) - - def package_name(version: str, target: Target) -> str: return f"{BINARY_NAME}-v{version}-{target.triple}" @@ -237,7 +207,7 @@ def prepare_stage(version: str, target: Target, *, root: Path = ROOT) -> Path: if not source_binary.is_file(): raise ReleaseError( f"release binary is missing: `{source_binary}`\n" - f"help: run `python3 x.py build {target.triple}` first" + f"help: run `meson compile -C build build-release` with -Drelease_targets={target.triple} first" ) dist_dir = root / "dist" @@ -545,7 +515,7 @@ def require_clean_tree() -> None: if dirty: raise ReleaseError( "official releases require a clean Git working tree\n" - "help: commit, stash, or remove local changes before running `x.py release`" + "help: commit, stash, or remove local changes before running `meson compile -C build release`" ) @@ -571,171 +541,31 @@ def verify_release_source(version: str) -> None: require_release_tag(version) -def run_check_suite() -> None: - run_command(["cargo", "fmt", "--check"]) - run_python_tests() - run_command(["cargo", "test", "--workspace", "--locked"]) - run_command( - [ - "cargo", - "clippy", - "--workspace", - "--locked", - "--all-targets", - "--", - "-D", - "warnings", - ] - ) - run_command(["cargo", "build", "--workspace", "--locked"]) - - -def command_check(_: argparse.Namespace) -> None: - run_check_suite() - - -def command_test(_: argparse.Namespace) -> None: - run_python_tests() - run_command(["cargo", "test", "--workspace", "--locked"]) - - -def command_build(args: argparse.Namespace) -> None: - build_targets(select_targets(args.targets)) - - -def command_package(args: argparse.Namespace) -> None: - targets = select_targets(args.targets) - package_targets(targets, load_version(), detect_host_target(), allow_unverified=args.allow_unverified) - - -def command_checksum(args: argparse.Namespace) -> None: - targets = select_targets(args.targets) - checksum_path = write_checksums( - collect_release_archives(targets, load_version()), - ) - status("Checksums", str(checksum_path.relative_to(ROOT))) - - -def command_verify_release(_: argparse.Namespace) -> None: - version = load_version() - verify_release_source(version) - status("Verified", f"clean source at annotated tag v{version}") - - -def command_release(args: argparse.Namespace) -> None: - version = load_version() - verify_release_source(version) - targets = select_targets(args.targets) - run_check_suite() - build_targets(targets) - package_targets(targets, version, detect_host_target()) - - -def command_clean(_: argparse.Namespace) -> None: - status("Cleaning", "Cargo build artifacts") - run_command(["cargo", "clean"]) - if DIST_DIR.exists(): - status("Cleaning", str(DIST_DIR.relative_to(ROOT))) - shutil.rmtree(DIST_DIR) - - -def command_list_targets(_: argparse.Namespace) -> None: - try: - host = detect_host_target() - except ReleaseError: - host = "" - print(f"Host: {host}") - print("Supported release targets:") - for target in SUPPORTED_TARGETS.values(): - marker = " (native default)" if target.triple == host else "" - print( - f" {target.triple:<36} {target.platform:<8} " - f"{target.architecture:<13} {target.archive}{marker}" - ) - - -def add_target_arguments(parser: argparse.ArgumentParser) -> None: - parser.add_argument( - "targets", - nargs="*", - metavar="TARGET", - help="release target triple; defaults to the rustc host", - ) - - -def run_python_tests() -> None: - run_command( - [sys.executable, "-m", "unittest", "discover", "-s", "tests/xpy", "-v"] - ) - - -def create_parser(version: str) -> argparse.ArgumentParser: - parser = argparse.ArgumentParser( - description="Build and package reproducible Vex release artifacts." - ) - parser.add_argument("--version", action="version", version=f"%(prog)s {version}") - commands = parser.add_subparsers(dest="command") - - check = commands.add_parser("check", help="run the complete local validation suite") - check.set_defaults(handler=command_check) - - test = commands.add_parser("test", help="run release-tool and Rust tests") - test.set_defaults(handler=command_test) - - build = commands.add_parser("build", help="build release binaries") - add_target_arguments(build) - build.set_defaults(handler=command_build) - - package = commands.add_parser("package", help="package existing release binaries") - add_target_arguments(package) - package.add_argument( - "--allow-unverified", action="store_true", - help="development only: permit packaging when no execution verifier is available", - ) - package.set_defaults(handler=command_package) - - checksum = commands.add_parser( - "checksum", help="verify a complete archive set and write SHA256SUMS" - ) - add_target_arguments(checksum) - checksum.set_defaults(handler=command_checksum) - - verify_release = commands.add_parser( - "verify-release", help="verify clean source and the annotated version tag" - ) - verify_release.set_defaults(handler=command_verify_release) - - release = commands.add_parser( - "release", help="validate, build, and package an official tagged release" - ) - add_target_arguments(release) - release.set_defaults(handler=command_release) - - clean = commands.add_parser("clean", help="remove Cargo and release-tool artifacts") - clean.set_defaults(handler=command_clean) - - list_targets = commands.add_parser("list-targets", help="show supported release targets") - list_targets.set_defaults(handler=command_list_targets) - return parser - - def main(argv: Sequence[str] | None = None) -> int: - if sys.version_info < (3, 11): - print("error: x.py requires Python 3.11 or newer", file=sys.stderr) - return 1 - try: - version = load_version() - except ReleaseError as error: - print(f"error: {error}", file=sys.stderr) - return 1 - parser = create_parser(version) + parser = argparse.ArgumentParser(description="Create and verify Vex release artifacts (invoked by Meson).") + commands = parser.add_subparsers(dest="command", required=True) + package = commands.add_parser("package") + package.add_argument("targets", nargs="+") + package.add_argument("--allow-unverified", action="store_true") + checksum = commands.add_parser("checksum") + checksum.add_argument("targets", nargs="+") + commands.add_parser("verify-source") + commands.add_parser("clean") args = parser.parse_args(argv) - if not hasattr(args, "handler"): - parser.print_help() - return 0 try: - args.handler(args) - except ReleaseError as error: + version = load_version() + if args.command == "package": + package_targets(select_targets(args.targets), version, detect_host_target(), + allow_unverified=args.allow_unverified) + elif args.command == "checksum": + path = write_checksums(collect_release_archives(select_targets(args.targets), version)) + status("Checksums", str(path.relative_to(ROOT))) + elif args.command == "verify-source": + verify_release_source(version) + status("Verified", f"clean source at annotated tag v{version}") + elif DIST_DIR.exists(): + shutil.rmtree(DIST_DIR) + except (ReleaseError, OSError) as error: print(f"error: {error}", file=sys.stderr) return 1 return 0 diff --git a/tools/release_version.py b/tools/release_version.py index 66be09a..18adf62 100644 --- a/tools/release_version.py +++ b/tools/release_version.py @@ -1,3 +1,7 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 """The single official release identity policy (no build metadata).""" import re import sys diff --git a/tools/repository_checks.py b/tools/repository_checks.py index a71abdc..89fe442 100644 --- a/tools/repository_checks.py +++ b/tools/repository_checks.py @@ -1,4 +1,7 @@ #!/usr/bin/env python3 +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. # SPDX-License-Identifier: MPL-2.0 """Enforce reviewable workflow pins, platform coverage and release evidence.""" import argparse @@ -28,6 +31,18 @@ def validate(root=ROOT): raise ValueError(f'{name}: missing/duplicate platform {row["id"]}') if 'continue-on-error: true' in text: raise ValueError(f'{name}: platform failures may not be ignored') + if ("meson compile -C build acceptance" not in text + or "-Dacceptance_platform=${{ matrix.id }}" not in text): + raise ValueError(f'{name}: platform acceptance must use the Meson entry point') + build = re.search(r'(?ms)^ (?:platform|build):\n(.*?)(?=^ [a-z][\w-]*:\n|\Z)', text) + if not build or 'persist-credentials: false' not in build.group(1): + raise ValueError(f'{name}: checkout credentials may not enter build/runtime containers') + sdk = (root / 'tools/ci_cross.Dockerfile').read_text() + if not re.search(r'^FROM debian@sha256:[0-9a-f]{64}$', sdk, re.M): + raise ValueError('the amd64 cross SDK base image must be immutable') + for row in rows: + if row['executor'] == 'qemu' and not re.fullmatch(r'[\w./-]+@sha256:[0-9a-f]{64}', row.get('image', '')): + raise ValueError('QEMU runtime base images must be immutable') return rows @@ -46,6 +61,19 @@ def acceptance(directory, commit, rows, pin=None): or report.get('wave_version') != pin['version'] or not re.fullmatch('[0-9a-f]{64}', report.get('compiler_sha256', ''))): raise ValueError(f'invalid acceptance evidence for {row["id"]}') + if row['executor'] == 'qemu': + if (report.get('build_method') != 'cross' + or report.get('build_host') != 'x86_64-unknown-linux-gnu' + or report.get('execution_arch') != row['arch'] + or not re.fullmatch(r'sha256:[0-9a-f]{64}', report.get('sdk_image', '')) + or not re.fullmatch(r'sha256:[0-9a-f]{64}', report.get('runtime_image', '')) + or not report.get('cross_compiler') or not report.get('cross_packages')): + raise ValueError(f'invalid cross-build evidence for {row["id"]}') + fixtures = report.get('fixtures', {}) + expected = {'fake_wavec', 'target_wavec', 'native_wavec', 'artifact_wavec', 'doctor_tools', 'version_probe'} + if (set(fixtures) != expected or any(not re.fullmatch('[0-9a-f]{64}', item.get(key, '')) + for item in fixtures.values() for key in ('source_sha256', 'binary_sha256'))): + raise ValueError(f'incomplete target fixture evidence for {row["id"]}') if __name__ == '__main__': diff --git a/tools/requirements-build.txt b/tools/requirements-build.txt new file mode 100644 index 0000000..a7a061e --- /dev/null +++ b/tools/requirements-build.txt @@ -0,0 +1,5 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 +meson==1.8.5 diff --git a/tools/source_policy.py b/tools/source_policy.py new file mode 100644 index 0000000..bb75e95 --- /dev/null +++ b/tools/source_policy.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 +"""Check source licensing and intentional worktree line endings without mutation.""" +import argparse +from pathlib import Path +import subprocess + +ROOT = Path(__file__).resolve().parents[1] +NOTICE = 'This Source Code Form is subject to the terms of the Mozilla Public\nLicense, v. 2.0. If a copy of the MPL was not distributed with this\nfile, You can obtain one at https://mozilla.org/MPL/2.0/.' +SPDX = 'SPDX-License-Identifier: MPL-2.0' +SOURCE_SUFFIXES = {'.rs', '.py', '.sh', '.ps1', '.cmd', '.bat', '.toml', '.yml', '.yaml', '.build', '.options'} +BINARY_SUFFIXES = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.ico', '.pdf', '.zip', '.gz', '.xz', '.bz2', '.tar', '.7z', '.exe', '.dll', '.so', '.a', '.o', '.lib', '.wasm', '.woff', '.woff2', '.bin'} + + +def paths(root=ROOT): + raw = subprocess.check_output(['git', 'ls-files', '--cached', '--others', '--exclude-standard', '-z'], cwd=root) + deleted = subprocess.check_output(['git', 'ls-files', '--deleted', '-z'], cwd=root).split(b'\0') + return sorted({Path(name.decode('utf-8')) for name in raw.split(b'\0') if name and name not in deleted}) + + +def needs_header(path): + # WSON/lock/Wave fixtures test exact syntax and diagnostics. JSON cannot + # carry comments. Generated CLI tools/docs and third-party notices retain + # their own provenance; no project copyright is asserted over them. + return path.suffix in SOURCE_SUFFIXES and not str(path).startswith(('vendor/', 'third_party/')) + + +def check_file(path, data): + if path.suffix in BINARY_SUFFIXES or (b'\0' in data and not needs_header(path)): + return + text = data.decode('utf-8') + if path.suffix in {'.cmd', '.bat'}: + if b'\n' in data.replace(b'\r\n', b'') or b'\r' in data.replace(b'\r\n', b''): + raise ValueError('Windows cmd/bat scripts require CRLF') + elif b'\r' in data: + raise ValueError('text must use LF, not CRLF or mixed endings') + if needs_header(path): + marker = '//' if path.suffix == '.rs' else '@rem' if path.suffix in {'.cmd', '.bat'} else '#' + comments = [] + for line in text.splitlines(): + if line.startswith('#!') or not line.strip(): + continue + if not line.startswith(marker): + break + comments.append(line[len(marker):].strip()) + if SPDX not in comments or not all(line in comments for line in NOTICE.splitlines()): + raise ValueError('missing MPL 2.0 notice and SPDX header') + + +def validate(root=ROOT): + errors = [] + for path in paths(root): + absolute = root / path + if absolute.is_symlink(): + continue # Git records a link target, not ownership of its contents. + try: + check_file(path, absolute.read_bytes()) + except (OSError, UnicodeError, ValueError) as error: + errors.append(f'{path}: {error}') + if errors: + raise ValueError('\n'.join(errors)) + + +if __name__ == '__main__': + argparse.ArgumentParser(description=__doc__).parse_args() + validate() + print('Verified source headers and repository line endings.') diff --git a/wson/Cargo.toml b/wson/Cargo.toml index e4769d1..15816ac 100644 --- a/wson/Cargo.toml +++ b/wson/Cargo.toml @@ -1,3 +1,7 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 [package] name = "wson" version.workspace = true diff --git a/wson/src/edit.rs b/wson/src/edit.rs new file mode 100644 index 0000000..85acb2f --- /dev/null +++ b/wson/src/edit.rs @@ -0,0 +1,133 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +//! Dependency edits use parser byte ranges; unrelated source remains byte exact. +use super::*; +use std::ops::Range; + +pub fn dependency(raw: &str, name: &str, addition: Option<&str>) -> Result { + let map = loads_versions(raw, "format", &[2, 3, 4])?; + let escapes = matches!(map.get("format"), Some(WsonValue::Int(2..=4))); + let mut p = Parser { + raw, + pos: 0, + depth: 0, + escapes: Some(escapes), + }; + p.take(b'{')?; + let mut array = None; + let mut last = None; + loop { + p.space()?; + if p.peek() == Some(b'}') { + break; + } + let start = p.pos; + while p + .peek() + .is_some_and(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-')) + { + p.pos += 1; + } + let key = &raw[start..p.pos]; + p.space()?; + p.pos += 1; + p.space()?; + let value_start = p.pos; + p.value()?; + if key == "dependencies" { + array = Some(value_start..p.pos); + } + let end = p.pos; + p.space()?; + let comma = p.peek() == Some(b','); + if comma { + p.pos += 1; + } + last = Some((end, comma)); + } + let root_end = p.pos; + let Some(range) = array else { + let text = addition.ok_or_else(|| format!("unknown direct dependency `{name}`"))?; + let prefix = if last.is_some_and(|(_, comma)| !comma) { + "," + } else { + "" + }; + let at = last.map_or(root_end, |(end, _)| end); + let mut result = raw.to_owned(); + if !prefix.is_empty() { + result.insert_str(at, prefix); + } + result.insert_str( + root_end + prefix.len(), + &format!("\n dependencies = [{text}]\n"), + ); + return Ok(result); + }; + p.pos = range.start; + p.take(b'[')?; + let mut entries: Vec<(Range, Option, String)> = Vec::new(); + loop { + p.space()?; + if p.peek() == Some(b']') { + break; + } + let start = p.pos; + let value = p.value()?; + let end = p.pos; + let WsonValue::Object(fields) = value else { + return Err("dependency must be an object".into()); + }; + let Some(WsonValue::String(alias)) = fields.get("name") else { + return Err("dependency name missing".into()); + }; + p.space()?; + let comma = (p.peek() == Some(b',')).then_some(p.pos); + if comma.is_some() { + p.pos += 1; + } + entries.push((start..end, comma, alias.clone())); + } + let mut result = raw.to_owned(); + let found = entries.iter().position(|(_, _, alias)| alias == name); + match (addition, found) { + (Some(_), Some(_)) => return Err(format!("direct dependency `{name}` already exists")), + (Some(text), None) => { + result.insert_str(p.pos, &format!("\n {text}\n ")); + if let Some((range, None, _)) = entries.last() { result.insert(range.end, ','); } + } + (None, Some(index)) => { + let (range, comma, _) = &entries[index]; + if let Some(comma) = comma { result.remove(*comma); } + result.replace_range(range.clone(), ""); + if comma.is_none() && index > 0 { + if let Some(comma) = entries[index-1].1 { result.remove(comma); } + } + } + (None, None) => return Err(format!("unknown direct dependency `{name}`; transitive dependencies must be edited in their owning package")), + } + loads_versions(&result, "format", &[2, 3, 4])?; + Ok(result) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn comments_and_string_syntax_survive() { + let raw = "{format=4, name=\"app\", // header\n dependencies=[ /*keep*/ {name=\"one\",path=\"a,//b\"} // tail\n ], note=\"[,{}]\"}"; + let added = dependency(raw, "two", Some("{name=\"two\",path=\"../two\"}")).unwrap(); + assert!(added.contains("path=\"a,//b\"}, // tail")); + let removed = dependency(&added, "one", None).unwrap(); + assert!(removed.contains("/*keep*/")); + assert!(removed.contains("// tail")); + assert!(removed.contains("note=\"[,{}]\"")); + assert!(dependency(&removed, "one", None).is_err()); + for input in ["{}", "{name=\"app\"}", "{name=\"app\", // hi\n}"] { + let output = dependency(input, "one", Some("{name=\"one\",path=\"a\"}")).unwrap(); + assert!(loads_versions(&output, "format", &[2, 3, 4]).is_ok()); + } + } +} diff --git a/wson/src/lib.rs b/wson/src/lib.rs index 9fd10a0..d7bec13 100644 --- a/wson/src/lib.rs +++ b/wson/src/lib.rs @@ -1,6 +1,11 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 //! Token-aware WSON boundary shared by manifests and lockfiles. //! Legacy strings retain their backslashes; only explicitly versioned input //! decodes JSON escapes. The upstream parser is used for scalar literals only. +pub mod edit; pub use wson_rs::{WsonMap, WsonValue}; /// Both file reads and in-memory parser entry points enforce this bound. @@ -52,6 +57,65 @@ pub fn quote(value: &str) -> String { serde_json::to_string(value).expect("serializing a string cannot fail") } +/// Convert an already validated WSON subtree to typed machine data. Extended +/// scalar literals are rejected instead of silently changing their meaning. +pub fn json_value(value: &WsonValue) -> Result { + use serde_json::Value; + Ok(match value { + WsonValue::Null => Value::Null, + WsonValue::Bool(value) => Value::Bool(*value), + WsonValue::Int(value) => (*value).into(), + WsonValue::Float(value) => serde_json::Number::from_f64(*value) + .map(Value::Number) + .ok_or("invalid JSON number")?, + WsonValue::String(value) => Value::String(value.clone()), + WsonValue::Array(values) => { + Value::Array(values.iter().map(json_value).collect::>()?) + } + WsonValue::Object(values) => Value::Object( + values + .iter() + .map(|(k, v)| Ok((k.clone(), json_value(v)?))) + .collect::>()?, + ), + _ => return Err("this field requires ordinary JSON-compatible values".into()), + }) +} + +/// Render protocol-shaped JSON data using WSON field names and versioned +/// string escaping. Arbitrary JSON object keys are intentionally rejected. +pub fn render_json(value: &serde_json::Value) -> Result { + use serde_json::Value; + Ok(match value { + Value::Object(values) => { + let fields = values + .iter() + .map(|(key, value)| { + if key.is_empty() + || !key + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-')) + { + return Err("invalid WSON field name".into()); + } + Ok(format!("{key} = {}", render_json(value)?)) + }) + .collect::, String>>()?; + format!("{{{}}}", fields.join(", ")) + } + Value::Array(values) => format!( + "[{}]", + values + .iter() + .map(render_json) + .collect::, _>>()? + .join(", ") + ), + Value::String(value) => quote(value), + other => other.to_string(), + }) +} + struct Parser<'a> { raw: &'a str, pos: usize,