From ca2efdaf184e3dc73b91ef3f890de51955581424 Mon Sep 17 00:00:00 2001 From: lingjhf Date: Tue, 6 Oct 2026 18:11:54 +0800 Subject: [PATCH] perf(ci): tier PR builds and skip routine release packaging --- .gitea/BUILD_AND_RELEASE.md | 18 +++++-- .gitea/CI_PERFORMANCE.md | 18 ++++++- .gitea/workflows/ci.yml | 52 +++++++++++++++++-- tool/gitea/ci_scope.py | 70 ++++++++++++++++++++++++++ tool/gitea/test_ci_scope.py | 99 +++++++++++++++++++++++++++++++++++++ 5 files changed, 246 insertions(+), 11 deletions(-) create mode 100644 tool/gitea/ci_scope.py create mode 100644 tool/gitea/test_ci_scope.py diff --git a/.gitea/BUILD_AND_RELEASE.md b/.gitea/BUILD_AND_RELEASE.md index 7ecb158..5c2ba00 100644 --- a/.gitea/BUILD_AND_RELEASE.md +++ b/.gitea/BUILD_AND_RELEASE.md @@ -13,13 +13,21 @@ shipping a production signed Android release. The Windows ZIP includes the whole Flutter Release directory and passes the PE dependency audit. Processing workers and optional models are separate; these four repositories contain no worker bundle. -PR/main CI analyzes and tests the app, builds both platforms, and uploads -cutdex-release-packages including SHA256SUMS and a release manifest. It also saves +CI always analyzes and tests the app. Ordinary code PRs also compile both +platforms, but skip Windows packaging, artifact uploads and final assembly. +Documentation-only PRs skip platform compilation as well. PR changes to CI, +tooling, native platform configuration, package dependencies or app update code +run the complete pipeline. `ci_scope.py` compares the PR base and head using Git +history, including deleted files; a failed comparison fails code checks. +Main pushes and manual CI runs always execute the complete pipeline and upload +cutdex-release-packages including SHA256SUMS and a release manifest. They also save cutdex-release-metadata containing only the manifest, checksums, Windows update index and audit report. Platform, complete and metadata artifacts retain 30 days. Protect main -with `Gitea CI / Gitea CI passed (pull_request)`. +with `Gitea CI / Gitea CI passed (pull_request)`. This required check validates +every expected job and permits skipped jobs only when the selected scope +explicitly excludes them; failures, cancellations and unexpected skips fail it. -Windows compilation and packaging are separate jobs. Compilation saves the +Windows compilation and packaging are separate jobs. Full-pipeline compilation saves the unpackaged Release directory as `cutdex-windows-app` for 30 days; packaging downloads it and runs the existing PE audit and Velopack tools. Rerunning a failed packaging job reuses this app without recompiling. Assembly and Release jobs @@ -62,7 +70,7 @@ operator attention. Published Releases are never overwritten. The built-in GITEA_TOKEN handles release writes and Actions artifact reads; no separate release-write PAT is required. Do not commit credentials or keystores. -PR/main CI produces Actions artifacts without creating Releases. If a tag is pushed +Full-pipeline CI produces Actions artifacts without creating Releases. If a tag is pushed before main CI succeeds, release preparation fails without creating a draft; retry the Release workflow once CI has finished. This design overlaps platform uploads, not main CI builds with Release uploads. There is no legacy whole-archive diff --git a/.gitea/CI_PERFORMANCE.md b/.gitea/CI_PERFORMANCE.md index 13ed7cb..84fa45e 100644 --- a/.gitea/CI_PERFORMANCE.md +++ b/.gitea/CI_PERFORMANCE.md @@ -1,6 +1,22 @@ # CI build performance -The workflow runs checks first, then Android and Windows compilation concurrently. +The workflow runs checks first, then Android and Windows compilation concurrently +when compilation is required. Ordinary code PRs stop after compilation and native +SDK validation; they skip artifact transfers, Windows packaging and assembly. +Documentation-only PRs run checks without compiling either platform. Changes to +CI, tooling, native platform configuration, dependencies and app update code +force the full pipeline. Main pushes and manual CI runs always use the full +pipeline, preserving the exact-commit artifacts needed by Release. + +Scope selection uses the complete PR base/head history in the quality checkout. +Other checkouts retain their default shallow fetch. Git comparisons include +deleted paths and disable rename detection, so moving a packaging file into docs +cannot hide its deletion. Unknown paths compile both platforms; empty PR diffs +run the full pipeline. Scope selection errors fail CI instead of skipping jobs. +The final required check requires success for selected jobs and `skipped` for +excluded jobs, and always requires successful code checks. + +In the full pipeline, Windows compilation saves `cutdex-windows-app`; an independent Windows job downloads that app, audits it and creates Velopack packages. Packaging needs neither Flutter dependencies nor another Windows compilation. The Android job diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index a4888b8..6a056a8 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -24,6 +24,9 @@ jobs: quality: name: Check code and tests runs-on: cutdex-windows-x64 + outputs: + build-app: ${{ steps.scope.outputs.build-app }} + package-app: ${{ steps.scope.outputs.package-app }} env: CUTDEX_GITEA_TOKEN: ${{ secrets.CUTDEX_GITEA_TOKEN }} steps: @@ -32,6 +35,16 @@ jobs: with: persist-credentials: false github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }} + fetch-depth: 0 + - name: Select compilation and packaging scope + id: scope + env: + CI_EVENT_NAME: ${{ gitea.event_name }} + CI_PR_BASE_SHA: ${{ gitea.event.pull_request.base.sha }} + CI_PR_HEAD_SHA: ${{ gitea.event.pull_request.head.sha }} + run: | + python tool/gitea/ci_scope.py + if ($LASTEXITCODE -ne 0) { throw 'CI scope selection failed.' } - name: Prepare Flutter environment uses: ./.gitea/actions/prepare-flutter with: @@ -51,6 +64,7 @@ jobs: android: name: Build Android APK needs: quality + if: ${{ needs.quality.outputs.build-app == 'true' }} runs-on: cutdex-windows-x64 env: CUTDEX_GITEA_TOKEN: ${{ secrets.CUTDEX_GITEA_TOKEN }} @@ -75,6 +89,7 @@ jobs: GITEA_ACTOR: lingjhf run: flutter build apk --release --flavor production --target-platform android-arm64,android-x64 - name: Upload Android CI artifact + if: ${{ needs.quality.outputs.package-app == 'true' }} uses: ./.gitea/actions/upload-artifact with: name: cutdex-android-build @@ -85,6 +100,7 @@ jobs: windows-build: name: Build Windows x64 app needs: quality + if: ${{ needs.quality.outputs.build-app == 'true' }} runs-on: cutdex-windows-x64 env: CUTDEX_GITEA_TOKEN: ${{ secrets.CUTDEX_GITEA_TOKEN }} @@ -108,6 +124,7 @@ jobs: python tool/windows/windows_updates.py verify-sdk if ($LASTEXITCODE -ne 0) { throw 'Windows native SDK version validation failed.' } - name: Save Windows app for independent packaging retries + if: ${{ needs.quality.outputs.package-app == 'true' }} uses: ./.gitea/actions/upload-artifact with: name: cutdex-windows-app @@ -123,7 +140,8 @@ jobs: windows: name: Audit and package Windows x64 - needs: windows-build + needs: [quality, windows-build] + if: ${{ needs.quality.outputs.package-app == 'true' }} runs-on: cutdex-windows-x64 steps: - name: Check out source @@ -154,7 +172,8 @@ jobs: build: name: Assemble and validate CI artifacts - needs: [android, windows] + needs: [quality, android, windows] + if: ${{ needs.quality.outputs.package-app == 'true' }} runs-on: cutdex-windows-x64 steps: - name: Check out source @@ -197,11 +216,34 @@ jobs: checks: name: Gitea CI passed if: always() - needs: build + needs: [quality, android, windows-build, windows, build] runs-on: cutdex-windows-x64 steps: - name: Verify CI result env: - RESULT: ${{ needs.build.result }} + QUALITY_RESULT: ${{ needs.quality.result }} + BUILD_APP: ${{ needs.quality.outputs.build-app }} + PACKAGE_APP: ${{ needs.quality.outputs.package-app }} + # The local runner omits results for jobs excluded by their condition. + # Required jobs still fail below if this becomes 'skipped'. + ANDROID_RESULT: ${{ needs.android.result || 'skipped' }} + WINDOWS_BUILD_RESULT: ${{ needs.windows-build.result || 'skipped' }} + WINDOWS_PACKAGE_RESULT: ${{ needs.windows.result || 'skipped' }} + ASSEMBLY_RESULT: ${{ needs.build.result || 'skipped' }} run: | - if ($env:RESULT -ne 'success') { throw "App build: $env:RESULT" } + if ($env:QUALITY_RESULT -ne 'success') { throw "Code checks: $env:QUALITY_RESULT" } + if ($env:BUILD_APP -notin @('true', 'false') -or $env:PACKAGE_APP -notin @('true', 'false')) { + throw 'Missing or invalid CI scope outputs.' + } + if ($env:PACKAGE_APP -eq 'true' -and $env:BUILD_APP -ne 'true') { throw 'Packaging requires compilation.' } + $compileResult = if ($env:BUILD_APP -eq 'true') { 'success' } else { 'skipped' } + $packageResult = if ($env:PACKAGE_APP -eq 'true') { 'success' } else { 'skipped' } + $jobs = @( + @{ Name = 'Android compilation'; Result = $env:ANDROID_RESULT; Expected = $compileResult }, + @{ Name = 'Windows compilation'; Result = $env:WINDOWS_BUILD_RESULT; Expected = $compileResult }, + @{ Name = 'Windows packaging'; Result = $env:WINDOWS_PACKAGE_RESULT; Expected = $packageResult }, + @{ Name = 'Artifact assembly'; Result = $env:ASSEMBLY_RESULT; Expected = $packageResult } + ) + foreach ($job in $jobs) { + if ($job.Result -ne $job.Expected) { throw "$($job.Name): $($job.Result), expected $($job.Expected)." } + } diff --git a/tool/gitea/ci_scope.py b/tool/gitea/ci_scope.py new file mode 100644 index 0000000..325099c --- /dev/null +++ b/tool/gitea/ci_scope.py @@ -0,0 +1,70 @@ +"""Select PR compilation and packaging scope from the complete Git change set.""" + +import os +from pathlib import Path, PurePosixPath +import re +import subprocess +import sys + + +def packaging_change(path): + path = path.lower() + return ( + path.startswith(('.gitea/', '.github/workflows/', '.github/actions/', + 'tool/', 'android/', 'windows/', + 'packages/cutdex_native/android/', + 'packages/cutdex_native/windows/', + 'lib/integrations/app_update', + 'lib/features/settings/update')) + or PurePosixPath(path).name in {'pubspec.yaml', 'pubspec.lock', '.metadata'} + or (path.startswith('test/') and 'update' in path) + ) + + +def documentation_change(path): + path = PurePosixPath(path.lower()) + return ( + str(path).startswith(('docs/', '.github/issue_template/')) + or str(path) == '.github/pull_request_template.md' + or (len(path.parts) == 1 and path.suffix in {'.md', '.rst'}) + or (len(path.parts) == 1 and path.name in {'license', 'notice'}) + or (str(path).startswith('packages/') and path.name == 'readme.md') + ) + + +def select_scope(event, paths): + paths = list(paths) + if event != 'pull_request' or not paths or any(packaging_change(path) for path in paths): + return {'build-app': True, 'package-app': True} + return {'build-app': not all(documentation_change(path) for path in paths), + 'package-app': False} + + +def changed_paths(base, head): + for sha in (base, head): + if not re.fullmatch(r'[0-9a-f]{40}', sha): + raise ValueError('PR base and head must be full Git commit SHAs') + result = subprocess.run( + ['git', 'diff', '--name-only', '--no-renames', '-z', f'{base}...{head}'], + check=True, capture_output=True, + ) + return result.stdout.decode('utf-8', errors='surrogateescape').rstrip('\0').split('\0') if result.stdout else [] + + +def main(): + event = os.environ['CI_EVENT_NAME'] + paths = changed_paths(os.environ.get('CI_PR_BASE_SHA', ''), + os.environ.get('CI_PR_HEAD_SHA', '')) if event == 'pull_request' else [] + scope = select_scope(event, paths) + with Path(os.environ['GITHUB_OUTPUT']).open('a', encoding='utf-8') as stream: + for name, enabled in scope.items(): + stream.write(f'{name}={str(enabled).lower()}\n') + print(f"CI scope: compile={scope['build-app']}, package={scope['package-app']}") + + +if __name__ == '__main__': + try: + main() + except (KeyError, ValueError, subprocess.CalledProcessError) as error: + print(f'Cannot determine CI scope: {error}', file=sys.stderr) + sys.exit(1) diff --git a/tool/gitea/test_ci_scope.py b/tool/gitea/test_ci_scope.py new file mode 100644 index 0000000..c008f0a --- /dev/null +++ b/tool/gitea/test_ci_scope.py @@ -0,0 +1,99 @@ +import os +from pathlib import Path +import subprocess +import tempfile +import unittest +from unittest.mock import patch + +from ci_scope import changed_paths, main, select_scope + + +class ScopeTests(unittest.TestCase): + def test_main_and_manual_runs_always_produce_release_artifacts(self): + for event in ('push', 'workflow_dispatch'): + with self.subTest(event=event): + self.assertEqual(select_scope(event, ['README.md']), + {'build-app': True, 'package-app': True}) + + def test_regular_code_pr_compiles_both_platforms_without_packaging(self): + self.assertEqual(select_scope('pull_request', ['lib/main.dart', 'test/app_test.dart']), + {'build-app': True, 'package-app': False}) + + def test_documentation_only_pr_skips_platform_jobs(self): + self.assertEqual(select_scope('pull_request', ['README.md', 'docs/setup.md', + 'packages/cutdex_ui/README.md', '.github/PULL_REQUEST_TEMPLATE.md']), + {'build-app': False, 'package-app': False}) + + def test_documentation_does_not_hide_code_changes(self): + self.assertEqual(select_scope('pull_request', ['README.md', 'lib/main.dart']), + {'build-app': True, 'package-app': False}) + + def test_packaging_changes_force_full_validation(self): + for path in ('.gitea/workflows/ci.yml', '.gitea/actions/upload-artifact/action.yml', + 'tool/gitea/ci_scope.py', 'tool/windows/windows_updates.py', + 'windows/runner/main.cpp.in', 'android/app/build.gradle.kts', + 'pubspec.yaml', 'pubspec.lock', 'packages/cutdex_ui/pubspec.yaml', + 'packages/cutdex_native/windows/CMakeLists.txt', + 'lib/integrations/app_update_bridge.dart', + 'lib/features/settings/update_controller.dart', 'test/app_updates_test.dart'): + with self.subTest(path=path): + self.assertEqual(select_scope('pull_request', ['README.md', path]), + {'build-app': True, 'package-app': True}) + + def test_arbitrary_runtime_markdown_is_not_treated_as_documentation(self): + self.assertTrue(select_scope('pull_request', ['assets/help.md'])['build-app']) + + def test_empty_change_set_is_conservative(self): + self.assertEqual(select_scope('pull_request', []), + {'build-app': True, 'package-app': True}) + + def test_invalid_or_missing_shas_are_rejected(self): + for base, head in (('', 'a' * 40), ('--help', 'b' * 40), ('a' * 40, 'bad')): + with self.subTest(base=base, head=head), self.assertRaises(ValueError): + changed_paths(base, head) + + def test_failed_git_comparison_cannot_skip_builds(self): + with patch('ci_scope.subprocess.run', side_effect=subprocess.CalledProcessError(1, ['git'])): + with self.assertRaises(subprocess.CalledProcessError): + changed_paths('a' * 40, 'b' * 40) + + def test_outputs_propagate_as_action_boolean_strings(self): + with tempfile.TemporaryDirectory() as directory: + output = Path(directory) / 'output' + with patch.dict(os.environ, {'CI_EVENT_NAME': 'pull_request', + 'CI_PR_BASE_SHA': 'a' * 40, 'CI_PR_HEAD_SHA': 'b' * 40, + 'GITHUB_OUTPUT': str(output)}), patch('ci_scope.changed_paths', return_value=['lib/main.dart']): + main() + self.assertEqual(output.read_text(), 'build-app=true\npackage-app=false\n') + + def test_deleted_build_file_is_detected_when_renamed_into_docs(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + def git(*args): + return subprocess.check_output(['git', '-C', str(root), *args], text=True).strip() + git('init', '--quiet') + git('config', 'user.name', 'CI scope test') + git('config', 'user.email', 'ci-scope@example.invalid') + (root / 'tool').mkdir() + (root / 'tool/package.py').write_text('packaging input\n') + git('add', '.') + git('commit', '--quiet', '-m', 'base') + base = git('rev-parse', 'HEAD') + (root / 'docs').mkdir() + (root / 'tool/package.py').rename(root / 'docs/package.md') + git('add', '-A') + git('commit', '--quiet', '-m', 'move build file') + head = git('rev-parse', 'HEAD') + original = os.getcwd() + try: + os.chdir(root) + paths = changed_paths(base, head) + finally: + os.chdir(original) + self.assertIn('tool/package.py', paths) + self.assertEqual(select_scope('pull_request', paths), + {'build-app': True, 'package-app': True}) + + +if __name__ == '__main__': + unittest.main() -- 2.54.0