diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md index a6d2c14..2521bf7 100644 --- a/.claude/CLAUDE.md +++ b/.claude/CLAUDE.md @@ -77,6 +77,7 @@ long form of everything below), `doc/api-surface.md`, `doc/verification.md` (dev - **Feedback package**: separate (PLAN.md D4), a workspace member, lock-step version, hosted constraint `>= ` (never exact, never a path or an override); the core must never mention it; its own Pigeon bridge; native pins are literals compared by `test/feedback_package_drift_test.dart`; it adds no Android provider; publish only through `scripts/publish_feedback.sh`, core first. + Releases: only `.github/workflows/release.yml` publishes (tag `v`, OIDC, `environment: pub.dev`, after its gate; guarded in `test/native_versions_test.dart`); `workflow_dispatch` there is a dry run (pub.dev refuses non-tag publishing). - **Device harness** (`scripts/device/`, not in CI): its guards are on by default and must stay so; a new check goes through `Run.guard` / `Run.expect`, a new parser in `scripts/device/core/` with a test that shows it failing (`test/device_harness_test.dart`). A NOT POSSIBLE scenario exits 2. - **Docs**: a doc claim about code (a name, default, limit, command, path) is checked against the code; `README.md`, `CHANGELOG.md` (the newest entry is diff --git a/.github/CI.md b/.github/CI.md index a0d5ee9..292b41b 100644 --- a/.github/CI.md +++ b/.github/CI.md @@ -1,9 +1,9 @@ # CI/CD -Nothing here publishes, tags or deploys. Releases to pub.dev are a separate, human-run -step (PLAN.md, "Release checklist"). All workflows except `claude-review.yml` (owned by the org's shared workflow, which needs -`pull-requests`/`issues` write, `id-token` write and a secret) use `permissions: contents: read` -and checkout with `persist-credentials: false`. +Only `release.yml` publishes (pub.dev, on a pushed version tag; see "Releases" below). Nothing else here publishes, tags or +deploys. All workflows except `claude-review.yml` (owned by the org's shared workflow, which needs +`pull-requests`/`issues` write, `id-token` write and a secret) use top-level `permissions: contents: read` +and checkout with `persist-credentials: false`; the one other permission is `id-token: write` on the two publishing jobs of `release.yml`. ## Workflows @@ -11,6 +11,7 @@ and checkout with `persist-credentials: false`. |---|---|---| | `ci.yml` | PR, push to `main` | Format, bridge and option codegen, analyze + test + iOS build, Android APK build, `pub publish --dry-run`, and the aggregate `ci-ok` | | `native-pins.yml` | weekly (Mon 06:17 UTC), manual | Verifies the pins in `native-versions.json` still exist upstream, and that the vendored option manifests are still the SDKs' published ones (`dart scripts/sync_option_manifests.dart --check`). Network checks live only here, never in PR CI | +| `release.yml` | push of a tag `v`, manual (always a dry run) | The release: gate, then publish `bugsee_flutter`, then `bugsee_flutter_feedback`, to pub.dev with OIDC. See "Releases" | | `claude-review.yml` | PR opened / updated | Calls the shared org review workflow. Advisory; do not require it (needs an org secret, unavailable to fork PRs). Do not edit it here | ### `ci.yml` jobs and check names @@ -142,6 +143,34 @@ for its CI (see `bugsee/bugsee-android` `.github/CI.md`); this repo does not, so neither competes for that slot nor inherits its dirty workspace. Moving the iOS leg there is possible later, but only after SwiftPM and Xcode availability on it are confirmed. +## Releases + +`release.yml` publishes BOTH packages from one tag, in lock-step (the same version in both pubspecs). The tag form is `v` +(`v10.0.0`, `v10.0.0-beta.1`; the form the 9.x tags use). pub.dev needs a tag pattern with `{{version}}`: `v{{version}}` for each package, and the +workflow's `on.push.tags` matches it. Authentication is pub.dev's automated publishing (GitHub OIDC, [dart.dev docs](https://dart.dev/tools/pub/automated-publishing)): +no secret exists. pub.dev accepts it only from a run triggered by a TAG PUSH, so `workflow_dispatch` (input `dryRun`, default true; false is refused +in the first step) runs the `gate` only (it includes the dry runs of both packages and prints what pub.dev has); the publish jobs do not run, so the environment's tag rule never sees a branch. + +| Job | Needs | Permissions | What it does | +|---|---|---|---| +| `gate` | | `contents: read`, `checks: read` | The tag's commit is reachable from `origin/main`; `scripts/check_release.sh` (tag == both pubspec versions == both CHANGELOG top entries; the wrapper identity, the feedback lower bound and the pins are compared by the `flutter test` below); a successful `ci-ok` check run exists on the commit (so the iOS and Android builds were green); then on the floor Flutter: format, both Pigeon checks, the option registry check, `flutter analyze` and `flutter test` (root and feedback package), `flutter pub publish --dry-run`, the core archive through `scripts/check_pub_archive.sh`, and `scripts/publish_feedback.sh` (dry run). Holds no token and no environment | +| `publish-core` | `gate`; tag push only | `contents: read`, `id-token: write`; `environment: pub.dev` | `dart-lang/setup-dart` (it exchanges the runner's OIDC token for the pub.dev credential, `PUB_TOKEN`; `subosito/flutter-action` does not), then `flutter pub publish --force` of `bugsee_flutter` (skipped when that version is already live: a re-run is safe) | +| `publish-feedback` | `gate`, `publish-core`; tag push only | the same; same environment | Waits (`scripts/pub_dev_status.sh wait`, 20 minutes) until the core version is live on pub.dev, then `dart-lang/setup-dart` (the credential is short-lived, so it is minted after the wait), then `scripts/publish_feedback.sh --publish --yes`: it refuses a dirty tree and publishes from a copy of the TRACKED files (see its header). Skipped with a warning and a step summary when the package does not exist on pub.dev yet (below); skipped when that version is live | + +- **Concurrency.** Tag pushes share the group `release`, never cancelled: a running release finishes first. GitHub keeps one running and ONE pending run per group, so a third tag push replaces the pending one (re-push it). A rehearsal has a group of its own (`release-dry-`) and cannot displace a release. +- **The checked commit is the published one.** The publish jobs check out `github.sha`, not the tag's current target, so a tag moved after the gate publishes nothing unchecked. +- **First version of the feedback package.** pub.dev can enable automated publishing only for a package that already exists, so the very first version + of `bugsee_flutter_feedback` is published by hand once (PLAN.md, release checklist). Until then `publish-feedback` publishes nothing and says so + (the core is already out by then). After the manual publish and enabling automated publishing, the next tag publishes it. +- **Guards.** `test/native_versions_test.dart` ("workflows"): only `release.yml` publishes; a publishing job is under `environment: pub.dev`, + holds `id-token: write`, needs `gate`, and publishes in a step that runs on a tag push only; `id-token: write` appears nowhere else (mutation + tests show each break failing); the gate repeats `ci.yml`'s format and codegen commands. `test/release_scripts_test.dart` runs both scripts + (the pub.dev one against a local server). `scripts/pub_dev_status.sh` treats anything but 200/404 as an error, never as "not there". +- **Manual fallback.** From a clean checkout of the tag on the floor Flutter: `flutter pub publish` for the core, wait until it is live, then + `scripts/publish_feedback.sh --publish`. Never from an agent. + +Maintainer setup (nothing here applies it): see the PR description of the release pipeline and PLAN.md, release checklist step 7. + ## Default branch The rewrite lives on `main`, the default branch (it was `nextgen` until 2026-11-23; that branch is kept as the diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..01c6cc6 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,221 @@ +name: release + +# The only workflow that publishes. Pushing a tag `v` releases BOTH packages from that +# commit, in lock-step: `bugsee_flutter` first, then (once it is live on pub.dev) +# `bugsee_flutter_feedback`. Authentication is pub.dev's automated publishing (GitHub OIDC): there +# is no secret and no stored credential. pub.dev accepts it only from a run triggered by a tag push, +# so a manual run (`workflow_dispatch`) is always a dry run: it runs the whole gate (which includes +# the dry runs of both packages) and the publish jobs do not run. See .github/CI.md ("Releases") and PLAN.md ("Release checklist"). +# +# Safety, in the order a run meets it: +# gate read-only; tag is on main, tag == both pubspecs and both CHANGELOG tops, ci-ok was +# green on the commit, format / codegen / analyze / test / pub dry-run / archive checks +# publish-core needs gate; `environment: pub.dev` (reviewers); the only job with id-token (core) +# publish-feedback needs gate + publish-core; same environment; waits for the core to be live +# test/native_versions_test.dart ("release workflow") fails if any of that is weakened. +on: + push: + tags: ['v[0-9]*.[0-9]*.[0-9]*'] + workflow_dispatch: + inputs: + dryRun: + description: 'Dry run (the only mode pub.dev accepts outside a tag push: leave true)' + type: boolean + default: true + +permissions: + contents: read + +# Two releases never overlap, and a running release is never cancelled half way. GitHub keeps one +# running and ONE pending run per group: a third tag push replaces the pending one (re-push it). +# A manual rehearsal has a group of its own, so it can neither wait behind nor displace a release. +concurrency: + group: ${{ github.event_name == 'push' && 'release' || format('release-dry-{0}', github.run_id) }} + cancel-in-progress: false + +jobs: + gate: + name: release gate + runs-on: ubuntu-latest + timeout-minutes: 45 + # checks: read, only to ask whether ci-ok passed on this commit. + permissions: + contents: read + checks: read + outputs: + version: ${{ steps.version.outputs.version }} + steps: + - name: A manual run is a dry run + if: github.event_name == 'workflow_dispatch' && !inputs.dryRun + run: | + echo "::error::pub.dev accepts automated publishing only from a tag push; a manual run is a dry run. Push the tag instead." + exit 1 + - uses: actions/checkout@v7 + with: + persist-credentials: false + # The whole history: the tag's commit must be shown to be on main. + fetch-depth: 0 + - name: The tagged commit is on main + if: github.event_name == 'push' + run: | + if ! git merge-base --is-ancestor "$GITHUB_SHA" refs/remotes/origin/main; then + echo "::error::$GITHUB_REF_NAME ($GITHUB_SHA) is not reachable from main; releases are cut from main only" + exit 1 + fi + - name: The tag names the version of both packages + id: version + env: + REF_NAME: ${{ github.ref_name }} + EVENT: ${{ github.event_name }} + run: | + if [ "$EVENT" = push ]; then + tag="$REF_NAME" + else + # Rehearsal: the tag a release of the checked-out version would carry. + tag="v$(sed -n -E 's/^version:[[:space:]]*([^[:space:]#]+).*$/\1/p' pubspec.yaml | head -n 1)" + fi + version="$(scripts/check_release.sh "$tag")" + echo "version=$version" >> "$GITHUB_OUTPUT" + echo "release $version (tag $tag)" >> "$GITHUB_STEP_SUMMARY" + - name: ci-ok passed on this commit + if: github.event_name == 'push' + env: + GH_TOKEN: ${{ github.token }} + run: | + ok="$(gh api "repos/$GITHUB_REPOSITORY/commits/$GITHUB_SHA/check-runs?per_page=100" \ + --jq '[.check_runs[] | select(.name == "ci-ok")] | length > 0 and all(.conclusion == "success")')" + if [ "$ok" != true ]; then + echo "::error::no successful ci-ok check run on $GITHUB_SHA: wait for ci to finish on main, or fix it" + exit 1 + fi + # The floor, like the checks that depend on formatter output (see ci.yml). + - uses: subosito/flutter-action@v2 + with: + channel: stable + flutter-version: '3.50.0' + cache: true + - run: flutter config --enable-swift-package-manager + - run: flutter pub get --enforce-lockfile + - run: dart format --output=none --set-exit-if-changed lib test example/lib example/integration_test scripts pigeons packages + - run: dart scripts/generate_pigeon.dart --check + - run: dart scripts/generate_pigeon.dart --package packages/bugsee_flutter_feedback --check + - run: dart scripts/generate_options.dart --check + - run: flutter analyze + - run: flutter test + - run: cd packages/bugsee_flutter_feedback && flutter analyze + - run: cd packages/bugsee_flutter_feedback && flutter test + - run: flutter pub publish --dry-run + - run: | + flutter pub publish --to-archive="$RUNNER_TEMP/core.tar.gz" + scripts/check_pub_archive.sh "$RUNNER_TEMP/core.tar.gz" + # Dry run of the sibling (and its archive check), from a copy of the tracked files. + - run: scripts/publish_feedback.sh + # Read-only: what the release would do (a rehearsal shows it without publishing). + - name: What pub.dev has now + env: + VERSION: ${{ steps.version.outputs.version }} + run: | + for p in bugsee_flutter bugsee_flutter_feedback; do + echo "$p $VERSION on pub.dev: $(scripts/pub_dev_status.sh status "$p" "$VERSION" || echo unknown)" | tee -a "$GITHUB_STEP_SUMMARY" + done + + publish-core: + name: publish bugsee_flutter + needs: [gate] + # A manual run is the gate only: pub.dev refuses it, and the environment's tag rule would too. + if: github.event_name == 'push' + runs-on: ubuntu-latest + timeout-minutes: 20 + # The reviewers of this environment approve the release; pub.dev can require it by name. + environment: pub.dev + permissions: + contents: read + id-token: write + steps: + # The commit the gate checked, never the tag's current target: a tag moved after the gate + # must not publish unchecked code. + - uses: actions/checkout@v7 + with: + persist-credentials: false + ref: ${{ github.sha }} + - uses: subosito/flutter-action@v2 + with: + channel: stable + flutter-version: '3.50.0' + cache: true + - run: flutter config --enable-swift-package-manager + - run: flutter pub get --enforce-lockfile + - name: Is this version already live? + id: live + env: + VERSION: ${{ needs.gate.outputs.version }} + # Assigned first: inside `echo "$(...)"` a failing call would be lost and the state left empty. + run: | + state="$(scripts/pub_dev_status.sh status bugsee_flutter "$VERSION")" + echo "state=$state" >> "$GITHUB_OUTPUT" + # Exchanges the runner's OIDC token for the pub.dev credential (PUB_TOKEN); the Flutter action + # does not. Right before the upload: the token is short-lived. + - uses: dart-lang/setup-dart@v1 + if: github.event_name == 'push' && steps.live.outputs.state != 'live' + with: + sdk: '3.14.0' # what Flutter 3.50.0 bundles; native-versions.json flutter.dart + - name: Publish bugsee_flutter + if: github.event_name == 'push' && steps.live.outputs.state != 'live' + run: flutter pub publish --force + - name: Already live, nothing to do + if: steps.live.outputs.state == 'live' + run: echo "::notice::bugsee_flutter ${{ needs.gate.outputs.version }} is already on pub.dev; not published again" + + publish-feedback: + name: publish bugsee_flutter_feedback + needs: [gate, publish-core] + if: github.event_name == 'push' + runs-on: ubuntu-latest + timeout-minutes: 45 + environment: pub.dev + permissions: + contents: read + id-token: write + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + ref: ${{ github.sha }} + - uses: subosito/flutter-action@v2 + with: + channel: stable + flutter-version: '3.50.0' + cache: true + - run: flutter config --enable-swift-package-manager + # The feedback package depends on the core at this version: it must resolve from pub.dev + # (indexing can lag the upload by a minute or two). + - name: Wait until the core is live + env: + VERSION: ${{ needs.gate.outputs.version }} + run: scripts/pub_dev_status.sh wait bugsee_flutter "$VERSION" 1200 15 + - name: Is this version already live? + id: live + env: + VERSION: ${{ needs.gate.outputs.version }} + run: | + state="$(scripts/pub_dev_status.sh status bugsee_flutter_feedback "$VERSION")" + echo "state=$state" >> "$GITHUB_OUTPUT" + # pub.dev: automated publishing exists only for a package that already exists, so the very + # first version of the sibling is published by hand once (PLAN.md, release checklist). + - name: The package does not exist on pub.dev yet + if: steps.live.outputs.state == 'missing-package' + run: | + msg="bugsee_flutter_feedback is not on pub.dev yet: automated publishing needs an existing package. Publish the first version by hand (PLAN.md, release checklist), then enable automated publishing for it. SKIPPED." + echo "::warning::$msg" + echo "$msg" >> "$GITHUB_STEP_SUMMARY" + # The pub.dev credential, minted after the wait above (it is short-lived). + - uses: dart-lang/setup-dart@v1 + if: github.event_name == 'push' && steps.live.outputs.state == 'missing-version' + with: + sdk: '3.14.0' + - name: Publish bugsee_flutter_feedback + if: github.event_name == 'push' && steps.live.outputs.state == 'missing-version' + run: scripts/publish_feedback.sh --publish --yes + - name: Already live, nothing to do + if: steps.live.outputs.state == 'live' + run: echo "::notice::bugsee_flutter_feedback ${{ needs.gate.outputs.version }} is already on pub.dev; not published again" diff --git a/PLAN.md b/PLAN.md index 976ae30..58e27d3 100644 --- a/PLAN.md +++ b/PLAN.md @@ -103,7 +103,17 @@ Other gaps, none with an issue: ## Release checklist -Nothing in this repository publishes, tags or deploys by itself; a maintainer does all of this by hand. +Publishing is done by `.github/workflows/release.yml` when a maintainer pushes the tag (step 7); nothing else here publishes, and an agent +never tags or publishes. The one-time setup (step 0) is by hand on pub.dev and GitHub. + +0. **One-time setup, before the first tag** (pub.dev and GitHub admin; the workflow cannot do it, see `.github/CI.md`, "Releases"): + - Publish the FIRST version of `bugsee_flutter_feedback` by hand (a new package cannot use automated publishing): from a clean checkout of + the release commit on Flutter 3.50.0, after the core is live, `scripts/publish_feedback.sh --publish`. Skip when it already exists. + - pub.dev, Admin tab of EACH package (`bugsee_flutter`, publisher bugsee.com, and `bugsee_flutter_feedback`): enable automated publishing from + GitHub Actions, repository `bugsee/bugsee-flutter`, tag pattern `v{{version}}`; tick "Require GitHub Actions environment" with `pub.dev`. + - GitHub, Settings, Environments: create `pub.dev` with required reviewers, and "deployment branches and tags" limited to the `v*` tags. + - GitHub, Settings, Rules, tags: a ruleset on `v*` so only maintainers can create tags and nobody can move or delete one. + - Rehearse: Actions, `release`, Run workflow, `dryRun` true (needs `release.yml` on the default branch). It runs the gate only (with the dry runs of both packages); the publish jobs run on a tag push only, so the first real run is the first time the environment approval, OIDC and the upload are exercised. 1. **Decide** the open questions above (publish or not, name and publisher, the first version, the default branch). 2. **Pins final.** If a native pin moves, edit `native-versions.json`, then run `dart scripts/sync_option_manifests.dart`, the two @@ -122,9 +132,11 @@ Nothing in this repository publishes, tags or deploys by itself; a maintainer do scripts/publish_feedback.sh # the feedback package: a dry run by default, then the archive check flutter pub publish --to-archive=/tmp/core.tar.gz && scripts/check_pub_archive.sh /tmp/core.tar.gz ``` -7. **Publish in order:** the core first (`flutter pub publish` from the repository root), wait until it is live on pub.dev, then the feedback package - (`scripts/publish_feedback.sh --publish`, which refuses a dirty tree and publishes from a copy of the tracked files). -8. **Tag** the release commit (`v`, the form the 9.x tags use) and write the GitHub release notes from the CHANGELOG. +7. **Tag and let the workflow publish.** On `main`, with `ci-ok` green on the release commit, push the tag `v` (the form the 9.x tags use; + `git tag -s v && git push origin v`). `release.yml` runs the gate, waits for the `pub.dev` environment approval, publishes the + core, waits until it is live, then publishes the feedback package. Manual fallback if the workflow cannot be used: the core first (`flutter pub + publish` from the repository root), wait until it is live on pub.dev, then `scripts/publish_feedback.sh --publish`. +8. **Release notes.** Write the GitHub release for the tag from the CHANGELOG. 9. **After:** check the pub.dev pages (README rendering, scores, the Platforms and SDK tabs), install from pub.dev into a clean app on both platforms, and make `main` hold the release (see open decision 5). diff --git a/doc/design-rules.md b/doc/design-rules.md index d46554a..4902c9c 100644 --- a/doc/design-rules.md +++ b/doc/design-rules.md @@ -74,7 +74,7 @@ Report files (`ReportOps.java` + `ReportFileFlow.java` + `CreatedReports.java`, ## Feedback package -Feedback package (`packages/bugsee_flutter_feedback`, doc `packages/bugsee_flutter_feedback/doc/feedback.md`): the in-app chat is a SEPARATE package (D4), a member of the repo's pub workspace (root `pubspec.yaml` `workspace:` with `example`), released in lock-step with the core (same version; constraint `>= `, never exact: pub warns; never a path dependency or an override: unpublishable). The core must never mention it (`test/feedback_package_drift_test.dart` greps lib, android, ios, the core bridge for `BugseeFeedback`/`SwiftUI`); its bridge is its OWN Pigeon definition (`packages/bugsee_flutter_feedback/pigeons`, `dart scripts/generate_pigeon.dart --package packages/bugsee_flutter_feedback`), never widen the core's. Native pins are LITERALS in its `build.gradle` / `Package.swift` (no `native-versions.json` next to a published copy), compared by that test. It adds NO Android provider (the SDK's own `BugseeFeedbackInitProvider`, or the Gradle plugin's injected `registerFeedbackExtension()`, registers the module; our call is a safety net) and on iOS it registers `BugseeFeedback` from its own `+load` registrar, referenced by the Swift plugin class, because the add-on's `+load` shim can be dead-stripped from a static link. Publish order: the core first. The sibling is dry-run/published ONLY through `scripts/publish_feedback.sh` (a copy of the TRACKED files without `.git`; a real publish refuses a dirty tree; both archives go through `scripts/check_pub_archive.sh`). The workspace `pubspec.lock` at the root is committed and CI uses `--enforce-lockfile` (regenerate on the floor Flutter). Listener slot: one SDK slot per process, so the wrapper hands the SDK ONE fan-out listener (Android `FeedbackOps.FANOUT`, iOS `BGSFlutterFeedbackFanout` + `BGSFlutterFeedbackAdapterSlot`, which tells the add-on once and never with nil: its `setListener` changes are unordered tasks): the root `.pubignore` drops `/packages/` and pub applies every ancestor `.pubignore`, so it cannot be published from its own directory in this repo. iOS tests: `packages/bugsee_flutter_feedback/ios/feedback_wrapper_tests` (same arrangement as `ios/wrapper_tests`); Android: `./gradlew :bugsee_flutter_feedback:testDebugUnitTest` from `example/android`. +Feedback package (`packages/bugsee_flutter_feedback`, doc `packages/bugsee_flutter_feedback/doc/feedback.md`): the in-app chat is a SEPARATE package (D4), a member of the repo's pub workspace (root `pubspec.yaml` `workspace:` with `example`), released in lock-step with the core (same version; constraint `>= `, never exact: pub warns; never a path dependency or an override: unpublishable). The core must never mention it (`test/feedback_package_drift_test.dart` greps lib, android, ios, the core bridge for `BugseeFeedback`/`SwiftUI`); its bridge is its OWN Pigeon definition (`packages/bugsee_flutter_feedback/pigeons`, `dart scripts/generate_pigeon.dart --package packages/bugsee_flutter_feedback`), never widen the core's. Native pins are LITERALS in its `build.gradle` / `Package.swift` (no `native-versions.json` next to a published copy), compared by that test. It adds NO Android provider (the SDK's own `BugseeFeedbackInitProvider`, or the Gradle plugin's injected `registerFeedbackExtension()`, registers the module; our call is a safety net) and on iOS it registers `BugseeFeedback` from its own `+load` registrar, referenced by the Swift plugin class, because the add-on's `+load` shim can be dead-stripped from a static link. Publish order: the core first. The sibling is dry-run/published ONLY through `scripts/publish_feedback.sh` (a copy of the TRACKED files without `.git`; a real publish refuses a dirty tree; both archives go through `scripts/check_pub_archive.sh`). Releases are made only by `.github/workflows/release.yml` (tag `v`, OIDC, `environment: pub.dev`, after its gate; `.github/CI.md`, "Releases"). The workspace `pubspec.lock` at the root is committed and CI uses `--enforce-lockfile` (regenerate on the floor Flutter). Listener slot: one SDK slot per process, so the wrapper hands the SDK ONE fan-out listener (Android `FeedbackOps.FANOUT`, iOS `BGSFlutterFeedbackFanout` + `BGSFlutterFeedbackAdapterSlot`, which tells the add-on once and never with nil: its `setListener` changes are unordered tasks): the root `.pubignore` drops `/packages/` and pub applies every ancestor `.pubignore`, so it cannot be published from its own directory in this repo. iOS tests: `packages/bugsee_flutter_feedback/ios/feedback_wrapper_tests` (same arrangement as `ios/wrapper_tests`); Android: `./gradlew :bugsee_flutter_feedback:testDebugUnitTest` from `example/android`. ## Device verification diff --git a/scripts/check_release.sh b/scripts/check_release.sh new file mode 100755 index 0000000..d3262fb --- /dev/null +++ b/scripts/check_release.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# Checks that a release tag names the version both packages carry. +# +# scripts/check_release.sh TAG # TAG is `v`, e.g. v10.0.0-beta.1 +# +# Exits 0 and prints the version when TAG is `v` + a semantic version, the root pubspec and +# the feedback package's pubspec both say that version, and the top `## ` entry of both +# CHANGELOG.md files is that version. The other repeated copies (wrapper identity in Dart, iOS +# and Android, the feedback lower bound, the native pins) are compared by `flutter test`, which +# the release gate runs; this script only ties the TAG to them. pub.dev requires the same match +# (tag pattern `v{{version}}`), and a tag that disagrees must fail before anything is uploaded. +set -euo pipefail + +root="$(cd "$(dirname "$0")/.." && pwd)" +tag="${1:?usage: $0 TAG}" + +semver='[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?' +if ! printf '%s\n' "$tag" | grep -Eq "^v$semver\$"; then + echo "::error::tag '$tag' is not v..[-prerelease]" >&2 + exit 1 +fi +want="${tag#v}" + +status=0 +check() { # LABEL ACTUAL + if [ "$2" != "$want" ]; then + echo "::error::$1 is '$2', the tag says '$want'" >&2 + status=1 + fi +} +pubspec_version() { sed -n -E 's/^version:[[:space:]]*([^[:space:]#]+).*$/\1/p' "$1" | head -n 1; } +changelog_top() { sed -n -E 's/^##[[:space:]]+v?([^[:space:]]+).*$/\1/p' "$1" | head -n 1; } + +check "pubspec.yaml version" "$(pubspec_version "$root/pubspec.yaml")" +check "packages/bugsee_flutter_feedback/pubspec.yaml version" "$(pubspec_version "$root/packages/bugsee_flutter_feedback/pubspec.yaml")" +check "CHANGELOG.md top entry" "$(changelog_top "$root/CHANGELOG.md")" +check "packages/bugsee_flutter_feedback/CHANGELOG.md top entry" "$(changelog_top "$root/packages/bugsee_flutter_feedback/CHANGELOG.md")" + +[ $status -eq 0 ] && echo "$want" +exit $status diff --git a/scripts/pub_dev_status.sh b/scripts/pub_dev_status.sh new file mode 100755 index 0000000..94f9dfe --- /dev/null +++ b/scripts/pub_dev_status.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +# Asks the pub.dev API whether a package version is live. Read-only: never needs credentials. +# +# scripts/pub_dev_status.sh status PACKAGE VERSION +# prints one word: `live`, `missing-version` (the package exists) or `missing-package` +# scripts/pub_dev_status.sh wait PACKAGE VERSION [TIMEOUT_SECONDS [INTERVAL_SECONDS]] +# polls until `live` (exit 0); exit 1 on timeout (default 900 s, every 15 s) +# +# PUB_DEV_API overrides the base URL (the tests use a local server). Any answer other than 200 or +# 404, or a network failure, is an error (exit 2 from `status`), never read as "not there". +set -euo pipefail + +api="${PUB_DEV_API:-https://pub.dev}" + +http_code() { + curl --silent --show-error --output /dev/null --write-out '%{http_code}' \ + --max-time 20 --header 'Accept: application/vnd.pub.v2+json' "$1" || echo 000 +} + +status() { + local pkg="$1" version="$2" code + code="$(http_code "$api/api/packages/$pkg/versions/$version")" + case "$code" in + 200) echo live; return 0 ;; + 404) ;; + *) echo "pub.dev answered $code for $pkg $version" >&2; return 2 ;; + esac + code="$(http_code "$api/api/packages/$pkg")" + case "$code" in + 200) echo missing-version ;; + 404) echo missing-package ;; + *) echo "pub.dev answered $code for $pkg" >&2; return 2 ;; + esac +} + +cmd="${1:-}" +case "$cmd" in + status) + status "${2:?usage: $0 status PACKAGE VERSION}" "${3:?usage: $0 status PACKAGE VERSION}" + ;; + wait) + pkg="${2:?usage: $0 wait PACKAGE VERSION [TIMEOUT [INTERVAL]]}" + version="${3:?usage: $0 wait PACKAGE VERSION [TIMEOUT [INTERVAL]]}" + timeout="${4:-900}" + interval="${5:-15}" + deadline=$((SECONDS + timeout)) + while :; do + # A transient error is retried until the deadline, like "not yet". + s="$(status "$pkg" "$version" || true)" + if [ "$s" = live ]; then + echo "$pkg $version is live" + exit 0 + fi + if [ "$SECONDS" -ge "$deadline" ]; then + echo "::error::$pkg $version is not live on pub.dev after ${timeout}s" >&2 + exit 1 + fi + echo "waiting for $pkg $version on pub.dev (${s:-no answer})" + sleep "$interval" + done + ;; + *) + echo "usage: $0 status PACKAGE VERSION | wait PACKAGE VERSION [TIMEOUT [INTERVAL]]" >&2 + exit 64 + ;; +esac diff --git a/scripts/publish_feedback.sh b/scripts/publish_feedback.sh index b2b7beb..24bd59c 100755 --- a/scripts/publish_feedback.sh +++ b/scripts/publish_feedback.sh @@ -3,7 +3,8 @@ # # scripts/publish_feedback.sh # `flutter pub publish --dry-run`, then checks the archive # scripts/publish_feedback.sh --publish # the real thing (publish bugsee_flutter FIRST); refuses a dirty tree -# scripts/publish_feedback.sh --stage DIR # only writes the copy to DIR (for the test of this script) +# scripts/publish_feedback.sh --publish --yes # the same without pub's prompt (`--force`): the release workflow +# scripts/publish_feedback.sh --stage DIR # only writes the copy to DIR (for the test of this script) # # Why a copy: the root package's .pubignore drops /packages/ so that `bugsee_flutter` does not ship # its sibling, and pub applies every .pubignore between the git root and the package it publishes, @@ -32,6 +33,12 @@ if [ ${#mode[@]} -eq 0 ] && [ -n "$(git -C "$root" status --porcelain)" ]; then exit 1 fi +if [ "${2:-}" = "--yes" ]; then + # Only with --publish: the answer to the prompt of a real publish (the release workflow has no tty). + [ ${#mode[@]} -eq 0 ] || { echo "usage: $0 [--publish [--yes] | --stage DIR]" >&2; exit 64; } + mode=(--force) +fi + if [ -n "$stage" ]; then tmp="$stage" mkdir -p "$tmp" diff --git a/test/feedback_package_drift_test.dart b/test/feedback_package_drift_test.dart index a99b095..0812f8a 100644 --- a/test/feedback_package_drift_test.dart +++ b/test/feedback_package_drift_test.dart @@ -727,6 +727,13 @@ void main() { expect(script, contains('check_pub_archive.sh')); expect(script, contains('cd packages/bugsee_flutter_feedback')); expect(script, contains('flutter pub publish')); + // `--yes` (no prompt: the release workflow has no tty) belongs to --publish only. + expect(script, contains('mode=(--force)')); + final yes = Process.runSync('bash', [ + 'scripts/publish_feedback.sh', + '--yes', + ]); + expect(yes.exitCode, 64, reason: 'a dry run must not accept --yes'); expect( File('scripts/publish_feedback.sh').statSync().mode & 0x40, isNonZero, diff --git a/test/native_versions_test.dart b/test/native_versions_test.dart index b356b1f..669c353 100644 --- a/test/native_versions_test.dart +++ b/test/native_versions_test.dart @@ -30,6 +30,110 @@ Map jobsOf(String live) { }; } +/// Why [text] (workflow file [name]) breaks the publishing rule, or an empty list. +/// +/// Only `release.yml` publishes: a real publish (a `pub publish` that is neither `--dry-run` nor +/// `--to-archive=`, or `publish_feedback.sh --publish`) must sit in a job that runs in the +/// `pub.dev` environment, holds `id-token: write`, needs the `gate` job, and in a step that runs +/// on a tag push only (`github.event_name == 'push'`). `id-token: write` exists only in such jobs. +List publishViolations(String name, String text) { + final out = []; + final live = liveOf(text); + final isRelease = name == 'release.yml'; + final realPublish = RegExp( + r'(?:(?:flutter|dart) pub publish|publish_feedback\.sh --publish)', + ); + // Each command of a line is classified on its own: `pub publish --dry-run && pub publish --force` + // is a real publish. + bool isReal(String l) => l + .split(RegExp(r'&&|\|\||;|\|')) + .any( + (c) => + realPublish.hasMatch(c) && + !c.contains('--dry-run') && + !c.contains('--to-archive='), + ); + if (!live.contains('\njobs:')) return out; + final jobs = jobsOf(live); + for (final e in jobs.entries) { + final job = e.value; + final real = job.split('\n').where(isReal).toList(); + final hasToken = RegExp( + r'^ id-token: write\s*$', + multiLine: true, + ).hasMatch(job); + final where = '$name job ${e.key}'; + if (real.isNotEmpty && !isRelease) { + out.add('$where: only release.yml publishes'); + } + if (hasToken && !isRelease) { + out.add('$where: id-token: write outside release.yml'); + } + if (hasToken && real.isEmpty) { + out.add('$where: id-token: write outside a publishing job'); + } + if (real.isEmpty) continue; + if (!RegExp( + r'^ environment: pub\.dev\s*$', + multiLine: true, + ).hasMatch(job)) { + out.add('$where: a publishing job must run in `environment: pub.dev`'); + } + if (!hasToken) { + out.add('$where: a publishing job needs id-token: write (OIDC)'); + } + final needs = RegExp( + r'^ needs: \[([^\]]*)\]', + multiLine: true, + ).firstMatch(job); + if (needs == null || + !needs.group(1)!.split(',').map((e) => e.trim()).contains('gate')) { + out.add('$where: a publishing job must need the gate job'); + } + // The job runs after a SUCCESSFUL gate: no condition may override that (`always()` runs a job + // after a failed need), and a failed gate must not be tolerated. + final jobIf = RegExp(r'^ if: (.*)$', multiLine: true).firstMatch(job); + if (jobIf != null && + RegExp(r'always\(\)|cancelled\(\)|failure\(\)') + .hasMatch(jobIf.group(1)!)) { + out.add( + '$where: a job-level if must not run the job after a failed gate', + ); + } + if (live.contains('continue-on-error')) { + out.add('$where: continue-on-error would let a failed gate pass'); + } + final steps = job.split(RegExp(r'\n - ')); + for (final step in steps) { + if (!step.split('\n').any(isReal)) continue; + // `push` required, alone or AND-ed with more (never OR-ed with another event). + final cond = RegExp(r'^\s+if: (.*)$', multiLine: true).firstMatch(step); + if (cond == null || + !RegExp(r"^github\.event_name == 'push'( && [^|]*)?$") + .hasMatch(cond.group(1)!.trim())) { + out.add('$where: a real publish step must run on a tag push only'); + } + } + // pub.dev OIDC: setup-dart exchanges the runner token for PUB_TOKEN; before the publish. + final realAt = steps.indexWhere((st) => st.split('\n').any(isReal)); + final oidcAt = steps.indexWhere( + (st) => st.contains('uses: dart-lang/setup-dart@v1'), + ); + if (oidcAt < 0 || oidcAt > realAt) { + out.add( + '$where: a publishing job must run dart-lang/setup-dart (the pub.dev OIDC token) before the publish', + ); + } + } + if (isRelease && jobs.containsKey('gate')) { + final gate = jobs['gate']!; + if (gate.contains('id-token') || gate.contains('environment:')) { + out.add('$name: the gate must not hold the OIDC token or an environment'); + } + } + return out; +} + void main() { final pins = jsonDecode(read('native-versions.json')) as Map; final flutterPin = pins['flutter'] as Map; @@ -452,6 +556,14 @@ void main() { test('every workflow is least-privilege', () { for (final f in ours) { final live = liveOf(read(f.path)); + // The one write permission there is: the OIDC token of a publishing job in release.yml + // (where it may sit is checked by `only the release workflow publishes` below). + final noToken = f.path.endsWith('release.yml') + ? live.replaceAll( + RegExp(r'^ id-token: write\n', multiLine: true), + '', + ) + : live; expect( live, matches( @@ -460,7 +572,7 @@ void main() { reason: '${f.path}: top-level permissions must be contents: read', ); expect( - live, + noToken, isNot(contains('write')), reason: '${f.path}: no write permission', ); @@ -493,18 +605,254 @@ void main() { } }); - test('nothing publishes: pub publish is always a dry run', () { - for (final f in files) { - for (final l in liveOf(read(f.path)).split('\n')) { - if (RegExp(r'(flutter|dart) pub publish').hasMatch(l)) { - // `--to-archive` only writes the tarball: it never uploads. - expect( - l.contains('--dry-run') || l.contains('--to-archive='), - isTrue, - reason: '${f.path}: $l', - ); - } - } + // Was "nothing publishes: pub publish is always a dry run". The release workflow now publishes + // (pub.dev automated publishing, OIDC), so the rule is where a publish may sit, not that there + // is none; every other workflow still only dry-runs or writes an archive. + test('only the release workflow publishes, only under the environment, only after the gate', () { + // The shared-workflow callers (claude-review.yml needs id-token: write for its own purpose) + // hold no `run:` lines; only our own workflows can publish. + for (final f in ours) { + final name = f.path.split('/').last; + expect(publishViolations(name, read(f.path)), isEmpty, reason: name); + } + // release.yml really has them (a rule that matched nothing would pass vacuously). + final jobs = jobsOf(liveOf(read('.github/workflows/release.yml'))); + expect(jobs.keys, ['gate', 'publish-core', 'publish-feedback']); + expect(jobs['publish-core'], contains('flutter pub publish --force')); + expect( + jobs['publish-feedback'], + contains('scripts/publish_feedback.sh --publish --yes'), + ); + expect( + jobs['publish-feedback'], + contains('needs: [gate, publish-core]'), + reason: 'the sibling depends on the core: it follows it', + ); + }); + + test('the publishing rule fails when it is broken (mutations)', () { + final release = read('.github/workflows/release.yml'); + final ci = read('.github/workflows/ci.yml'); + List v(String name, String text) => publishViolations(name, text); + String swap(String text, String from, String to) { + expect(text, contains(from), reason: 'the mutation must apply: $from'); + return text.replaceFirst(from, to); + } + + // A publish anywhere but release.yml (a dry run or an archive is fine). + expect( + v( + 'ci.yml', + swap( + ci, + 'flutter pub publish --dry-run', + 'flutter pub publish --force', + ), + ), + contains(contains('only release.yml publishes')), + ); + expect( + v( + 'ci.yml', + swap( + ci, + '- run: scripts/publish_feedback.sh\n', + '- run: scripts/publish_feedback.sh --publish\n', + ), + ), + contains(contains('only release.yml publishes')), + ); + // The OIDC token outside release.yml. + expect( + v( + 'ci.yml', + swap( + ci, + ' timeout-minutes: 15\n', + ' timeout-minutes: 15\n permissions:\n id-token: write\n', + ), + ), + contains(contains('id-token: write outside release.yml')), + ); + // A publishing job without the environment, without the token, without the gate. + expect( + v('release.yml', swap(release, ' environment: pub.dev\n', '')), + contains(contains('environment: pub.dev')), + ); + expect( + v('release.yml', swap(release, ' id-token: write\n', '')), + contains(contains('needs id-token: write')), + ); + expect( + v('release.yml', swap(release, ' needs: [gate]\n', '')), + contains(contains('must need the gate job')), + ); + expect( + v( + 'release.yml', + swap(release, 'needs: [gate, publish-core]', 'needs: [publish-core]'), + ), + contains(contains('must need the gate job')), + ); + // The token in a job that publishes nothing (the gate). + expect( + v( + 'release.yml', + swap( + release, + ' checks: read\n', + ' checks: read\n id-token: write\n', + ), + ), + contains(contains('outside a publishing job')), + ); + // A real publish that a manual run would reach. + expect( + v( + 'release.yml', + swap( + release, + " if: github.event_name == 'push' && steps.live.outputs.state != 'live'\n run: flutter pub publish --force", + ' run: flutter pub publish --force', + ), + ), + contains(contains('tag push only')), + ); + // A dry run chained to a real publish is a real publish. + expect( + v( + 'ci.yml', + swap( + ci, + '- run: flutter pub publish --dry-run', + '- run: flutter pub publish --dry-run && flutter pub publish --force', + ), + ), + contains(contains('only release.yml publishes')), + ); + // A condition that also admits a manual run. + expect( + v( + 'release.yml', + release.replaceAll( + "if: github.event_name == 'push' && steps.live.outputs.state != 'live'", + "if: github.event_name == 'push' || github.event_name == 'workflow_dispatch'", + ), + ), + contains(contains('tag push only')), + ); + // A publishing job that runs after a failed gate. + expect( + v( + 'release.yml', + swap( + release, + " needs: [gate]\n # A manual run", + " needs: [gate]\n if: always()\n # A manual run", + ), + ), + contains(contains('after a failed gate')), + ); + expect( + v( + 'release.yml', + swap( + release, + ' timeout-minutes: 45\n # checks: read', + ' timeout-minutes: 45\n continue-on-error: true\n # checks: read', + ), + ), + contains(contains('continue-on-error')), + ); + // No pub.dev OIDC setup before the publish (nothing would authenticate it). + expect( + v( + 'release.yml', + release.replaceAll( + RegExp(r' - uses: dart-lang/setup-dart@v1\n(?: .*\n)+'), + '', + ), + ), + contains(contains('dart-lang/setup-dart')), + ); + expect(v('release.yml', release), isEmpty); + }); + + test('release.yml: version tag or by hand, dry run by default, never overlapping, the gate is ci.yml\'s checks', () { + final live = liveOf(read('.github/workflows/release.yml')); + final jobs = jobsOf(live); + expect(live, contains("tags: ['v[0-9]*.[0-9]*.[0-9]*']")); + expect(live, contains('workflow_dispatch:')); + expect(live, isNot(contains('pull_request'))); + expect(live, isNot(contains('branches:'))); + expect( + live, + matches(RegExp(r'dryRun:\n(?:\s+.*\n)*?\s+default: true\n')), + ); + expect( + live, + contains( + r"group: ${{ github.event_name == 'push' && 'release' || format('release-dry-{0}', github.run_id) }}", + ), + reason: 'one release at a time; a rehearsal has its own group', + ); + // Both publish jobs exist for a tag push only (the environment's tag rule would refuse a branch). + for (final j in ['publish-core', 'publish-feedback']) { + expect( + jobs[j], + contains(" if: github.event_name == 'push'\n"), + reason: j, + ); + } + // A status read keeps its exit code: never `echo "...$(pub_dev_status.sh ...)"` in a publishing job. + for (final j in ['publish-core', 'publish-feedback']) { + expect( + jobs[j], + isNot(contains(r'echo "state=$(scripts/pub_dev_status')), + reason: + '$j: a failing status call would be lost and read as nothing to do', + ); + } + expect(live, contains('cancel-in-progress: false')); + // The gate repeats ci.yml's format and codegen commands, on the floor. + final ci = liveOf(read('.github/workflows/ci.yml')); + final gate = jobs['gate']!; + for (final cmd in [ + 'dart format --output=none --set-exit-if-changed lib test example/lib example/integration_test scripts pigeons packages', + 'dart scripts/generate_pigeon.dart --check', + 'dart scripts/generate_pigeon.dart --package packages/bugsee_flutter_feedback --check', + 'dart scripts/generate_options.dart --check', + ]) { + expect(ci, contains(cmd)); + expect(gate, contains(cmd), reason: cmd); + } + for (final cmd in [ + 'flutter analyze', + 'flutter test', + 'flutter pub publish --dry-run', + r'scripts/check_pub_archive.sh "$RUNNER_TEMP/core.tar.gz"', + 'scripts/check_release.sh', + '- run: scripts/publish_feedback.sh\n', + r'git merge-base --is-ancestor "$GITHUB_SHA" refs/remotes/origin/main', + 'name == "ci-ok"', + ]) { + expect(gate, contains(cmd), reason: cmd); + } + expect( + live, + contains("sdk: '${flutterPin['dart']}'"), + reason: + 'the Dart of the OIDC setup is the one the floor Flutter bundles', + ); + final floor = "flutter-version: '${flutterPin['min']}'"; + expect( + "flutter-version: '".allMatches(live).length, + floor.allMatches(live).length, + reason: 'every Flutter in the release is the floor', + ); + // Publishing jobs check out the gated commit, not whatever the tag points at later. + for (final j in ['publish-core', 'publish-feedback']) { + expect(jobs[j], contains(r'ref: ${{ github.sha }}'), reason: j); } }); diff --git a/test/release_scripts_test.dart b/test/release_scripts_test.dart new file mode 100644 index 0000000..b625627 --- /dev/null +++ b/test/release_scripts_test.dart @@ -0,0 +1,149 @@ +// The two scripts of the release workflow (.github/workflows/release.yml), run for real: +// scripts/check_release.sh (tag == pubspecs == CHANGELOG tops) and scripts/pub_dev_status.sh +// (is a version live on pub.dev), the latter against a local server so nothing reaches pub.dev. +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; + +String pubspecVersion() => RegExp( + r'^version:[ \t]*(\S+)', + multiLine: true, +).firstMatch(File('pubspec.yaml').readAsStringSync())!.group(1)!; + +void main() { + group('check_release.sh', () { + ProcessResult run(String tag, {String root = '.'}) => + Process.runSync('bash', ['$root/scripts/check_release.sh', tag]); + + test('the current tree is releasable under its own version', () { + final r = run('v${pubspecVersion()}'); + expect(r.exitCode, 0, reason: '${r.stderr}'); + expect('${r.stdout}'.trim(), pubspecVersion()); + }); + + test('a tag that is not v is refused', () { + for (final tag in [ + '10.0.0', + 'v10.0', + 'v10.0.0.1', + 'v10.0.0 ', + 'vX', + '', + ]) { + expect(run(tag).exitCode, isNot(0), reason: "'$tag'"); + } + }); + + test('a tag that names another version is refused, naming each copy', () { + final r = run('v99.0.0'); + expect(r.exitCode, 1); + final err = '${r.stderr}'; + for (final what in [ + 'pubspec.yaml version', + 'packages/bugsee_flutter_feedback/pubspec.yaml version', + 'CHANGELOG.md top entry', + 'packages/bugsee_flutter_feedback/CHANGELOG.md top entry', + ]) { + expect(err, contains(what)); + } + }); + + test('each copy alone is enough to refuse', () { + final tmp = Directory.systemTemp.createTempSync('rel'); + addTearDown(() => tmp.deleteSync(recursive: true)); + Directory('${tmp.path}/scripts').createSync(); + Directory('${tmp.path}/packages/bugsee_flutter_feedback') + .createSync(recursive: true); + File('scripts/check_release.sh') + .copySync('${tmp.path}/scripts/check_release.sh'); + void lay(Map v) { + File('${tmp.path}/pubspec.yaml') + .writeAsStringSync('name: a\nversion: ${v['p']}\n'); + File('${tmp.path}/packages/bugsee_flutter_feedback/pubspec.yaml') + .writeAsStringSync('name: b\nversion: ${v['fp']}\n'); + File('${tmp.path}/CHANGELOG.md') + .writeAsStringSync('## ${v['c']}\n\ntext\n## 1.0.0\n'); + File('${tmp.path}/packages/bugsee_flutter_feedback/CHANGELOG.md') + .writeAsStringSync('## ${v['fc']}\n'); + } + + lay({'p': '1.2.3', 'fp': '1.2.3', 'c': '1.2.3', 'fc': '1.2.3'}); + expect(run('v1.2.3', root: tmp.path).exitCode, 0); + for (final k in ['p', 'fp', 'c', 'fc']) { + final v = {'p': '1.2.3', 'fp': '1.2.3', 'c': '1.2.3', 'fc': '1.2.3'}; + v[k] = '1.2.4'; + lay(v); + final r = run('v1.2.3', root: tmp.path); + expect(r.exitCode, 1, reason: k); + expect('${r.stderr}', contains("'1.2.4'"), reason: k); + } + }); + }); + + group('pub_dev_status.sh', () { + late HttpServer server; + late String api; + // path -> status code; anything else is 404, '/boom' paths are 500. + final known = { + '/api/packages/core': 200, + '/api/packages/core/versions/1.0.0': 200, + '/api/packages/err': 500, + '/api/packages/err/versions/1.0.0': 500, + }; + + setUp(() async { + server = await HttpServer.bind('127.0.0.1', 0); + api = 'http://127.0.0.1:${server.port}'; + server.listen((req) { + req.response.statusCode = known[req.uri.path] ?? 404; + req.response.close(); + }); + }); + tearDown(() => server.close(force: true)); + + Future run(List args) => Process.run( + 'bash', + ['scripts/pub_dev_status.sh', ...args], + environment: {'PUB_DEV_API': api}, + ); + + test('live, missing version, missing package', () async { + expect( + '${(await run(['status', 'core', '1.0.0'])).stdout}'.trim(), + 'live', + ); + expect( + '${(await run(['status', 'core', '2.0.0'])).stdout}'.trim(), + 'missing-version', + ); + expect( + '${(await run(['status', 'nope', '1.0.0'])).stdout}'.trim(), + 'missing-package', + ); + }); + + test('a server error is an error, never "not there" (a flaky answer must not skip a publish)', () async { + final r = await run(['status', 'err', '1.0.0']); + expect(r.exitCode, 2); + expect('${r.stdout}'.trim(), isEmpty); + }); + + test('an unreachable server is an error too', () async { + await server.close(force: true); + final r = await run(['status', 'core', '1.0.0']); + expect(r.exitCode, 2); + server = await HttpServer.bind('127.0.0.1', 0); + }); + + test('wait returns when live and times out when not', () async { + expect((await run(['wait', 'core', '1.0.0', '5', '1'])).exitCode, 0); + final r = await run(['wait', 'core', '2.0.0', '2', '1']); + expect(r.exitCode, 1); + expect('${r.stderr}', contains('not live on pub.dev after 2s')); + }); + + test('a bad command is a usage error', () async { + expect((await run(['frobnicate'])).exitCode, 64); + }); + }); +}