diff --git a/.agents/skills/branches-and-pull-requests/SKILL.md b/.agents/skills/branches-and-pull-requests/SKILL.md index c5f9c48..19f0234 100644 --- a/.agents/skills/branches-and-pull-requests/SKILL.md +++ b/.agents/skills/branches-and-pull-requests/SKILL.md @@ -31,7 +31,7 @@ Changed files add labels too: `.github/**`, `Dockerfile` or `docker-compose.yml` 2. Write commit messages as a sentence about the change, in the imperative: "Validate the star rating on update". 3. Open the pull request and fill in `.github/pull_request_template.md`: a two or three sentence summary, the linked issue (`Part of` or `Closes LeanMeanCleanApps/.github#`), the type of change, and whether the shared layers are touched. 4. If shared layers, skills or repository setup changed, say so; the same change has to go to all five templates (`family-sync`). -5. Wait for every required check (`ci-pipeline`). Fix failures with new commits; don't force-push over review comments. +5. Wait for every required check (`ci-pipeline`). The pipeline only runs the jobs the change needs, and a job it skipped counts as passed. Fix failures with new commits; don't force-push over review comments. ## Don't diff --git a/.agents/skills/ci-pipeline/SKILL.md b/.agents/skills/ci-pipeline/SKILL.md index e7f01de..1b58f16 100644 --- a/.agents/skills/ci-pipeline/SKILL.md +++ b/.agents/skills/ci-pipeline/SKILL.md @@ -1,6 +1,6 @@ --- name: ci-pipeline -description: The Build Pipeline workflow - its jobs, the six required checks, the Summary comment, the monthly schedules, and how to fix a failing check without weakening it. Use when a check fails, when changing .github/workflows, or when explaining what CI does. +description: The Build Pipeline workflow - its jobs, the six required checks, which of them a change runs, the Summary comment, the monthly schedules, and how to fix a failing check without weakening it. Use when a check fails, when changing .github/workflows, or when explaining what CI does. metadata: scope: repository --- @@ -22,6 +22,16 @@ One workflow, `.github/workflows/build-pipeline.yml`, runs on every pull request After those, Release Check and Publish only run on the monthly release (`releases`). +A first job, Changes, sorts the files a pull request or push touched with `dorny/paths-filter`, and each job runs only when the change needs it: + +| A change that touches | Runs | +| --- | --- | +| Anything not listed below: `src/`, `tests/`, the build files, `Dockerfile`, `.template.config/`, `.github/workflows/`, `.github/actions/` | Everything | +| Only package content: `.agents/`, `AGENTS.md`, `CLAUDE.md`, `template/`, `docs/`, `NUGET.md`, `LICENSE.md`, `icon.png` | Build packs the template, Test verifies it, and Static Analysis | +| Only repository documents: `README.md`, the community files, the issue forms and the settings files in `.github/` | Static Analysis | + +The Summary always runs, and shows a job the change didn't need as not run. A skipped job counts as passed for its required check. Scheduled and manual runs run everything. Static Analysis scans the workflows and the C# on every run, because the code scanning rule on `main` expects CodeQL results for both and fails a pull request that skipped either. The two lists in the Changes job name what's safe to skip, so a file nobody listed counts as code. + Actions from GitHub (`actions/*` and `github/*`) are referenced by their major version tag. Actions from anyone else are pinned to a commit SHA with the version in a comment beside it, because the CodeQL scan of the workflows reports an unpinned third-party action. Dependabot keeps both up to date. A copy made with GitHub's "Use this template" gets this workflow with no secrets or setup. Outside the LeanMeanCleanApps organisation it runs only the format check, build and tests: Static Analysis, Dependency Review, Container Scan, the template's pack and verify steps, Release Check and Publish all check `github.repository_owner` and skip, and the Summary shows them as not run. Skipped jobs count as passed for required checks, so a private copy goes green without Advanced Security. A solution made with `dotnet new` gets the much smaller `template/ci.yml` as `.github/workflows/ci.yml` instead. `ci-for-your-solution` covers both. Keep any new job that needs Advanced Security, a secret or the template folders behind the same owner check. @@ -31,13 +41,14 @@ A copy made with GitHub's "Use this template" gets this workflow with no secrets 1. Read the Summary comment first; it names the unhappy check and links to its details. 2. Reproduce locally where you can (every command finds the `.slnx` in the root on its own): `dotnet format --verify-no-changes`, `dotnet build`, `dotnet test`, the coverage command in `coverage`, `docker build . --target run`. 3. Fix the cause in the code. For security findings, see `security-findings`. -4. Changing the workflow itself: keep each tool as an off-the-shelf action (`.github/actions/pipeline-report` is the only one of our own), keep the job names (they're the required check names), and keep everything working in someone else's copy of the template with no secrets or setup. +4. Changing the workflow itself: keep each tool as an off-the-shelf action (`.github/actions/pipeline-report` is the only one of our own), keep the job names (they're the required check names), and keep everything working in someone else's copy of the template with no secrets or setup. A new job needs `changes` in its `needs` and a condition on `needs.changes.outputs.code` or `package`, written as `!= 'false'` so an empty output means run. ## Don't - Skip, disable or mark a test as skipped to get green. - Lower `COVERAGE_THRESHOLD`, raise `TEMPLATE_MAX_SIZE`, or relax a severity to pass. - Rename a job without updating the repository's required checks. +- Add a path to the lists in the Changes job to get a failing job skipped. A path only goes there when nothing the skipped jobs check can read it. - Add a step that needs an account, a paid service or a secret to pass on a fresh copy. - Push an empty commit to re-run CI. Re-run the job from the Actions page. diff --git a/.github/actions/pipeline-report/report.py b/.github/actions/pipeline-report/report.py index 8e6cec2..3fad6d0 100644 --- a/.github/actions/pipeline-report/report.py +++ b/.github/actions/pipeline-report/report.py @@ -12,7 +12,8 @@ Reads every stage's result from the NEEDS environment variable (toJSON(needs)), the same test results, and the open code scanning alerts. Writes one table to the run summary and, on a pull request, keeps a single comment up to date with it. - Exits non-zero if any stage blocks the merge. + Exits non-zero if any stage blocks the merge. A stage the Changes job found the + change doesn't need shows as not run, and doesn't block. """ from __future__ import annotations @@ -194,10 +195,14 @@ def blocks(self) -> bool: } +NOT_NEEDED = "not needed for this change" + + def verdict(stages: list[Stage], pull_request: bool) -> str: blockers = [s for s in stages if s.blocks] if not blockers: - return "✅ **Ready to merge.** Every stage passed." if pull_request else "✅ **Pipeline passed.** Every stage passed." + passed = "Every stage this change needs passed." if any(s.headline == NOT_NEEDED for s in stages) else "Every stage passed." + return f"✅ **Ready to merge.** {passed}" if pull_request else f"✅ **Pipeline passed.** {passed}" first = blockers[0] reason = (first.reason or first.headline) if first.result == "failure" else f"the stage was {first.result}" more = f" (and {len(blockers) - 1} more)" if len(blockers) > 1 else "" @@ -248,13 +253,15 @@ def build_headline(needs: dict) -> str: return SEPARATOR.join(parts) or "built" -def test_headline(result: str, tests: TestResults | None, tests_outcome: str = "", full: bool = True) -> str: +def test_headline(result: str, tests: TestResults | None, tests_outcome: str = "", full: bool = True, code: bool = True) -> str: parts = [] if tests is not None: parts.append(f"{tests.passed} passed{SEPARATOR}{tests.failed} failed{SEPARATOR}{tests.skipped} skipped") + elif not code: + parts.append("no code changed, so only the template was checked") if result == "success" and full: parts.append("template installs, builds and passes its tests") - elif result == "failure" and tests_outcome == "passed": + elif result == "failure" and (tests_outcome == "passed" or not code): parts.append("the generated template failed to build or test") return SEPARATOR.join(parts) or "no test results" @@ -320,6 +327,24 @@ def outside_stage(name: str) -> Stage: return Stage(name, "n/a", NOT_RUN_OUTSIDE) +def needed(needs: dict, flag: str) -> bool: + """Whether the change needs the part of the pipeline behind a Changes output: code or package. + + Only an explicit 'false' says it doesn't. Scheduled and manual runs, copies outside our + organisation and a failed Changes job leave the outputs empty, and then everything is needed. + """ + return needs.get("changes", {}).get("outputs", {}).get(flag) != "false" + + +def unneeded_stages(needs: dict) -> set[str]: + names: set[str] = set() + if not needed(needs, "package"): + names |= {"Build", "Test"} + if not needed(needs, "code"): + names |= {"Coverage", "Dependency Review", "Container Scan"} + return names + + def count_ignored(path: str) -> int: if not os.path.isfile(path): return 0 @@ -503,12 +528,13 @@ def job_link(*names: str) -> str: test = stage_result(needs, "test") full = full_pipeline() + code = needed(needs, "code") stages = [ Stage("Build", stage_result(needs, "build"), build_headline(needs), job_link("Build")), Stage( "Test", test, - test_headline(test, tests, needs.get("test", {}).get("outputs", {}).get("tests", ""), full), + test_headline(test, tests, needs.get("test", {}).get("outputs", {}).get("tests", ""), full, code), job_link("Test"), f"{tests.failed} test{'s' if tests.failed != 1 else ''} failed" if tests and tests.failed else "", ), @@ -536,6 +562,13 @@ def job_link(*names: str) -> str: ] if not full: stages = [outside_stage(s.name) if s.name in ("Static Analysis", "Dependency Review", "Container Scan") else s for s in stages] + # A stage the change doesn't need shows as not run. One that ran anyway, or was cancelled, keeps its + # result. Coverage has no job of its own: without code to test there's no report to measure. + unneeded = unneeded_stages(needs) + stages = [Stage(s.name, "n/a", NOT_NEEDED) if s.name in unneeded and (s.result == "skipped" or s.name == "Coverage") else s for s in stages] + changes = stage_result(needs, "changes") if "changes" in needs else "success" + if changes not in ("success", "skipped"): + stages.insert(0, Stage("Changes", changes, "couldn't work out which files changed, so nothing else ran", job_link("Changes"))) body = render_summary(stages, pull_request, run_url, sha) write_step_summary(body.replace(MARKER + "\n", "")) diff --git a/.github/actions/pipeline-report/test_report.py b/.github/actions/pipeline-report/test_report.py index 9bea17a..63f9e44 100644 --- a/.github/actions/pipeline-report/test_report.py +++ b/.github/actions/pipeline-report/test_report.py @@ -124,6 +124,11 @@ def test_skipped_stage_blocks(self): stages = [report.Stage("Container Scan", "skipped", "didn't run")] self.assertIn("the stage was skipped", report.verdict(stages, True)) + def test_stages_a_change_does_not_need_are_named_in_the_verdict(self): + stages = [report.Stage("Static Analysis", "success", "ok"), report.Stage("Build", "n/a", report.NOT_NEEDED)] + self.assertEqual(report.verdict(stages, True), "✅ **Ready to merge.** Every stage this change needs passed.") + self.assertEqual(report.verdict(stages, False), "✅ **Pipeline passed.** Every stage this change needs passed.") + def test_summary_table_has_marker_rows_and_links(self): stages = [report.Stage("Build", "success", "version `1.0`", "https://example.com/job")] text = report.render_summary(stages, True, "https://example.com/run", "abcdef1234") @@ -158,6 +163,20 @@ def test_test_headline_blames_the_template_only_when_the_tests_passed(self): self.assertNotIn("template", report.test_headline("failure", tests, "failed")) self.assertIn("template installs", report.test_headline("success", tests)) + def test_test_headline_without_code_changes_reports_the_template_only(self): + self.assertEqual(report.test_headline("success", None, code=False), "no code changed, so only the template was checked · template installs, builds and passes its tests") + self.assertIn("the generated template failed to build or test", report.test_headline("failure", None, code=False)) + + def test_only_an_explicit_false_makes_a_stage_unneeded(self): + self.assertEqual(report.unneeded_stages({}), set()) + self.assertEqual(report.unneeded_stages({"changes": {"result": "success", "outputs": {}}}), set()) + self.assertEqual(report.unneeded_stages({"changes": {"outputs": {"code": "true", "package": "true"}}}), set()) + self.assertEqual(report.unneeded_stages({"changes": {"outputs": {"code": "false", "package": "true"}}}), {"Coverage", "Dependency Review", "Container Scan"}) + self.assertEqual( + report.unneeded_stages({"changes": {"outputs": {"code": "false", "package": "false"}}}), + {"Build", "Test", "Coverage", "Dependency Review", "Container Scan"}, + ) + def test_coverage_row_has_its_own_result(self): low, full = report.Coverage(75, 3, 4), report.Coverage(100, 10, 10) self.assertEqual(report.coverage_result("failure", full, 95), "success") @@ -323,6 +342,102 @@ def upsert_comment(self, number, body): self.assertNotIn(report.MARKER, summary) self.assertIn("| Dependency Review | ⚪ Not run |", summary) + def summary(self, needs, results=False, event="pull_request"): + """Runs the summary command and returns its exit code and the table it wrote.""" + + class FakeGitHub(report.GitHub): + def jobs(self, run_id): + return {} + + def alerts(self, tool, ref): + return [] + + def upsert_comment(self, number, body): + pass + + with tempfile.TemporaryDirectory() as directory: + if results: + write_results(directory, exit_code="0", coverage=COVERAGE.replace('sequenceCoverage="75"', 'sequenceCoverage="100"')) + environment = { + "NEEDS": json.dumps(needs), + "GITHUB_EVENT_NAME": event, + "PR_NUMBER": "7", + "GITHUB_REF": "refs/heads/main", + "GITHUB_REPOSITORY": "owner/repo", + "GITHUB_RUN_ID": "99", + "GITHUB_STEP_SUMMARY": os.path.join(directory, "summary.md"), + } + with mock.patch.dict(os.environ, environment), mock.patch.object(report, "GitHub", FakeGitHub): + code = report.command_summary(directory) + with open(os.path.join(directory, "summary.md"), encoding="utf-8") as handle: + return code, handle.read() + + def test_summary_command_passes_when_only_repository_documents_changed(self): + needs = {key: {"result": "skipped", "outputs": {}} for key in ("build", "test", "dependencies", "scan")} + needs["changes"] = {"result": "success", "outputs": {"code": "false", "package": "false"}} + needs["analysis"] = {"result": "success", "outputs": {}} + + code, summary = self.summary(needs) + + self.assertEqual(code, 0) + self.assertIn("**Ready to merge.** Every stage this change needs passed.", summary) + for stage in ("Build", "Test", "Coverage", "Dependency Review", "Container Scan"): + self.assertIn(f"| {stage} | ⚪ Not run | Not needed for this change |", summary) + self.assertIn("🟢 Passed | No open CodeQL alerts |", summary) + self.assertNotIn("Changes", summary) + + def test_summary_command_passes_when_only_package_content_changed(self): + needs = {key: {"result": "success", "outputs": {}} for key in ("build", "test", "analysis")} + needs.update({key: {"result": "skipped", "outputs": {}} for key in ("dependencies", "scan")}) + needs["changes"] = {"result": "success", "outputs": {"code": "false", "package": "true"}} + + code, summary = self.summary(needs) + + self.assertEqual(code, 0) + self.assertIn("Every stage this change needs passed.", summary) + self.assertIn("🟢 Passed | No code changed, so only the template was checked · Template installs, builds and passes its tests |", summary) + for stage in ("Coverage", "Dependency Review", "Container Scan"): + self.assertIn(f"| {stage} | ⚪ Not run | Not needed for this change |", summary) + + def test_summary_command_still_blocks_on_a_skipped_stage_the_change_needs(self): + needs = {key: {"result": "success", "outputs": {}} for key in ("build", "test", "analysis", "dependencies")} + needs["scan"] = {"result": "skipped", "outputs": {}} + needs["changes"] = {"result": "success", "outputs": {"code": "true", "package": "true"}} + + code, summary = self.summary(needs, results=True) + + self.assertEqual(code, 1) + self.assertIn("**Blocked by Container Scan**: the stage was skipped.", summary) + + def test_summary_command_blocks_when_a_needed_stage_fails_beside_unneeded_ones(self): + needs = {key: {"result": "skipped", "outputs": {}} for key in ("dependencies", "scan")} + needs.update({"build": {"result": "success", "outputs": {}}, "test": {"result": "failure", "outputs": {}}, "analysis": {"result": "skipped", "outputs": {}}}) + needs["changes"] = {"result": "success", "outputs": {"code": "false", "package": "true"}} + + code, summary = self.summary(needs) + + self.assertEqual(code, 1) + self.assertIn("**Blocked by Test** (and 1 more): no code changed, so only the template was checked · the generated template failed to build or test.", summary) + + def test_summary_command_blocks_when_the_changes_job_fails(self): + needs = {key: {"result": "skipped", "outputs": {}} for key in ("build", "test", "analysis", "dependencies", "scan")} + needs["changes"] = {"result": "failure", "outputs": {}} + + code, summary = self.summary(needs) + + self.assertEqual(code, 1) + self.assertIn("**Blocked by Changes** (and 6 more): couldn't work out which files changed, so nothing else ran.", summary) + + def test_summary_command_reports_every_stage_on_a_scheduled_run(self): + needs = {key: {"result": "success", "outputs": {}} for key in ("changes", "build", "test", "analysis", "scan")} + needs["dependencies"] = {"result": "skipped", "outputs": {}} + + code, summary = self.summary(needs, results=True, event="schedule") + + self.assertEqual(code, 0) + self.assertIn("**Pipeline passed.** Every stage passed.", summary) + self.assertNotIn("Not needed", summary) + if __name__ == "__main__": unittest.main() diff --git a/.github/workflows/build-pipeline.yml b/.github/workflows/build-pipeline.yml index 87ed58c..da229b7 100644 --- a/.github/workflows/build-pipeline.yml +++ b/.github/workflows/build-pipeline.yml @@ -39,14 +39,75 @@ concurrency: # format check, build and tests. The scans need GitHub Advanced Security on a private repository, # and packing, verifying and publishing the template only matter here. Skipped jobs count as passed # for required checks, so a copy goes green with no setup. See the ci-for-your-solution skill. +# +# Here, a pull request or push runs only what its files need. Changes sorts them into three groups: +# - Repository documents and GitHub settings, which nothing in the pipeline reads: only Static +# Analysis and the Summary run. +# - Package content, which ships in the template but can't change what compiles: the template is +# also packed and verified. +# - Everything else is code, and everything runs. +# Scheduled and manual runs always run everything. env: COVERAGE_THRESHOLD: 95 TEMPLATE_MAX_SIZE: 1048576 jobs: + changes: + name: Changes + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: read + + outputs: + code: ${{ steps.filter.outputs.code }} + package: ${{ steps.filter.outputs.package }} + + steps: + - name: Checkout + id: checkout + uses: actions/checkout@v7 + + - name: Filter + id: filter + # Skipped for a scheduled or manual run, and in a copy outside the organisation. That leaves + # both outputs empty, and every job reads anything but 'false' as "run". + if: ${{ github.repository_owner == 'LeanMeanCleanApps' && (github.event_name == 'pull_request' || github.event_name == 'push') }} + uses: dorny/paths-filter@ceb8a2b8f2d89434be7ff52d3de7ec3738c5cc9d # v4.0.3 + with: + # A file counts when it matches '**' and none of the '!' lines under it. + predicate-quantifier: some-with-excludes + filters: | + # true when anything but a repository document changed + package: &package + - '**' + - '!README.md' + - '!ACCESSIBILITY.md' + - '!CODE_OF_CONDUCT.md' + - '!CONTRIBUTING.md' + - '!SECURITY.md' + - '!SUPPORT.md' + - '!.github/CODEOWNERS' + - '!.github/ISSUE_TEMPLATE/**' + - '!.github/*.md' + - '!.github/*.yml' + # true when anything but a repository document or package content changed + code: + - *package + - '!.agents/**' + - '!AGENTS.md' + - '!CLAUDE.md' + - '!LICENSE.md' + - '!NUGET.md' + - '!docs/**' + - '!icon.png' + - '!template/**' + build: name: Build runs-on: ubuntu-latest + needs: changes + if: ${{ needs.changes.outputs.package != 'false' }} permissions: contents: read @@ -93,10 +154,12 @@ jobs: - name: Format id: format + if: ${{ needs.changes.outputs.code != 'false' }} run: dotnet format --verify-no-changes --verbosity diagnostic - name: Build id: build + if: ${{ needs.changes.outputs.code != 'false' }} run: | docker build . \ --target run \ @@ -129,11 +192,12 @@ jobs: - name: Test Pipeline Report id: test-report + if: ${{ needs.changes.outputs.code != 'false' }} run: python3 -m unittest discover --start-directory .github/actions/pipeline-report --verbose - name: Upload Image id: upload-image - if: ${{ github.repository_owner == 'LeanMeanCleanApps' }} + if: ${{ github.repository_owner == 'LeanMeanCleanApps' && needs.changes.outputs.code != 'false' }} uses: actions/upload-artifact@v7 with: name: image @@ -152,7 +216,8 @@ jobs: test: name: Test runs-on: ubuntu-latest - needs: build + needs: [changes, build] + if: ${{ needs.changes.outputs.package != 'false' }} permissions: contents: read @@ -166,6 +231,7 @@ jobs: - name: Test id: test + if: ${{ needs.changes.outputs.code != 'false' }} run: | docker build . \ --target results \ @@ -179,6 +245,7 @@ jobs: - name: Report id: report + if: ${{ needs.changes.outputs.code != 'false' }} uses: ./.github/actions/pipeline-report with: command: test @@ -187,7 +254,7 @@ jobs: - name: Upload Results id: upload-results - if: ${{ !cancelled() }} + if: ${{ !cancelled() && needs.changes.outputs.code != 'false' }} uses: actions/upload-artifact@v7 with: name: test-results @@ -269,8 +336,10 @@ jobs: analysis: name: Static Analysis runs-on: ubuntu-latest - needs: test - if: ${{ github.repository_owner == 'LeanMeanCleanApps' }} + needs: [changes, test] + # Always runs, even when Test was skipped. The code scanning rule on main expects CodeQL results + # for both languages on every pull request, and won't pass one that skipped either scan. + if: ${{ !cancelled() && !failure() && github.repository_owner == 'LeanMeanCleanApps' }} permissions: actions: read contents: read @@ -303,8 +372,8 @@ jobs: dependencies: name: Dependency Review runs-on: ubuntu-latest - needs: test - if: ${{ github.event_name == 'pull_request' && github.repository_owner == 'LeanMeanCleanApps' }} + needs: [changes, test] + if: ${{ github.event_name == 'pull_request' && github.repository_owner == 'LeanMeanCleanApps' && needs.changes.outputs.code != 'false' }} permissions: contents: read pull-requests: write @@ -326,8 +395,8 @@ jobs: scan: name: Container Scan runs-on: ubuntu-latest - needs: [build, test] - if: ${{ github.repository_owner == 'LeanMeanCleanApps' }} + needs: [changes, build, test] + if: ${{ github.repository_owner == 'LeanMeanCleanApps' && needs.changes.outputs.code != 'false' }} permissions: contents: read security-events: write @@ -459,7 +528,7 @@ jobs: summary: name: Summary runs-on: ubuntu-latest - needs: [build, test, analysis, dependencies, scan] + needs: [changes, build, test, analysis, dependencies, scan] # Report on failures too, but not when a newer push cancelled this run: its stale result would # overwrite the comment the newer run is about to write. if: ${{ !cancelled() }} @@ -481,6 +550,7 @@ jobs: - name: Download Results id: download + if: ${{ needs.changes.outputs.code != 'false' }} continue-on-error: true uses: actions/download-artifact@v8 with: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 25c0e07..92e3006 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -68,7 +68,7 @@ Agents are welcome here, as long as a person stays in charge. [AGENTS.md](AGENTS 1. Open the pull request against `main` and fill in the template. 1. Link the issue it resolves, for example `Closes #123`. -1. Every check must pass: Build, Test, Static Analysis, Dependency Review, Container Scan and Summary. The Summary comment on your pull request says which one is unhappy and links to the details. +1. Every check must pass: Build, Test, Static Analysis, Dependency Review, Container Scan and Summary. The Summary comment on your pull request says which one is unhappy and links to the details. The pipeline only runs the checks your change needs, so a fix to this page skips the build and the tests. A check it skipped shows as not run in the Summary and counts as passed. 1. The maintainer reviews every pull request and squash-merges it once it's green. That's not a lack of trust, it's just how the lights stay on. If a review takes a while, a polite nudge is fine. [Governance](https://github.com/LeanMeanCleanApps/.github/blob/main/GOVERNANCE.md) says how decisions get made, and what's in scope. ## Getting help