From 35332d211430a6af497bb7af0e20667a76b0ae58 Mon Sep 17 00:00:00 2001 From: Connor Fitzgerald Date: Fri, 18 Sep 2026 11:06:10 -0400 Subject: [PATCH] Update agent tooling (#10202) --- .agents/skills/cts-triage/SKILL.md | 310 +++++++++++++ .agents/skills/webgpu-specs/SKILL.md | 29 ++ .agents/skills/webgpu-specs/download.sh | 23 + .claude/skills/cts-triage/SKILL.md | 33 +- .claude/skills/webgpu-specs/SKILL.md | 4 +- .github/actions/ai-commit-check/LICENSE.MIT | 19 + .github/actions/ai-commit-check/README.md | 42 ++ .github/actions/ai-commit-check/action.yml | 45 ++ .../actions/ai-commit-check/scripts/check.sh | 111 +++++ .github/pull_request_template.md | 26 +- .github/workflows/ci.yml | 9 + AGENTS.md | 253 +++-------- CLAUDE.md | 75 ++++ CONTRIBUTING.md | 17 +- LICENSE.MIT | 2 +- docs/broadcast_license.nu | 26 -- naga-cli/LICENSE.MIT | 2 +- naga-types/LICENSE.MIT | 2 +- naga/LICENSE.MIT | 2 +- wgpu-core-remote-types/LICENSE.APACHE | 176 ++++++++ wgpu-core-remote-types/LICENSE.MIT | 21 + wgpu-core-remote/LICENSE.APACHE | 176 ++++++++ wgpu-core-remote/LICENSE.MIT | 21 + wgpu-core/LICENSE.MIT | 2 +- wgpu-core/platform-deps/apple/LICENSE.MIT | 2 +- .../platform-deps/emscripten/LICENSE.MIT | 2 +- .../linux-android-bsd/LICENSE.MIT | 2 +- wgpu-core/platform-deps/wasm/LICENSE.MIT | 2 +- wgpu-core/platform-deps/windows/LICENSE.MIT | 2 +- wgpu-hal/LICENSE.MIT | 2 +- wgpu-info/LICENSE.MIT | 2 +- wgpu-naga-bridge/LICENSE.MIT | 2 +- wgpu-types/LICENSE.MIT | 2 +- wgpu/LICENSE.MIT | 2 +- xtask/src/main.rs | 8 + xtask/src/sync_repo_files.rs | 417 ++++++++++++++++++ xtask/src/sync_repo_files/file_sync.rs | 266 +++++++++++ 37 files changed, 1884 insertions(+), 253 deletions(-) create mode 100644 .agents/skills/cts-triage/SKILL.md create mode 100644 .agents/skills/webgpu-specs/SKILL.md create mode 100644 .agents/skills/webgpu-specs/download.sh create mode 100644 .github/actions/ai-commit-check/LICENSE.MIT create mode 100644 .github/actions/ai-commit-check/README.md create mode 100644 .github/actions/ai-commit-check/action.yml create mode 100644 .github/actions/ai-commit-check/scripts/check.sh create mode 100644 CLAUDE.md delete mode 100644 docs/broadcast_license.nu create mode 100644 wgpu-core-remote-types/LICENSE.APACHE create mode 100644 wgpu-core-remote-types/LICENSE.MIT create mode 100644 wgpu-core-remote/LICENSE.APACHE create mode 100644 wgpu-core-remote/LICENSE.MIT create mode 100644 xtask/src/sync_repo_files.rs create mode 100644 xtask/src/sync_repo_files/file_sync.rs diff --git a/.agents/skills/cts-triage/SKILL.md b/.agents/skills/cts-triage/SKILL.md new file mode 100644 index 000000000..313b689eb --- /dev/null +++ b/.agents/skills/cts-triage/SKILL.md @@ -0,0 +1,310 @@ +--- +name: cts-triage +description: Run CTS test suites and investigate failures +--- + +# Triage Process + +When working on a category of CTS tests, follow this systematic process to identify issues, prioritize fixes, and document findings. + +## Step 0: Divide Into Manageable Chunks + +List all the tests matching a selector: + +```bash +cargo xtask cts -- --list 'webgpu:api,validation,*' 2>&1 | wc -l +``` + +If there is a reasonable number of tests matching the selector (less than a +couple hundred or so, but this isn't a hard cutoff), then you can proceed with +triage. Otherwise, make a list of more detailed wildcards that match fewer +tests, verify that each wildcard matches a reasonable number of tests, and +triage each wildcard separately. + +## Step 1: Get Overall Statistics + +Run the full test suite for the category to understand the scope: + +```bash +cargo xtask cts 'webgpu:api,validation,category:*' 2>&1 | grep -E "(Summary|Passed|Failed)" | tail -5 +``` + +This gives you the pass rate and number of failures. Document this as your baseline. + +## Step 2: Identify Test Subcategories + +Review the output from the running the CTS (with or without `--list`) to +identify any subcategories that may exist within the suite being analyzed. +Subcategories typically have an additional `:`- or `,`-delimited word in the +test name. Running tests by subcategory may be more manageable than running +with the entire suite at once or running individual tests. + +## Step 3: Run Each Subcategory + +Test each subcategory individually to identify which ones are passing vs failing: + +```bash +cargo xtask cts 'webgpu:api,validation,category:subcategory:*' 2>&1 | grep -E "(Passed|Failed|Skipped)" | tail -3 +``` + +Track the pass rate for each subcategory. This helps you identify: + +- What's already working (don't break it!) +- Where the failures are concentrated +- Which issues affect multiple categories + +## Step 4: Analyze Failure Patterns + +For failing subcategories, look at what tests are failing: + +```bash +cargo xtask cts 'webgpu:api,validation,category:subcategory:*' 2>&1 | grep "\[fail\]" | head -20 +``` + +Look for patterns: + +- **Format-specific failures**: May indicate missing format capability checks +- **Parameter-specific failures**: Validation missing for specific parameter combinations + +## Step 5: Examine Specific Failures + +Pick a representative failing test and run it individually to see the error: + +```bash +cargo xtask cts 'webgpu:api,validation,category:subcategory:specific_test' 2>&1 | tail -30 +``` + +Look for: + +- **"EXPECTATION FAILED: DID NOT REJECT"**: wgpu is accepting invalid input (validation gap) +- **"Validation succeeded unexpectedly"**: Similar to above +- **"Unexpected validation error occurred"**: wgpu is rejecting valid input +- **Error message content**: Tells you what validation is triggering or missing + +## Step 6: Check CTS Test Source + +To understand what the test expects, read the TypeScript source: + +```bash +grep -A 40 "test_name" cts/src/webgpu/api/validation/path/file.spec.ts +``` + +The test source shows: + +- What configurations are being tested +- What the expected behavior is (pass/fail) +- The validation rules from the WebGPU spec +- Comments explaining the rationale + +## Step 7: Categorize Issues + +Group failures into categories: + +**High Priority - Validation Gaps:** + +- wgpu accepts invalid configurations that should fail +- Security or correctness implications +- Example: Accepting wrong texture formats, missing aspect checks + +**Medium Priority - Spec Compliance:** + +- Edge cases not handled correctly +- Optional field validation issues +- Example: depthCompare optional field handling + +**Low Priority - Minor Gaps:** + +- Less common scenarios +- Limited real-world impact +- Example: Depth bias with non-triangle topologies + +**Known Issues - Skip:** + +- Known failure patterns (documented in Common Patterns below) +- Track count but don't try to fix + +## Step 8: Identify Root Causes + +For validation gaps, find where validation should happen: + +1. **Search for existing validation:** + + ```bash + grep -n "relevant_keyword" wgpu-core/src/device/resource.rs + ``` + +2. **Look for render/compute pipeline creation:** + - Render pipeline: `wgpu-core/src/device/resource.rs` around `create_render_pipeline` + - Compute pipeline: Similar location + - Look for existing validation patterns you can follow + +3. **Check for helper functions:** + + ```bash + grep "fn is_" wgpu-types/src/texture/format.rs + ``` + +4. **Find error enums:** + ```bash + grep "pub enum.*Error" wgpu-core/src/pipeline.rs + ``` + +## Step 9: Implement Fixes + +When implementing fixes: + +1. **Add error variants if needed** (in `wgpu-core/src/pipeline.rs`) +2. **Add helper methods** (in `wgpu-types` if checking properties) +3. **Add validation checks** (in `wgpu-core/src/device/resource.rs`) +4. **Test the fix** with specific failing tests +5. **Run full subcategory** to verify all related tests pass +6. **Check you didn't break passing tests** + +## Step 10: Document Findings + +Create or update a triage document (e.g., `category_triage.md`). + +Do not write information about changes you have made to the triage document. Only capture the state of the tests and any investigation into open issues. + +````markdown +# Category CTS Tests - Triage Report + +**Overall Status:** XP/YF/ZS (%/%/%) + +## Passing Sub-suites ✅ + +[List sub-suites that have no failures (all pass or skip)] + +## Remaining Issues ⚠️ + +[List sub-suites that have failures and if it can be stated concisely, a summary of the issue] + +## Issue Detail + +[List detail of any investigation into failures. Do not go into detail about passed suites, just list the failures.] + +### 1. title, e.g. a distinguishing word from the test selector + +**Test selector:** `webgpu:api,validation,render_pipeline,depth_stencil_state:format:*` +**What it tests:** [Description] +**Example failure:** +[a selector for a single failing test, e.g.:] + +``` +webgpu:api,validation,render_pipeline,depth_stencil_state:depthCompare_optional:isAsync=false;format="stencil8" +``` + +**Error:** +[error message from the failing tests, e.g.:] + +``` +Unexpected validation error occurred: Depth/stencil state is invalid: +Format Stencil8 does not have a depth aspect, but depth test/write is enabled +``` + +**Root cause:** +[Your analysis of the root cause. Do not speculate. Only include the results of specific investigation you have done.] +The validation is triggering incorrectly. When `depthCompare` is undefined/missing in JavaScript, it's getting translated to a default value that makes `is_depth_enabled()` return true, even for stencil-only formats. + +**Fix needed:** +[Your proposed fix. Again, do not speculate. Only state the fix if it is obvious from the root cause analysis, or if you have done specific investigation into how to fix it.] + +### 2. title + +[repeat as needed for additional issues] +```` + +## Step 11: Update CTS Result Lists + +The result lists have these purposes: + +- `cts_runner/test.lst` contains sets of tests with no failures. It is not an + exhaustive list of passing sets of tests. +- `cts_runner/fail.lst` contains sets of tests with failures. A comment can record + the pass rate, especially when the pass rate is high. +- `cts_runner/skip.lst` contains sets of tests in which at least 90% of the tests + are skipped. + +If you fix a set of tests, add it to `cts_runner/test.lst` only when all of its +tests pass or skip. Do not add a set of tests that has any failures. + +Use wildcards to minimize the number of selectors: + +``` +webgpu:api,validation,category:subcategory:isAsync=false;* +``` + +Use a higher-level wildcard only when all tests that it matches belong in the +same result list. Do not use a wildcard that also matches tests from another +result list. + +Keep the selectors in the order that the `lst_files_are_sorted` integration +test requires. This rule also applies to selectors in comments. + +## Step 12: Verify and Build + +Before finishing: + +```bash +# Format code +cargo fmt + +# Check for errors +cargo clippy --tests + +# Build to ensure no compilation errors +cargo build + +# Run the tests you added to test.lst +cargo xtask cts 'webgpu:api,validation,category:subcategory:isAsync=false;*' +``` + +# Common Patterns + +If the user asked to investigate a failure, and the cause of the failure is +noted here with "do not attempt to fix", then stop and ask the user before +attempting to fix. + +**Pattern: Format-specific failures** + +- Check if format validation is missing +- Look for `is_depth_stencil_format()`, `is_color_format()` etc. +- May need to add format capability checks + +**Pattern: Aspect-related failures** + +- Check if code validates format aspects (DEPTH, STENCIL, COLOR) +- Use `hal::FormatAspects::from(format)` to check +- Validate operations match available aspects + +**Pattern: Optional field failures** + +- May be WebGPU optional field semantics issue +- Check if undefined in JS becomes a default value in Rust +- May need to distinguish "not set" from "set to default" + +**Pattern: Atomics accepted incorrectly** + +- Naga allows referencing an atomic directly in an expression +- Should only allow accessing via `atomicLoad`, `atomicStore`, etc. +- Only investigate as necessary to confirm this is the issue. Do not attempt to fix. Refer user to https://github.com/gfx-rs/wgpu/issues/5474. + +**Pattern: Error reporting for destroyed resources** + +- Tests that check for validation errors when a destroyed resource is used. `wgpu` often reports these errors later than WebGPU requires, causing the tests to fail. +- `wgpu` may report these errors earlier than it should, causing the test to fail with an unexpected validation error. +- Look for: + - Tests with `state="destroyed"` parameter + - Tests checking that operations on destroyed buffers or textures should fail +- Example failing tests: + - `webgpu:api,validation,encoding,cmds,compute_pass:indirect_dispatch_buffer_state:` with `state="destroyed"` subcases +- Only investigate as necessary to confirm this is the issue. Do not attempt to fix. Refer user to https://github.com/gfx-rs/wgpu/issues/7881. + +# Tips + +- **Start with high-impact fixes**: Validation gaps with security implications +- **Look for existing patterns**: Other validation code shows the style +- **Test incrementally**: Fix one category at a time, verify it works +- **Document as you go**: Don't wait until the end to write the triage +- **Ask for clarification**: If test expectations are unclear, check the WebGPU spec or test source +- **Track your progress**: Update pass rates as you fix issues diff --git a/.agents/skills/webgpu-specs/SKILL.md b/.agents/skills/webgpu-specs/SKILL.md new file mode 100644 index 000000000..9edc28480 --- /dev/null +++ b/.agents/skills/webgpu-specs/SKILL.md @@ -0,0 +1,29 @@ +--- +name: webgpu-specs +description: Download WebGPU and WGSL specifications for use as a reference +allowed-tools: "Bash(sh .agents/skills/webgpu-specs/download.sh)" +--- + +Run `sh .agents/skills/webgpu-specs/download.sh` to download the +WebGPU and WGSL specifications if they are not present or if they have +been updated. You do not need to change directory before running the script. + +After the specs are downloaded, you can search in `target/claude/webgpu-spec.bs` +and `target/claude/wgsl-spec.bs` for relevant sections of the specification. + +When referencing the specifications, prefer to use named anchors rather than +line numbers. For example, to reference the "Object Descriptors" section, which has the +following header: + +``` +### Object Descriptors ### {#object-descriptors} +``` + +Use the URL so the user +can click to navigate directly to that section. + +For the WGSL specification, the base URL is . + +If necessary, read additional content from the file to find the header preceding +the text you want to reference. You may provide line numbers as additional +context, but always make every effort to provide the user with a clickable link. diff --git a/.agents/skills/webgpu-specs/download.sh b/.agents/skills/webgpu-specs/download.sh new file mode 100644 index 000000000..dc09ee6a2 --- /dev/null +++ b/.agents/skills/webgpu-specs/download.sh @@ -0,0 +1,23 @@ +#!/bin/sh + +set -e + +TARGET_DIR="$(cargo metadata --format-version 1 | jq -r ".target_directory")" + +WEBGPU="$TARGET_DIR/claude/webgpu-spec" +WGSL="$TARGET_DIR/claude/wgsl-spec" +mkdir -p "$TARGET_DIR/claude" + +if [ -f "$WEBGPU.etag" ]; then + curl --etag-save "$WEBGPU.etag.new" --etag-compare "$WEBGPU.etag" -fsSL https://raw.githubusercontent.com/gpuweb/gpuweb/main/spec/index.bs -o "$WEBGPU.bs" + [ -s "$WEBGPU.etag.new" ] && mv "$WEBGPU.etag.new" "$WEBGPU.etag" || rm "$WEBGPU.etag.new" +else + curl --etag-save "$WEBGPU.etag" https://raw.githubusercontent.com/gpuweb/gpuweb/main/spec/index.bs -o "$WEBGPU.bs" +fi + +if [ -f "$WGSL.etag" ]; then + curl --etag-save "$WGSL.etag.new" --etag-compare "$WGSL.etag" -fsSL https://raw.githubusercontent.com/gpuweb/gpuweb/main/wgsl/index.bs -o "$WGSL.bs" + [ -s "$WGSL.etag.new" ] && mv "$WGSL.etag.new" "$WGSL.etag" || rm "$WGSL.etag.new" +else + curl --etag-save "$WGSL.etag" https://raw.githubusercontent.com/gpuweb/gpuweb/main/wgsl/index.bs -o "$WGSL.bs" +fi diff --git a/.claude/skills/cts-triage/SKILL.md b/.claude/skills/cts-triage/SKILL.md index cf660b8b5..313b689eb 100644 --- a/.claude/skills/cts-triage/SKILL.md +++ b/.claude/skills/cts-triage/SKILL.md @@ -120,7 +120,7 @@ Group failures into categories: **Known Issues - Skip:** -- Known failure patterns (documented in AGENTS.md) +- Known failure patterns (documented in Common Patterns below) - Track count but don't try to fix ## Step 8: Identify Root Causes @@ -214,21 +214,32 @@ The validation is triggering incorrectly. When `depthCompare` is undefined/missi [repeat as needed for additional issues] ```` -## Step 11: Update test.lst +## Step 11: Update CTS Result Lists -For fixed tests that are now passing, add them to `cts_runner/test.lst`: +The result lists have these purposes: -1. **Use wildcards** to minimize lines: +- `cts_runner/test.lst` contains sets of tests with no failures. It is not an + exhaustive list of passing sets of tests. +- `cts_runner/fail.lst` contains sets of tests with failures. A comment can record + the pass rate, especially when the pass rate is high. +- `cts_runner/skip.lst` contains sets of tests in which at least 90% of the tests + are skipped. - ``` - webgpu:api,validation,category:subcategory:isAsync=false;* - ``` +If you fix a set of tests, add it to `cts_runner/test.lst` only when all of its +tests pass or skip. Do not add a set of tests that has any failures. -2. **Group related tests** when possible: - - If multiple subcategories all pass, use a higher-level wildcard - - Example: `webgpu:api,validation,category:*` if all subcategories pass +Use wildcards to minimize the number of selectors: -3. **Maintain alphabetical order** roughly in the file +``` +webgpu:api,validation,category:subcategory:isAsync=false;* +``` + +Use a higher-level wildcard only when all tests that it matches belong in the +same result list. Do not use a wildcard that also matches tests from another +result list. + +Keep the selectors in the order that the `lst_files_are_sorted` integration +test requires. This rule also applies to selectors in comments. ## Step 12: Verify and Build diff --git a/.claude/skills/webgpu-specs/SKILL.md b/.claude/skills/webgpu-specs/SKILL.md index ddbb58695..9edc28480 100644 --- a/.claude/skills/webgpu-specs/SKILL.md +++ b/.claude/skills/webgpu-specs/SKILL.md @@ -1,10 +1,10 @@ --- name: webgpu-specs description: Download WebGPU and WGSL specifications for use as a reference -allowed-tools: "Bash(sh .claude/skills/webgpu-specs/download.sh)" +allowed-tools: "Bash(sh .agents/skills/webgpu-specs/download.sh)" --- -Run `sh .claude/skills/webgpu-specs/download.sh` to download the +Run `sh .agents/skills/webgpu-specs/download.sh` to download the WebGPU and WGSL specifications if they are not present or if they have been updated. You do not need to change directory before running the script. diff --git a/.github/actions/ai-commit-check/LICENSE.MIT b/.github/actions/ai-commit-check/LICENSE.MIT new file mode 100644 index 000000000..6802bc4b8 --- /dev/null +++ b/.github/actions/ai-commit-check/LICENSE.MIT @@ -0,0 +1,19 @@ +MIT License + +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. \ No newline at end of file diff --git a/.github/actions/ai-commit-check/README.md b/.github/actions/ai-commit-check/README.md new file mode 100644 index 000000000..ca301930c --- /dev/null +++ b/.github/actions/ai-commit-check/README.md @@ -0,0 +1,42 @@ +# AI Commit Check + +A composite action that detects AI-authored commits and AI metadata trailers in a pull request. + +wgpu allows contributors to write code with an LLM, but the contributor must own the +change. See the [LLMs (AI)](../../../CONTRIBUTING.md#llms-ai) section of `CONTRIBUTING.md`. +This action rejects commits that attribute authorship to an AI instead. + +This is a vendored version of [`Jondolf/ai-commit-check`](https://github.com/Jondolf/ai-commit-check) +from commit `7069d4254c6310cdb0395a6ab0ca1f29af897f83` with its data collection changed to +be done using the `gh` CLI instead of raw git history, to avoid needing a deep checkout. + +## Usage + +```yaml +- name: Check for AI-authored commits + if: github.event_name == 'pull_request' + uses: ./.github/actions/ai-commit-check +``` + +## Inputs + +| Input | Default | Description | +| ------------------- | -------------------- | ------------------------------------------------------------------------------- | +| `repository` | current repository | The `owner/name` of the repository that holds the pull request. | +| `pull-request` | triggering PR number | The number of the pull request to check. | +| `expected-count` | PR commit count | The number of commits the pull request contains, used to detect a short list. | +| `fail-on-detection` | `true` | When `true`, exit non-zero on detection. Set to `false` to report outputs only. | +| `pattern` | built-in | The regular expression that flags AI metadata. | +| `token` | workflow token | The token that reads the commits of the pull request. | + +## Outputs + +| Output | Description | +| ------------------ | ------------------------------------------------------------- | +| `ai-commits-found` | `"true"` if the action detected AI-authored commits. | +| `count` | The number of commits that the action flagged as AI-authored. | +| `commits` | The flagged commit SHAs, separated by newlines. | + +## Attribution + +Licensed under the MIT License. See [LICENSE.MIT](LICENSE.MIT). diff --git a/.github/actions/ai-commit-check/action.yml b/.github/actions/ai-commit-check/action.yml new file mode 100644 index 000000000..7db201180 --- /dev/null +++ b/.github/actions/ai-commit-check/action.yml @@ -0,0 +1,45 @@ +name: "AI Commit Check" +description: "Detect AI-authored commits or AI metadata trailers in a pull request." +inputs: + repository: + description: "The `owner/name` of the repository that holds the pull request. Defaults to the repository of the workflow." + default: "" + pull-request: + description: "The number of the pull request to check. Defaults to the pull request that started the workflow." + default: "" + expected-count: + description: "The number of commits that the pull request contains. The action fails if the API returns fewer commits than this, because the API truncates long lists. Defaults to the count in the pull request event." + default: "" + fail-on-detection: + description: 'When "true", exit non-zero if the action detects AI-authored commits. Set this to "false" to report through the outputs only.' + default: "true" + pattern: + description: "The regular expression that flags AI metadata. When empty, the action uses a built-in pattern." + default: "" + token: + description: "The token that reads the commits of the pull request. Defaults to the token of the workflow." + default: "" +outputs: + ai-commits-found: + description: '"true" if the action detected AI-authored commits, otherwise "false".' + value: ${{ steps.check.outputs.ai-commits-found }} + count: + description: "The number of commits that the action flagged as AI-authored." + value: ${{ steps.check.outputs.count }} + commits: + description: "The flagged commit SHAs, separated by newlines." + value: ${{ steps.check.outputs.commits }} +runs: + using: "composite" + steps: + - name: Check commits for AI authorship + id: check + shell: bash + env: + AICC_REPOSITORY: ${{ inputs.repository || github.repository }} + AICC_PULL_REQUEST: ${{ inputs.pull-request || github.event.pull_request.number }} + AICC_EXPECTED_COUNT: ${{ inputs.expected-count || github.event.pull_request.commits }} + AICC_FAIL_ON_DETECTION: ${{ inputs.fail-on-detection }} + AICC_PATTERN: ${{ inputs.pattern }} + GH_TOKEN: ${{ inputs.token || github.token }} + run: bash "${{ github.action_path }}/scripts/check.sh" diff --git a/.github/actions/ai-commit-check/scripts/check.sh b/.github/actions/ai-commit-check/scripts/check.sh new file mode 100644 index 000000000..b2e98af95 --- /dev/null +++ b/.github/actions/ai-commit-check/scripts/check.sh @@ -0,0 +1,111 @@ +#!/usr/bin/env bash +set -euo pipefail + +# The inputs come in through environment variables. See action.yml. +REPOSITORY="${AICC_REPOSITORY:-}" +PULL_REQUEST="${AICC_PULL_REQUEST:-}" +EXPECTED_COUNT="${AICC_EXPECTED_COUNT:-}" +FAIL_ON_DETECTION="${AICC_FAIL_ON_DETECTION:-true}" +PATTERN="${AICC_PATTERN:-}" + +if [ -z "$REPOSITORY" ] || [ -z "$PULL_REQUEST" ]; then + echo "::error::This action needs a pull request. Run it on a 'pull_request' event, or set the 'repository' and 'pull-request' inputs." + exit 1 +fi + +# The default detection pattern flags common AI metadata signatures. +# These are based on https://botcommits.dev, the documentation of each AI platform, +# and some other miscellaneous references. Feel free to add more or fix any false positives! +if [ -z "$PATTERN" ]; then + PATTERN='(Co-authored-by|Signed-off-by|Authorized-by):.*(Claude|Copilot|Cursor|Codex|ChatGPT|GPT-|Gemini|Jules|Devin|Aider)' + PATTERN="$PATTERN"'|Generated with (\[)?(Claude Code|Cursor|Copilot)|🤖 Generated' + PATTERN="$PATTERN"'|claude\.ai/code|claude\.com/claude-code' + PATTERN="$PATTERN"'|noreply@anthropic\.com|noreply@openai\.com|github-copilot\[bot\]' + PATTERN="$PATTERN"'|cursoragent|@cursor\.com|devin-ai-integration|@devin\.ai|google-labs-jules|[0-9]+\+Copilot@users\.noreply\.github\.com|\[aider\]|\(aider\)' +fi + +echo "Reading the commits of $REPOSITORY#$PULL_REQUEST..." + +# The API supplies the commit metadata, so the workflow does not need the git +# history. A shallow checkout is sufficient. +# +# Each commit becomes one line that holds the SHA and a base64 record. The +# record holds the author name, the author email, the committer name, the +# committer email, and the full message, separated by newlines. +commits=$(gh api --paginate "repos/$REPOSITORY/pulls/$PULL_REQUEST/commits" --jq ' + .[] | "\(.sha) \( + [ + .commit.author.name, + .commit.author.email, + .commit.committer.name, + .commit.committer.email, + .commit.message + ] | join("\n") | @base64 + )" +') + +read_count=0 +if [ -n "$commits" ]; then + read_count=$(printf '%s\n' "$commits" | wc -l) +fi + +# The API lists at most 250 commits. Fail on a partial list instead of passing. +if [ -n "$EXPECTED_COUNT" ] && [ "$read_count" -lt "$EXPECTED_COUNT" ]; then + echo "::error::Read $read_count of the $EXPECTED_COUNT commits in $REPOSITORY#$PULL_REQUEST. The pull request is too long for the API to list. Check the remaining commits by hand." + exit 1 +fi + +echo "Evaluating $read_count commit(s)." + +failed=0 +count=0 +offending=() + +while IFS=' ' read -r sha record; do + [ -z "$sha" ] && continue + + text=$(printf '%s' "$record" | base64 -d) + + if printf '%s' "$text" | grep -Eiq "$PATTERN"; then + echo "::error::Commit $sha appears to be AI-authored or contains AI trailers." + echo "--------------------------------------------------" + echo " Commit: ${sha:0:9}" + echo " Author: $(printf '%s\n' "$text" | sed -n '1p') <$(printf '%s\n' "$text" | sed -n '2p')>" + echo " Committer: $(printf '%s\n' "$text" | sed -n '3p') <$(printf '%s\n' "$text" | sed -n '4p')>" + echo " Message:" + printf '%s\n' "$text" | tail -n +5 | sed 's/^/ /' + echo "--------------------------------------------------" + failed=1 + count=$((count + 1)) + offending+=("$sha") + fi +done <<<"$commits" + +# Emit step outputs so callers can react to the result. +if [ -n "${GITHUB_OUTPUT:-}" ]; then + if [ "$failed" -ne 0 ]; then + echo "ai-commits-found=true" >>"$GITHUB_OUTPUT" + else + echo "ai-commits-found=false" >>"$GITHUB_OUTPUT" + fi + echo "count=$count" >>"$GITHUB_OUTPUT" + { + echo "commits<<__AICC_EOF__" + if [ "${#offending[@]}" -gt 0 ]; then + printf '%s\n' "${offending[@]}" + fi + echo "__AICC_EOF__" + } >>"$GITHUB_OUTPUT" +fi + +if [ "$failed" -ne 0 ]; then + echo "Detected $count AI-authored commit(s) in $REPOSITORY#$PULL_REQUEST." + if [ "$FAIL_ON_DETECTION" = "true" ]; then + echo "Error: Attribution of commits to AIs is not allowed. Please remove the attribution." + exit 1 + fi + echo "fail-on-detection is disabled; reporting through the 'ai-commits-found' output instead of failing." + exit 0 +fi + +echo "Success: No AI-authored commits found in $REPOSITORY#$PULL_REQUEST." diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index d1780bb95..390971cd3 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,4 +1,5 @@ -**Connections** +## Connections + _Link to the issues addressed by this PR, or dependent PRs in other repositories_ _When one pull request builds on another, please put "Depends on @@ -6,21 +7,31 @@ _When one pull request builds on another, please put "Depends on notice that they shouldn't merge it until its ancestor has been approved. Don't use draft PR status to indicate this._ -**Description** +## Description + _Describe what problem this is solving, and how it's solved._ -**Testing** +## Testing + _Explain what you have done to ensure this change is adequately tested (e.g. adding test cases, running tests on an unusual platform, or manually checking visual results)._ -**Squash or Rebase?** +## Squash or Rebase? + _If your pull request contains multiple commits, please indicate whether they need to be squashed into a single commit before they're merged, or if they're ready to rebase onto `trunk` as they stand. In the latter case, please ensure that each commit passes all CI tests, so that we can continue to bisect along `trunk` to isolate bugs._ +## LLM Use? + +_Let us know how you used LLMs for this PR. This helps us understand +the classes of issues we should look for. LLM use is allowed, but we +ask that you understand all the code you submit and treat it as your own. +We do ask that any significant descriptions be written by hand._ + -**Checklist** +## Checklist @@ -40,3 +51,8 @@ person(s) who reviewed your changes. This will make sure it gets re-added to the - [ ] (If applicable) WebGPU implementations built with `wgpu` may be affected behaviorally. - [ ] (If applicable) Validation and feature gates are in place to confine behavioral changes. - [ ] (If applicable) Tests demonstrate the validation and altered logic works. + + diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ac2179d80..59591ec1d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -881,12 +881,21 @@ jobs: with: persist-credentials: false + # Only pull requests give a well-defined commit range. The merge queue + # runs the commits that this check already saw on the pull request. + - name: Check for AI-authored commits + if: github.event_name == 'pull_request' + uses: $/.github/actions/ai-commit-check + - name: Install repo MSRV toolchain run: | rustup toolchain install ${{ env.REPO_MSRV }} --no-self-update --profile=minimal --component rustfmt rustup override set ${{ env.REPO_MSRV }} cargo -V + - name: Check repository files + run: cargo --locked xtask sync-repo-files --check + # NOTE: Keep this above the others, because this will fail if there are _any_ changes to # files, even ones this step doesn't modify. - name: "Format `**/*.{md,js,html,yml}` files" diff --git a/AGENTS.md b/AGENTS.md index 9b2933380..5f8a888b9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,198 +1,75 @@ -# Global instructions +# wgpu Project Structure + +wgpu is a GPU API written in pure rust. Changes of any significance need to apply across the stack. + +- `naga` is our shader translator. It is responsible for consuming and translating untrusted shaders to trusted shader code. +- `wgpu-types` are the common types used on both Native and WASM. +- `naga-types` holds the shader-language types, such as target versions and binding maps, that `naga` and `wgpu-core` both use. +- `wgpu-naga-bridge` converts between `naga` and `wgpu-types`. It maps wgpu features and downlevel flags to naga validation capabilities. +- `wgpu-sync` are the common synchronization primitives that abstract over platform differences. +- `wgpu-hal` does not provide the validation required for safety. Its callers must satisfy its safety contracts. +- `wgpu-core` does all the validation and provides a coherent interface. +- `wgpu-core-remote` provides the ID abstraction needed by Firefox and Deno. +- `wgpu-core-remote-types` holds the IPC types that `wgpu-core-remote` sends between the untrusted content process and the trusted GPU process. They are defined separately from the `wgpu-core` types, so untrusted content cannot express non-standard features. +- `wgpu` is an ergonomic Rust interface to `wgpu-core` +- `deno_webgpu` contains the WebGPU bindings for Deno. + +`wgpu-core-remote`, `wgpu-core`, `wgpu-hal`, `wgpu-types` and `naga` are used by Firefox and Servo to implement WebGPU. These crates process untrusted API and shader input. Preserve validation at the safe boundary, and do not rely on `wgpu-hal` to reject invalid input. Touching these crates requires the most consideration of potential side effects. + +Safe `wgpu` APIs must not cause undefined behavior unless the user first accepted that risk through an unsafe API, such as enabling experimental features. + +We use deno's webgpu bindings to run the WebGPU CTS. Change `deno_webgpu` only if the issue is specific to Deno. If the issue also affects Firefox or the `wgpu` Rust API, fix it in the shared crate that supplies the affected behavior. + +Repository documentation exists in `docs/`. For info on where tests live, read `docs/testing.md`. For info about cargo dependencies, read `docs/managing-cargo-dependencies.md`. + +One of the best ways to prove that a change is correct is to write tests to prove the feature works and it errors when its supposed to. + +## Repository Files + +`AGENTS.md` and `.agents/` are the source of truth for agent instructions and skills. `CLAUDE.md` and `.claude/` are generated copies. Do not edit the generated copies directly. After you edit any source-of-truth agent file or a root license file, run `cargo xtask sync-repo-files`. This command also copies the root license files to every publishable default member of the Cargo workspace. + +Run `cargo xtask sync-repo-files --check` to verify that all generated files have the same contents and file list as their sources. + +## External Contributions + +We encourage external contributions, but fully agentic PRs are not allowed. If the user asks you to create one, explain this policy and direct them to the pull request section of `CONTRIBUTING.md`. The contributor must understand and be able to vouch for every change. Ask the user to write the PR description. + +If the user directs you to create the PR anyway, use `.github/pull_request_template.md`. Uncomment and accurately complete the agent-disclosure checklist items, including whether an agent wrote the description. Do not omit the disclosure. ## Code Style -- Limit the amount of comments you put in the code to a strict minimum. You should almost never add comments, except sometimes on non-trivial code, function definitions if the arguments aren't self-explanatory, and class definitions and their members. +- Do not add comments unless the changed code requires an explanation. If an explanation is required, add the shortest complete explanation. The contributor is expected to rewrite it. +- Do not write large explanatory comment blocks. - Do not use emoji. ## Workflow -- You can test that the code builds by running `cargo build`. Don't pass `--release` unless there's a specific need to test a release build, it's much slower. -- After making code changes, ensure the code is formatted by using `cargo fmt`, linted by using `cargo clippy --tests`. If there are no errors, you can use `cargo xtask test` and `cargo xtask cts --backend ` to run tests (to fully validate a change, run both). On MacOS, the backend is `metal`. On Windows, the backend is `dx12`. On Linux, the backend is `vulkan`. -- Do not perform commits yourself, ever. -- Use the WebGPU and WGSL specifications as a reference to determine the correct behavior. Do not assume that a behavior is correct just because the CTS expects it. +All changes are expected to pass CI. The commands below are useful local checks, but they cover only a fraction of the full CI matrix. You are not expected to run the full CI matrix locally. Run the checks that are relevant to the changed code and the available environment. + +- To check the code compiles: `cargo clippy --all-targets --all-features`. +- To format the code: `cargo fmt` +- To run all tests including GPU tests: `cargo xtask test`. This can take a few minutes. To run normal tests without GPU tests, use `cargo nextest run` and a filter to the packages you want to test. +- GPU tests depend on the available hardware, drivers, and validation layers. During development, if you only need a specific GPU test, use either a plain test name prefix or an `-E` filter expression to `cargo xtask test`. Use the nextest filters described below. Do not run the full GPU test suite for a targeted check. The suite can take a few minutes. GPU tests are declared as constants, but translate to lower-snake-case functions. +- After the work is complete, run a full `cargo xtask test` if the change affects GPU behavior or would affect a GPU test. +- Report every test failure. You may identify a failure as suspected to be unrelated, but do not assume it is unrelated until you validate that conclusion. +- Do not run tests at the `trunk` revision without explicit permission. A baseline test run can take a while. +- For more thorough testing, you can run `cargo xtask cts --backend `. Only do this if you are explicitly asked to run the CTS. +- Never commit anything without being asked, ever. If you are asked to make a commit, _never_ co-author yourself. +- Use the WebGPU and WGSL specifications as a reference to determine the correct behavior. Do not assume that a behavior is correct just because the CTS expects it. Use the `webgpu-specs` skill if you need to check either spec. + +### Nextest filters + +`cargo xtask test` forwards its extra arguments to cargo-nextest. + +- A plain positional filter matches test names that contain the filter text. A unique test name prefix is usually sufficient. +- `-E 'test(name)'` matches test names that contain `name`. +- `-E 'test(=name)'` matches the complete test name. +- `-E 'test(/expression/)'` matches test names with a regular expression. +- In an `-E` expression, `package(name)` restricts the package and `binary(name)` restricts the test binary. Restricting binaries can make test startup quicker. +- Use `&` for intersection, `|` for union, and `!` for exclusion. Use parentheses to group expressions. +- For example, `-E 'binary(wgpu-gpu) & test(buffer) & !test(map)'` selects tests in the `wgpu-gpu` binary whose names contain `buffer` but not `map`. +- Quote each `-E` expression so the shell does not interpret its operators. ## Changelog -We maintain a changelog in CHANGELOG.md. Changes should be noted in the -changelog if they are user-visible (changes to documented public APIs, -significant bug fixes, or new functionality). Changelog descriptions should be -concise. If you are not sure whether something should be in the CHANGELOG or -you are not sure how to describe the change, ask the user for guidance. - -## More information about tests - -There is some more detailed information about tests in @docs/testing.md. - -# CTS - -## Listing and Running Individual Tests - -Each line is a selector that will run multiple subtests. You can run a test with: - -```bash -cargo xtask cts 'webgpu:selector/path:test:*' -``` - -For fixing problems, it may be useful to run specific cases. You can get a list of the subtests with: - -```bash -cargo xtask cts -- --list 'webgpu:selector,path:test:*' -``` - -Then you can pass individual subtests on the command line as the selector. - -## Running Suites - -To run a suite of CTS tests and keep just the summary at the end: - -```bash -cargo xtask cts 'webgpu:selector,path:test:*' 2>&1 | grep -E "(Summary|Passed|Failed)" | tail -5 -``` - -To run a suite of tests and keep just the failing tests: - -```bash -cargo xtask cts 'webgpu:selector,path:test:*' 2>&1 | grep "\[fail\]" -``` - -## Keeping Track of Results - -We maintain three files listing CTS test selectors that are expected to pass, -not pass, or to be entirely skipped. These files are respectively -cts_runner/test.lst, cts_runner/fail.lst, and cts_runner/skip.lst. - -If you fix a CTS test, add the selector to test.lst. Be aware that the file is -not an exhaustive list of passing tests. - -CI expects every test in test.lst to pass, so only add suites that have zero -failures to test.lst. Do not add any suites that are not 100% pass/skip, even -if they are ≥99% passing. - -List suites with failures in fail.lst. You can put a comment `// xx%` -noting the pass rate, especially in cases where the pass rate is high. - -List suites that are ≥90% skips in skip.lst - -When adding to a lst file, use wildcards to identify the tests with as few lines -as possible. In some cases when adding tests it may be possible to combine with -existing lines to use a higher level wildcard. Only use a higher level wildcard -when all the tests it will match go in the same file. Do not use a higher level -wildcard if it would match tests that belong in a different file. - -## Source for the CTS Tests - -The TypeScript sources for the CTS are under cts/src. There is also generated JavaScript in cts/out. -Do not assume that a behavior is correct just because a CTS test expects it. Verify the correct -behavior in the WebGPU or WGSL specification. - -# Overview of the Code - -See `wgpu/src/documentation/images/big-picture.webp` for an overview of the system. - -The major components are: - -- `wgpu-hal` implements a backend for each supported graphics API (Vulkan, DX12, Metal, GLES). - -- `wgpu-core` implements the WebGPU API, including resource management and validation. - It calls the platform graphics APIs via `wgpu-hal`, and uses `naga` for shader translation. - -- `wgpu` is the native Rust API. In addition to providing bindings to `wgpu-core`, the `wgpu` - crate can also be compiled to WASM and built against the "WebGPU" backend, where it uses - whatever WebGPU implementation is provided by the WASM environment. `wgpu` is not used - by Deno and Firefox. - -- `naga` is the shader translator. It reads shaders in WGSL, GLSL, or SPIR-V, - translates to Naga IR, and then writes shaders in GLSL, HLSL, MSL (Metal Shading Language), SPIR-V, or WGSL. - It is responsible for validating that WGSL shaders are valid according to the WGSL language specification. - -- `wgpu-types` contains some type definitions that are applicable both to `wgpu-core` and to - the `wgpu` "WebGPU" backend. - -- `deno_webgpu` contains WebGPU bindings for the Deno Javascript runtime. - We also use Deno as a test environment for running the WebGPU CTS. - Only make a change in the Deno bindings if you are sure that the issue - doesn't apply to other clients (Firefox or `wgpu` Rust API). If it does - apply to other clients, the issue should probably be fixed in `wgpu-core`. - -For a more detailed discussion of the `wgpu` architecture, refer to -wgpu/src/documentation/internals/architecture.rs - -## Naga - -### Constant Evaluator (`naga/src/proc/constant_evaluator.rs`) - -The constant evaluator is responsible for evaluating constant expressions at compile time in WGSL/GLSL shaders. - -**Key Components:** - -1. **Expression Handling** (~line 1228): The `try_eval_and_append_impl` method handles different expression types and evaluates them if possible. - -2. **Type Conversions**: - - `cast()` (~line 2256): Handles type conversions with `Expression::As` where `convert` is `Some(width)` - - `bitcast()` (~line 2449): Handles bit reinterpretation with `Expression::As` where `convert` is `None` - - Key insight: For bitcast, the target width equals the source width (bit-preserving operation) - -3. **Helper Macros**: - - `gen_component_wise_extractor!`: Generates functions for component-wise operations on scalars/vectors - - `component_wise_scalar!`, `component_wise_float!`: Convenience macros for applying operations to each component - -4. **Borrow Checker Patterns**: - - When implementing methods that need to call themselves recursively or make multiple mutable borrows, extract all needed data from `self` fields before the recursive calls - - Clone vectors before iterating if you need to mutably borrow `self` during iteration - -## Expression Types and Type Inference - -- `Expression::As` with `convert: None` represents bitcast operations -- The validator (`naga/src/valid/expression.rs` ~line 1132) determines result types by: - - Getting source type's scalar - - Updating the `kind` to target kind - - Keeping the same `width` for bitcast (no conversion) - -# Other - -This is stuff that Claude wrote for itself. It can probably be improved. - -## Naga Tests - -**Test Structure:** - -1. **Unit Tests**: In the same file as the code being tested - - Example: `naga/src/proc/constant_evaluator.rs` has tests in a `#[cfg(test)] mod tests` block - - Pattern: Create arenas, build expressions, evaluate, assert results - -2. **Snapshot Tests**: - - Input files: `naga/tests/in/wgsl/*.wgsl` - - Output files: `naga/tests/out/wgsl/*.wgsl` - - Run with: `cargo test -p naga --test naga snapshots::convert_snapshots_wgsl` - - The output shows how constant expressions are evaluated at compile time - -3. **Adding Integration Tests**: - - Add test WGSL code to `naga/tests/in/wgsl/const-exprs.wgsl` for const expression tests - - The test automatically parses, validates, and generates output in `naga/tests/out/wgsl/wgsl-const-exprs.wgsl` - - Verify constant evaluation by checking the output file - -**Running Tests:** - -```bash -# Unit tests only -cargo test -p naga --lib - -# Specific test -cargo test -p naga --lib bitcast - -# All naga tests (including integration) -cargo test -p naga - -# WGSL snapshot tests -cargo test -p naga --test naga snapshots::convert_snapshots_wgsl -``` - -## WGSL Specification Implementation - -When implementing WGSL built-in functions: - -1. **Read the spec carefully**: WGSL spec section numbers are usually commented in code (e.g., "17.2.1. bitcast") -2. **Check parameterization**: The spec lists exactly which type combinations are valid -3. **Don't assume types**: For bitcast, only `i32`, `u32`, `f32` are specified - not 64-bit types -4. **AbstractInt special cases**: Some operations have special handling for abstract integers +We maintain a changelog in CHANGELOG.md. Changes should be noted in the changelog if they are user-visible (changes to documented public APIs, significant bug fixes, or new functionality). We generally do not consider changes to wgpu-core, wgpu-hal, wgpu-core-remote, or wgpu-core-remote-types worthy of changelogs, unless a `wgpu` user is expected to interface with them directly. Changelog descriptions should be concise. If you are not sure whether something should be in the CHANGELOG or you are not sure how to describe the change, ask the user for guidance. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 000000000..5f8a888b9 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,75 @@ +# wgpu Project Structure + +wgpu is a GPU API written in pure rust. Changes of any significance need to apply across the stack. + +- `naga` is our shader translator. It is responsible for consuming and translating untrusted shaders to trusted shader code. +- `wgpu-types` are the common types used on both Native and WASM. +- `naga-types` holds the shader-language types, such as target versions and binding maps, that `naga` and `wgpu-core` both use. +- `wgpu-naga-bridge` converts between `naga` and `wgpu-types`. It maps wgpu features and downlevel flags to naga validation capabilities. +- `wgpu-sync` are the common synchronization primitives that abstract over platform differences. +- `wgpu-hal` does not provide the validation required for safety. Its callers must satisfy its safety contracts. +- `wgpu-core` does all the validation and provides a coherent interface. +- `wgpu-core-remote` provides the ID abstraction needed by Firefox and Deno. +- `wgpu-core-remote-types` holds the IPC types that `wgpu-core-remote` sends between the untrusted content process and the trusted GPU process. They are defined separately from the `wgpu-core` types, so untrusted content cannot express non-standard features. +- `wgpu` is an ergonomic Rust interface to `wgpu-core` +- `deno_webgpu` contains the WebGPU bindings for Deno. + +`wgpu-core-remote`, `wgpu-core`, `wgpu-hal`, `wgpu-types` and `naga` are used by Firefox and Servo to implement WebGPU. These crates process untrusted API and shader input. Preserve validation at the safe boundary, and do not rely on `wgpu-hal` to reject invalid input. Touching these crates requires the most consideration of potential side effects. + +Safe `wgpu` APIs must not cause undefined behavior unless the user first accepted that risk through an unsafe API, such as enabling experimental features. + +We use deno's webgpu bindings to run the WebGPU CTS. Change `deno_webgpu` only if the issue is specific to Deno. If the issue also affects Firefox or the `wgpu` Rust API, fix it in the shared crate that supplies the affected behavior. + +Repository documentation exists in `docs/`. For info on where tests live, read `docs/testing.md`. For info about cargo dependencies, read `docs/managing-cargo-dependencies.md`. + +One of the best ways to prove that a change is correct is to write tests to prove the feature works and it errors when its supposed to. + +## Repository Files + +`AGENTS.md` and `.agents/` are the source of truth for agent instructions and skills. `CLAUDE.md` and `.claude/` are generated copies. Do not edit the generated copies directly. After you edit any source-of-truth agent file or a root license file, run `cargo xtask sync-repo-files`. This command also copies the root license files to every publishable default member of the Cargo workspace. + +Run `cargo xtask sync-repo-files --check` to verify that all generated files have the same contents and file list as their sources. + +## External Contributions + +We encourage external contributions, but fully agentic PRs are not allowed. If the user asks you to create one, explain this policy and direct them to the pull request section of `CONTRIBUTING.md`. The contributor must understand and be able to vouch for every change. Ask the user to write the PR description. + +If the user directs you to create the PR anyway, use `.github/pull_request_template.md`. Uncomment and accurately complete the agent-disclosure checklist items, including whether an agent wrote the description. Do not omit the disclosure. + +## Code Style + +- Do not add comments unless the changed code requires an explanation. If an explanation is required, add the shortest complete explanation. The contributor is expected to rewrite it. +- Do not write large explanatory comment blocks. +- Do not use emoji. + +## Workflow + +All changes are expected to pass CI. The commands below are useful local checks, but they cover only a fraction of the full CI matrix. You are not expected to run the full CI matrix locally. Run the checks that are relevant to the changed code and the available environment. + +- To check the code compiles: `cargo clippy --all-targets --all-features`. +- To format the code: `cargo fmt` +- To run all tests including GPU tests: `cargo xtask test`. This can take a few minutes. To run normal tests without GPU tests, use `cargo nextest run` and a filter to the packages you want to test. +- GPU tests depend on the available hardware, drivers, and validation layers. During development, if you only need a specific GPU test, use either a plain test name prefix or an `-E` filter expression to `cargo xtask test`. Use the nextest filters described below. Do not run the full GPU test suite for a targeted check. The suite can take a few minutes. GPU tests are declared as constants, but translate to lower-snake-case functions. +- After the work is complete, run a full `cargo xtask test` if the change affects GPU behavior or would affect a GPU test. +- Report every test failure. You may identify a failure as suspected to be unrelated, but do not assume it is unrelated until you validate that conclusion. +- Do not run tests at the `trunk` revision without explicit permission. A baseline test run can take a while. +- For more thorough testing, you can run `cargo xtask cts --backend `. Only do this if you are explicitly asked to run the CTS. +- Never commit anything without being asked, ever. If you are asked to make a commit, _never_ co-author yourself. +- Use the WebGPU and WGSL specifications as a reference to determine the correct behavior. Do not assume that a behavior is correct just because the CTS expects it. Use the `webgpu-specs` skill if you need to check either spec. + +### Nextest filters + +`cargo xtask test` forwards its extra arguments to cargo-nextest. + +- A plain positional filter matches test names that contain the filter text. A unique test name prefix is usually sufficient. +- `-E 'test(name)'` matches test names that contain `name`. +- `-E 'test(=name)'` matches the complete test name. +- `-E 'test(/expression/)'` matches test names with a regular expression. +- In an `-E` expression, `package(name)` restricts the package and `binary(name)` restricts the test binary. Restricting binaries can make test startup quicker. +- Use `&` for intersection, `|` for union, and `!` for exclusion. Use parentheses to group expressions. +- For example, `-E 'binary(wgpu-gpu) & test(buffer) & !test(map)'` selects tests in the `wgpu-gpu` binary whose names contain `buffer` but not `map`. +- Quote each `-E` expression so the shell does not interpret its operators. + +## Changelog + +We maintain a changelog in CHANGELOG.md. Changes should be noted in the changelog if they are user-visible (changes to documented public APIs, significant bug fixes, or new functionality). We generally do not consider changes to wgpu-core, wgpu-hal, wgpu-core-remote, or wgpu-core-remote-types worthy of changelogs, unless a `wgpu` user is expected to interface with them directly. Changelog descriptions should be concise. If you are not sure whether something should be in the CHANGELOG or you are not sure how to describe the change, ask the user for guidance. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5dafa98ec..072279554 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -179,6 +179,17 @@ However, the author submitting the PR must fully adhere to [Change Ownership](#c The author is responsible for the code, regardless of how it was created. Do not use "LLM generated" as a justification for low quality code. +Additionally, please write Issue and PR descriptions and large explanatory +comment blocks yourself. These need to be read by maintainers and maintainer +time is at a premium, so be respectful of maintainers time by not giving +them unadulterated LLM content to read. + +#### Undue Burden + +We reserve the right to close any PRs that cause an undue burden on +the maintainership. This could include, but is not limited to, [massive PRs](#large-pull-requests-are-risky), +[LLM slop](#llms-ai), or contributions not in good faith. + #### Designing new features As an open source project, wgpu wants to serve a broad audience. This @@ -194,12 +205,6 @@ consensus on the approach, including API changes, shader language extensions, implementation architecture, error handling, testing plans, benchmarking, and so on. -#### Undue Burden - -We reserve the right to close any PRs that cause an undue burden on -the maintainership. This could include, but is not limited to, [massive PRs](#large-pull-requests-are-risky), -[LLM slop](#llms-ai), or contributions not in good faith. - #### Large pull requests are risky Contributors should anticipate that the larger and more complex a pull diff --git a/LICENSE.MIT b/LICENSE.MIT index 8d02e4dbd..709e6b7fd 100644 --- a/LICENSE.MIT +++ b/LICENSE.MIT @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2025 The gfx-rs developers +Copyright (c) 2026 The gfx-rs developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/docs/broadcast_license.nu b/docs/broadcast_license.nu deleted file mode 100644 index 8f3b2c020..000000000 --- a/docs/broadcast_license.nu +++ /dev/null @@ -1,26 +0,0 @@ -# Quick maintenance script which broadcasts the license files to all crates -# that are released on crates.io - -# Change to the root of the repository -cd ($env.FILE_PWD | path dirname) - -let crates = [ - "wgpu", - "wgpu-core", - "wgpu-core/platform-deps/apple", - "wgpu-core/platform-deps/emscripten", - "wgpu-core/platform-deps/wasm", - "wgpu-core/platform-deps/linux-android-bsd", - "wgpu-core/platform-deps/windows", - "wgpu-hal", - "wgpu-info", - "wgpu-naga-bridge", - "wgpu-sync", - "wgpu-types", - "naga", - "naga-cli", -] - -for crate in $crates { - cp LICENSE.APACHE LICENSE.MIT $"./($crate)/" -} diff --git a/naga-cli/LICENSE.MIT b/naga-cli/LICENSE.MIT index 8d02e4dbd..709e6b7fd 100644 --- a/naga-cli/LICENSE.MIT +++ b/naga-cli/LICENSE.MIT @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2025 The gfx-rs developers +Copyright (c) 2026 The gfx-rs developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/naga-types/LICENSE.MIT b/naga-types/LICENSE.MIT index 8d02e4dbd..709e6b7fd 100644 --- a/naga-types/LICENSE.MIT +++ b/naga-types/LICENSE.MIT @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2025 The gfx-rs developers +Copyright (c) 2026 The gfx-rs developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/naga/LICENSE.MIT b/naga/LICENSE.MIT index 8d02e4dbd..709e6b7fd 100644 --- a/naga/LICENSE.MIT +++ b/naga/LICENSE.MIT @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2025 The gfx-rs developers +Copyright (c) 2026 The gfx-rs developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/wgpu-core-remote-types/LICENSE.APACHE b/wgpu-core-remote-types/LICENSE.APACHE new file mode 100644 index 000000000..d9a10c0d8 --- /dev/null +++ b/wgpu-core-remote-types/LICENSE.APACHE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/wgpu-core-remote-types/LICENSE.MIT b/wgpu-core-remote-types/LICENSE.MIT new file mode 100644 index 000000000..709e6b7fd --- /dev/null +++ b/wgpu-core-remote-types/LICENSE.MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 The gfx-rs developers + +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. diff --git a/wgpu-core-remote/LICENSE.APACHE b/wgpu-core-remote/LICENSE.APACHE new file mode 100644 index 000000000..d9a10c0d8 --- /dev/null +++ b/wgpu-core-remote/LICENSE.APACHE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/wgpu-core-remote/LICENSE.MIT b/wgpu-core-remote/LICENSE.MIT new file mode 100644 index 000000000..709e6b7fd --- /dev/null +++ b/wgpu-core-remote/LICENSE.MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 The gfx-rs developers + +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. diff --git a/wgpu-core/LICENSE.MIT b/wgpu-core/LICENSE.MIT index 8d02e4dbd..709e6b7fd 100644 --- a/wgpu-core/LICENSE.MIT +++ b/wgpu-core/LICENSE.MIT @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2025 The gfx-rs developers +Copyright (c) 2026 The gfx-rs developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/wgpu-core/platform-deps/apple/LICENSE.MIT b/wgpu-core/platform-deps/apple/LICENSE.MIT index 8d02e4dbd..709e6b7fd 100644 --- a/wgpu-core/platform-deps/apple/LICENSE.MIT +++ b/wgpu-core/platform-deps/apple/LICENSE.MIT @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2025 The gfx-rs developers +Copyright (c) 2026 The gfx-rs developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/wgpu-core/platform-deps/emscripten/LICENSE.MIT b/wgpu-core/platform-deps/emscripten/LICENSE.MIT index 8d02e4dbd..709e6b7fd 100644 --- a/wgpu-core/platform-deps/emscripten/LICENSE.MIT +++ b/wgpu-core/platform-deps/emscripten/LICENSE.MIT @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2025 The gfx-rs developers +Copyright (c) 2026 The gfx-rs developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/wgpu-core/platform-deps/linux-android-bsd/LICENSE.MIT b/wgpu-core/platform-deps/linux-android-bsd/LICENSE.MIT index 8d02e4dbd..709e6b7fd 100644 --- a/wgpu-core/platform-deps/linux-android-bsd/LICENSE.MIT +++ b/wgpu-core/platform-deps/linux-android-bsd/LICENSE.MIT @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2025 The gfx-rs developers +Copyright (c) 2026 The gfx-rs developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/wgpu-core/platform-deps/wasm/LICENSE.MIT b/wgpu-core/platform-deps/wasm/LICENSE.MIT index 8d02e4dbd..709e6b7fd 100644 --- a/wgpu-core/platform-deps/wasm/LICENSE.MIT +++ b/wgpu-core/platform-deps/wasm/LICENSE.MIT @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2025 The gfx-rs developers +Copyright (c) 2026 The gfx-rs developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/wgpu-core/platform-deps/windows/LICENSE.MIT b/wgpu-core/platform-deps/windows/LICENSE.MIT index 8d02e4dbd..709e6b7fd 100644 --- a/wgpu-core/platform-deps/windows/LICENSE.MIT +++ b/wgpu-core/platform-deps/windows/LICENSE.MIT @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2025 The gfx-rs developers +Copyright (c) 2026 The gfx-rs developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/wgpu-hal/LICENSE.MIT b/wgpu-hal/LICENSE.MIT index 8d02e4dbd..709e6b7fd 100644 --- a/wgpu-hal/LICENSE.MIT +++ b/wgpu-hal/LICENSE.MIT @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2025 The gfx-rs developers +Copyright (c) 2026 The gfx-rs developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/wgpu-info/LICENSE.MIT b/wgpu-info/LICENSE.MIT index 8d02e4dbd..709e6b7fd 100644 --- a/wgpu-info/LICENSE.MIT +++ b/wgpu-info/LICENSE.MIT @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2025 The gfx-rs developers +Copyright (c) 2026 The gfx-rs developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/wgpu-naga-bridge/LICENSE.MIT b/wgpu-naga-bridge/LICENSE.MIT index 8d02e4dbd..709e6b7fd 100644 --- a/wgpu-naga-bridge/LICENSE.MIT +++ b/wgpu-naga-bridge/LICENSE.MIT @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2025 The gfx-rs developers +Copyright (c) 2026 The gfx-rs developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/wgpu-types/LICENSE.MIT b/wgpu-types/LICENSE.MIT index 8d02e4dbd..709e6b7fd 100644 --- a/wgpu-types/LICENSE.MIT +++ b/wgpu-types/LICENSE.MIT @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2025 The gfx-rs developers +Copyright (c) 2026 The gfx-rs developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/wgpu/LICENSE.MIT b/wgpu/LICENSE.MIT index 8d02e4dbd..709e6b7fd 100644 --- a/wgpu/LICENSE.MIT +++ b/wgpu/LICENSE.MIT @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2025 The gfx-rs developers +Copyright (c) 2026 The gfx-rs developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 2102fcf99..23c33aab2 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -12,6 +12,7 @@ mod install_agility_sdk; mod install_warp; mod miri; mod run_wasm; +mod sync_repo_files; mod test; mod test_wasm; mod util; @@ -101,6 +102,12 @@ Commands: Must be a nightly toolchain. Defaults to `nightly`. + sync-repo-files + Sync agent files and crate licenses from their source-of-truth files + + --check Check for missing, extra, or different generated files without + changing them + vendor-web-sys Re-vendor the WebGPU web-sys bindings. @@ -170,6 +177,7 @@ fn main() -> anyhow::Result { Some("cts") => cts::run_cts(shell, args, passthrough_args)?, Some("run-wasm") => run_wasm::run_wasm(shell, args, passthrough_args)?, Some("miri") => miri::run_miri(shell, args)?, + Some("sync-repo-files") => sync_repo_files::run_sync_repo_files(shell, args)?, Some("test") => test::run_tests(shell, args, passthrough_args)?, Some("test-wasm") => test_wasm::run_wasm_tests(shell, args, passthrough_args)?, Some("vendor-web-sys") => vendor_web_sys::run_vendor_web_sys(shell, args)?, diff --git a/xtask/src/sync_repo_files.rs b/xtask/src/sync_repo_files.rs new file mode 100644 index 000000000..4878d9f6c --- /dev/null +++ b/xtask/src/sync_repo_files.rs @@ -0,0 +1,417 @@ +use std::{ + collections::BTreeSet, + path::{Path, PathBuf}, +}; + +use anyhow::{bail, Context}; +use pico_args::Arguments; +use xshell::Shell; + +mod file_sync; + +use file_sync::{sync_directory, sync_file, Mode}; + +const LICENSE_FILES: &[&str] = &["LICENSE.APACHE", "LICENSE.MIT"]; + +pub(crate) fn run_sync_repo_files(shell: Shell, mut args: Arguments) -> anyhow::Result<()> { + let mode = if args.contains("--check") { + Mode::Check + } else { + Mode::Write + }; + + let unknown_args = args.finish(); + if !unknown_args.is_empty() { + crate::bad_arguments!( + "Unknown arguments to sync-repo-files subcommand: {:?}", + unknown_args + ); + } + + let root = shell.current_dir(); + let license_targets = license_targets(&shell, &root)?; + let discrepancies = sync_repo_files(&root, &license_targets, mode)?; + + if discrepancies.is_empty() { + match mode { + Mode::Check => eprintln!("Repository files are synchronized."), + Mode::Write => eprintln!("Repository files synchronized."), + } + return Ok(()); + } + + for discrepancy in discrepancies { + eprintln!("error: {discrepancy}"); + } + eprintln!("hint: edit the source-of-truth files, then run `cargo xtask sync-repo-files`"); + bail!("repository files are not synchronized") +} + +/// Sync all repository files. +fn sync_repo_files( + root: &Path, + license_targets: &[PathBuf], + mode: Mode, +) -> anyhow::Result> { + let mut discrepancies = Vec::new(); + + // Sync AGENTS.md + sync_file( + root, + Path::new("AGENTS.md"), + Path::new("CLAUDE.md"), + mode, + &mut discrepancies, + )?; + // Sync .agents/ + sync_directory( + root, + Path::new(".agents"), + Path::new(".claude"), + mode, + &mut discrepancies, + )?; + + // Sync license files to each crate + for target in license_targets { + for license in LICENSE_FILES { + sync_file( + root, + Path::new(license), + &Path::new(target).join(license), + mode, + &mut discrepancies, + )?; + } + } + + Ok(discrepancies) +} + +/// Returns the list of all crates that need license files. +fn license_targets(shell: &Shell, root: &Path) -> anyhow::Result> { + let output = shell + .cmd("cargo") + .args(["metadata", "--locked", "--format-version", "1", "--no-deps"]) + .read() + .context("could not read Cargo metadata for license targets")?; + let metadata = serde_json::from_str(&output).context("could not parse Cargo metadata")?; + publishable_default_member_directories(&metadata, root) +} + +/// Extracts the directories of all default members of the repository. +/// +/// Grabs `$.workspace_default_members[*]` then uses that to index +/// into `$.packages[*]` and grab the `id`, `publish`, and `manifest_path` +/// fields. +fn publishable_default_member_directories( + metadata: &serde_json::Value, + root: &Path, +) -> anyhow::Result> { + // Both sides of the `strip_prefix` below must be canonical. Windows + // canonicalization adds a `\\?\` prefix that `cargo metadata` does not use. + let root = root + .canonicalize() + .with_context(|| format!("could not resolve the repository root `{}`", root.display()))?; + + let default_members = metadata + .get("workspace_default_members") + .and_then(serde_json::Value::as_array) + .context("Cargo metadata has no `workspace_default_members` array")?; + let default_member_ids = default_members + .iter() + .map(|member| { + member + .as_str() + .context("Cargo metadata contains a non-string default member ID") + }) + .collect::>>()?; + let packages = metadata + .get("packages") + .and_then(serde_json::Value::as_array) + .context("Cargo metadata has no `packages` array")?; + + let mut matched_default_members = BTreeSet::new(); + let mut targets = BTreeSet::new(); + for package in packages { + let id = package + .get("id") + .and_then(serde_json::Value::as_str) + .context("Cargo metadata package has no string `id`")?; + if !default_member_ids.contains(id) { + continue; + } + matched_default_members.insert(id); + + let publishable = match package.get("publish") { + None | Some(serde_json::Value::Null) => true, + Some(serde_json::Value::Array(registries)) => !registries.is_empty(), + Some(_) => bail!("Cargo metadata package `{id}` has an invalid `publish` value"), + }; + if !publishable { + continue; + } + + let manifest_path = package + .get("manifest_path") + .and_then(serde_json::Value::as_str) + .with_context(|| format!("Cargo metadata package `{id}` has no manifest path"))?; + let package_directory = Path::new(manifest_path) + .parent() + .with_context(|| format!("package manifest `{manifest_path}` has no parent directory"))? + .canonicalize() + .with_context(|| { + format!("could not resolve the directory of default member package `{id}`") + })?; + let relative_directory = package_directory.strip_prefix(&root).with_context(|| { + format!( + "default member package `{id}` is outside the repository root `{}`", + root.display() + ) + })?; + targets.insert(relative_directory.to_owned()); + } + + let missing_packages = default_member_ids + .difference(&matched_default_members) + .copied() + .collect::>(); + if !missing_packages.is_empty() { + bail!( + "Cargo metadata has no package entries for default members: {}", + missing_packages.join(", ") + ); + } + + Ok(targets.into_iter().collect()) +} + +#[cfg(test)] +mod tests { + use std::{ + fs, + path::{Path, PathBuf}, + process::{Command, Stdio}, + sync::atomic::{AtomicUsize, Ordering}, + }; + + use super::{publishable_default_member_directories, sync_directory, sync_file, Mode}; + + static NEXT_TEMP_DIRECTORY: AtomicUsize = AtomicUsize::new(0); + + fn git(directory: &Path, args: &[&str]) { + let status = Command::new("git") + .args(args) + .current_dir(directory) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .unwrap(); + assert!(status.success(), "`git {}` failed", args.join(" ")); + } + + struct TempDirectory(PathBuf); + + impl TempDirectory { + fn new() -> Self { + let id = NEXT_TEMP_DIRECTORY.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir() + .join(format!("wgpu-sync-repo-files-{}-{id}", std::process::id())); + fs::create_dir(&path).unwrap(); + git(&path, &["init"]); + // Keep the developer's global ignore rules out of the test. + git(&path, &["config", "core.excludesFile", "no-such-file"]); + Self(path) + } + + fn path(&self) -> &Path { + &self.0 + } + } + + impl Drop for TempDirectory { + fn drop(&mut self) { + fs::remove_dir_all(&self.0).unwrap(); + } + } + + #[test] + fn finds_publishable_default_member_directories() { + let temporary = TempDirectory::new(); + for package in ["public", "custom", "private", "other"] { + fs::create_dir(temporary.path().join(package)).unwrap(); + } + let public_manifest = temporary.path().join("public/Cargo.toml"); + let custom_manifest = temporary.path().join("custom/Cargo.toml"); + let private_manifest = temporary.path().join("private/Cargo.toml"); + let other_manifest = temporary.path().join("other/Cargo.toml"); + let metadata = serde_json::json!({ + "workspace_default_members": ["public", "custom", "private"], + "packages": [ + { + "id": "public", + "manifest_path": public_manifest, + "publish": null, + }, + { + "id": "custom", + "manifest_path": custom_manifest, + "publish": ["custom-registry"], + }, + { + "id": "private", + "manifest_path": private_manifest, + "publish": [], + }, + { + "id": "other", + "manifest_path": other_manifest, + "publish": null, + }, + ], + }); + + assert_eq!( + publishable_default_member_directories(&metadata, temporary.path()).unwrap(), + [PathBuf::from("custom"), PathBuf::from("public")] + ); + } + + #[test] + fn check_reports_missing_and_different_files() { + let temporary = TempDirectory::new(); + fs::write(temporary.path().join("source"), "source").unwrap(); + + let mut discrepancies = Vec::new(); + sync_file( + temporary.path(), + Path::new("source"), + Path::new("target"), + Mode::Check, + &mut discrepancies, + ) + .unwrap(); + assert_eq!(discrepancies.len(), 1); + assert!(discrepancies[0].contains("is missing")); + + fs::write(temporary.path().join("target"), "target").unwrap(); + discrepancies.clear(); + sync_file( + temporary.path(), + Path::new("source"), + Path::new("target"), + Mode::Check, + &mut discrepancies, + ) + .unwrap(); + assert_eq!(discrepancies.len(), 1); + assert!(discrepancies[0].contains("differs from")); + } + + #[test] + fn directory_check_reports_missing_extra_and_different_files() { + let temporary = TempDirectory::new(); + fs::create_dir_all(temporary.path().join("source/nested")).unwrap(); + fs::create_dir_all(temporary.path().join("target/obsolete")).unwrap(); + fs::write(temporary.path().join("source/nested/missing"), "missing").unwrap(); + fs::write(temporary.path().join("source/different"), "source").unwrap(); + fs::write(temporary.path().join("target/different"), "target").unwrap(); + fs::write(temporary.path().join("target/obsolete/extra"), "extra").unwrap(); + + let mut discrepancies = Vec::new(); + sync_directory( + temporary.path(), + Path::new("source"), + Path::new("target"), + Mode::Check, + &mut discrepancies, + ) + .unwrap(); + + assert_eq!(discrepancies.len(), 3); + assert!(discrepancies + .iter() + .any(|message| message.contains("missing"))); + assert!(discrepancies + .iter() + .any(|message| message.contains("extra"))); + assert!(discrepancies + .iter() + .any(|message| message.contains("differs from"))); + } + + #[test] + fn directory_sync_keeps_git_ignored_files() { + let temporary = TempDirectory::new(); + let root = temporary.path(); + fs::create_dir(root.join("source")).unwrap(); + fs::create_dir(root.join("generated")).unwrap(); + fs::write( + root.join(".gitignore"), + "generated/local +", + ) + .unwrap(); + fs::write(root.join("source/shared"), "shared").unwrap(); + fs::write(root.join("generated/shared"), "shared").unwrap(); + fs::write(root.join("generated/local"), "local").unwrap(); + fs::write(root.join("generated/stale"), "stale").unwrap(); + + let mut discrepancies = Vec::new(); + sync_directory( + root, + Path::new("source"), + Path::new("generated"), + Mode::Check, + &mut discrepancies, + ) + .unwrap(); + assert_eq!(discrepancies.len(), 1); + assert!(discrepancies[0].contains("stale")); + + discrepancies.clear(); + sync_directory( + root, + Path::new("source"), + Path::new("generated"), + Mode::Write, + &mut discrepancies, + ) + .unwrap(); + assert!(discrepancies.is_empty()); + assert!(root.join("generated/local").exists()); + assert!(!root.join("generated/stale").exists()); + } + + #[test] + fn directory_write_creates_updates_and_removes_files() { + let temporary = TempDirectory::new(); + fs::create_dir_all(temporary.path().join("source/nested")).unwrap(); + fs::create_dir_all(temporary.path().join("target/obsolete")).unwrap(); + fs::write(temporary.path().join("source/nested/missing"), "missing").unwrap(); + fs::write(temporary.path().join("source/different"), "source").unwrap(); + fs::write(temporary.path().join("target/different"), "target").unwrap(); + fs::write(temporary.path().join("target/obsolete/extra"), "extra").unwrap(); + + let mut discrepancies = Vec::new(); + sync_directory( + temporary.path(), + Path::new("source"), + Path::new("target"), + Mode::Write, + &mut discrepancies, + ) + .unwrap(); + + assert!(discrepancies.is_empty()); + assert_eq!( + fs::read_to_string(temporary.path().join("target/nested/missing")).unwrap(), + "missing" + ); + assert_eq!( + fs::read_to_string(temporary.path().join("target/different")).unwrap(), + "source" + ); + assert!(!temporary.path().join("target/obsolete").exists()); + } +} diff --git a/xtask/src/sync_repo_files/file_sync.rs b/xtask/src/sync_repo_files/file_sync.rs new file mode 100644 index 000000000..87338a8a1 --- /dev/null +++ b/xtask/src/sync_repo_files/file_sync.rs @@ -0,0 +1,266 @@ +use std::{ + collections::BTreeSet, + fs, + io::Write, + path::{Path, PathBuf}, + process::{Command, Stdio}, +}; + +use anyhow::{bail, Context}; +#[derive(Clone, Copy)] +pub(super) enum Mode { + /// Report differences without changing files. + Check, + /// Copy missing or changed files and remove extra files and empty directories. + Write, +} + +// Recursively syncs `root/source` into `root/target`. +pub(super) fn sync_directory( + root: &Path, + source: &Path, + target: &Path, + mode: Mode, + discrepancies: &mut Vec, +) -> anyhow::Result<()> { + let source_root = root.join(source); + let target_root = root.join(target); + let source_files = collect_files(&source_root).with_context(|| { + format!( + "could not read source-of-truth directory `{}`", + source.display() + ) + })?; + let target_files = if target_root.try_exists()? { + collect_files(&target_root) + .with_context(|| format!("could not read generated directory `{}`", target.display()))? + } else { + BTreeSet::new() + }; + + for relative in source_files.difference(&target_files) { + let source_file = source.join(relative); + let target_file = target.join(relative); + match mode { + Mode::Check => discrepancies.push(format!( + "generated file `{}` is missing; `{}` is the source of truth", + target_file.display(), + source_file.display() + )), + Mode::Write => copy_file(root, &source_file, &target_file)?, + } + } + + let mut extra_files = target_files + .difference(&source_files) + .map(|relative| target.join(relative)) + .collect::>(); + let ignored = git_ignored_paths(root, &extra_files)?; + extra_files.retain(|target_file| !ignored.contains(target_file)); + + for target_file in extra_files { + let source_file = source.join(target_file.strip_prefix(target)?); + match mode { + Mode::Check => discrepancies.push(format!( + "generated file `{}` is extra; source-of-truth file `{}` does not exist", + target_file.display(), + source_file.display() + )), + Mode::Write => { + eprintln!( + "Removing extra generated file `{}`; `{}` is the source of truth.", + target_file.display(), + source.display() + ); + fs::remove_file(root.join(&target_file)).with_context(|| { + format!( + "could not remove extra generated file `{}`", + target_file.display() + ) + })?; + } + } + } + + for relative in source_files.intersection(&target_files) { + sync_file( + root, + &source.join(relative), + &target.join(relative), + mode, + discrepancies, + )?; + } + + if matches!(mode, Mode::Write) && target_root.try_exists()? { + remove_empty_directories(&target_root)?; + } + + Ok(()) +} + +pub(super) fn sync_file( + root: &Path, + source: &Path, + target: &Path, + mode: Mode, + discrepancies: &mut Vec, +) -> anyhow::Result<()> { + let source_path = root.join(source); + let target_path = root.join(target); + let source_contents = fs::read(&source_path) + .with_context(|| format!("could not read source-of-truth file `{}`", source.display()))?; + let target_contents = match fs::read(&target_path) { + Ok(contents) => Some(contents), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + Err(error) => { + return Err(error) + .with_context(|| format!("could not read generated file `{}`", target.display())); + } + }; + + if target_contents.as_deref() == Some(source_contents.as_slice()) { + return Ok(()); + } + + match mode { + Mode::Check => { + let problem = if target_contents.is_some() { + "differs from" + } else { + "is missing; expected a copy of" + }; + discrepancies.push(format!( + "generated file `{}` {problem} source-of-truth file `{}`", + target.display(), + source.display() + )); + Ok(()) + } + Mode::Write => copy_file(root, source, target), + } +} + +fn copy_file(root: &Path, source: &Path, target: &Path) -> anyhow::Result<()> { + let source_path = root.join(source); + let target_path = root.join(target); + if let Some(parent) = target_path.parent() { + fs::create_dir_all(parent) + .with_context(|| format!("could not create directory `{}`", parent.display()))?; + } + eprintln!( + "Copying source-of-truth file `{}` to generated file `{}`.", + source.display(), + target.display() + ); + fs::copy(&source_path, &target_path).with_context(|| { + format!( + "could not copy source-of-truth file `{}` to generated file `{}`", + source.display(), + target.display() + ) + })?; + Ok(()) +} + +/// Returns the subset of `paths` that git ignores. +fn git_ignored_paths(root: &Path, paths: &[PathBuf]) -> anyhow::Result> { + if paths.is_empty() { + return Ok(BTreeSet::new()); + } + + let mut input = Vec::new(); + for path in paths { + let path = path + .to_str() + .with_context(|| format!("path `{}` is not valid UTF-8", path.display()))?; + input.extend_from_slice(path.as_bytes()); + input.push(0); + } + + // The `-z` form is necessary because the default output quotes any path that + // holds a backslash, which every relative path does on Windows. + let mut child = Command::new("git") + .args(["check-ignore", "--stdin", "-z"]) + .current_dir(root) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .context("could not run `git check-ignore`")?; + child + .stdin + .take() + .expect("stdin is piped") + .write_all(&input) + .context("could not write to `git check-ignore`")?; + let output = child + .wait_with_output() + .context("could not read from `git check-ignore`")?; + // `git check-ignore` exits 1 when it matches nothing, which is not an error. + if !matches!(output.status.code(), Some(0 | 1)) { + bail!( + "`git check-ignore` failed: {}", + String::from_utf8_lossy(&output.stderr).trim() + ); + } + + let stdout = + String::from_utf8(output.stdout).context("`git check-ignore` wrote invalid UTF-8")?; + Ok(stdout + .split('\0') + .filter(|path| !path.is_empty()) + .map(PathBuf::from) + .collect()) +} + +fn collect_files(root: &Path) -> anyhow::Result> { + if !root.try_exists()? { + bail!("directory `{}` does not exist", root.display()); + } + + let mut files = BTreeSet::new(); + collect_files_recursive(root, root, &mut files)?; + Ok(files) +} + +fn collect_files_recursive( + root: &Path, + directory: &Path, + files: &mut BTreeSet, +) -> anyhow::Result<()> { + let entries = fs::read_dir(directory) + .with_context(|| format!("could not read directory `{}`", directory.display()))?; + for entry in entries { + let entry = entry?; + let file_type = entry.file_type()?; + let path = entry.path(); + if file_type.is_dir() { + collect_files_recursive(root, &path, files)?; + } else if file_type.is_file() { + files.insert(path.strip_prefix(root)?.to_owned()); + } else { + bail!("unsupported file entry `{}`", path.display()); + } + } + Ok(()) +} + +fn remove_empty_directories(root: &Path) -> anyhow::Result { + let mut empty = true; + for entry in fs::read_dir(root)? { + let entry = entry?; + if entry.file_type()?.is_dir() { + if !remove_empty_directories(&entry.path())? { + empty = false; + } + } else { + empty = false; + } + } + + if empty { + fs::remove_dir(root)?; + } + Ok(empty) +}