Cotton code
290 lines · 15.1 KB · ShellRaw
#!/usr/bin/env bash# Run apps/cotton's CottonUITests on this Mac from a package outside the tree, where the FFI stub cannot stop them.##   scripts/ui-tests-stub.sh                                   # every test, this checkout#   scripts/ui-tests-stub.sh -- --filter TableDefinition       # extra args go to `swift test`#   scripts/ui-tests-stub.sh --checkout .worktrees/foo --summary -- --filter Notes#   scripts/ui-tests-stub.sh --prepare-only                    # write the package, sync, build nothing#   scripts/ui-tests-stub.sh --speed <out>                     # synthetic simulator frame timings#   scripts/ui-tests-stub.sh --fan-perf <out> [--fan-sim <udid>]#                                                              # the fan's budgets traced (scripts/perf/fan.sh)#   scripts/ui-tests-stub.sh --scroll-perf <out> [--fan-sim <udid>]#                                                              # lists flung under the fan, traced (scripts/perf/scroll.sh)#   scripts/ui-tests-stub.sh --voice <out>                     # dictation accuracy on synthetic speech (this Mac)#   scripts/ui-tests-stub.sh --voice <out> --recording <audio> --script <json>#                                                              # ... on one recording of the script read aloud, cut on its pauses#   scripts/ui-tests-stub.sh --voice <out> --manifest <json>   # ... on {hints, utterances: [{text, file}]}#   scripts/ui-tests-stub.sh --list                            # `swift test list`#   scripts/ui-tests-stub.sh --home-preview <udid> [-- <app args>]#                                                              # synthetic Home on YOUR booted simulator#                                                              # (-home-board bare, -home-tiles N)#   scripts/ui-tests-stub.sh --home-walk <udid> --walk <name> --walk-out <mp4> [-- <app args>]#                                                              # a walk of real touches on it, recorded#                                                              # (scripts/home-preview/HomeWalkUITests.swift)##   --checkout <root>  the checkout or worktree whose apps/cotton is tested#                      (default: the one holding this script)#   --dir <dir>        the package directory (default:#                      one locked reused directory per CI job; locally a#                      reusable ${TMPDIR}/cotton-ui-tests-stub/<checkout hash>)#   --summary          after the run, print "N run, M failed" and each failing test## WHY IT EXISTS. `swift test` in apps/cotton builds every test target, and# CottonKitTests needs the REAL Rust core — under the FFI stub# (`scripts/ffi-stub.sh`) its FFI tests fail beside CottonUITests'. CottonUITests needs only the product CottonUI,# which does not link the core. So this writes a small# package that depends on a private copy of apps/cotton BY PATH, holds a copy of# Tests/CottonUITests as its one test target `Check`, and runs `swift test`# there. Every session used to build that package by hand.## THE PRIVATE DEPENDENCY. A phone cut may leave a phone-only real framework# at apps/cotton/.ffi. The normal ffi-stub.sh preserves it, so a Mac stub# build cannot use that package directly. Sync the package into this run's# directory without build outputs or .ffi, then run a copy of ffi-stub.sh# there. SwiftPM sees only this private stub; the checkout's cut is untouched.## WHAT STAYS IN STEP. The tools version and the platforms are read from# apps/cotton/Package.swift on every run, so they never drift. The tests are# re-synced on every run with `rsync --delete`, so an edited test is the one# that runs and a deleted one is gone. The package directory is KEPT between# runs, so the second build is incremental (the first is about 3.5 GB).## THE TESTS READ THE TREE THEY CAME FROM. Many of them read the repository's# own files — sources, definitions, fixtures, the crates' copies — from a root# they find by walking up from `#filePath`, and `#filePath` in a copy names the# copy: from there nothing is where they look, and 21 of 64 tests in four# classes failed on "expected non-nil" (11 Oct 2026). So a run exports# COTTON_UI_TESTS_REPO_ROOT=<checkout>, which `SourceSweep.repoRoot` honours# before it walks, and every test that reads the tree asks the sweep for the# root. Nothing is linked. (The compiler's `-file-prefix-map` does not remap# `#filePath`; tried.) A failure's file and line still name the copy.## STILL EXPECTED TO FAIL: anything that wants the real core.## THE BUILD LOCK. `swift test` is a heavy build, so it runs under# `scripts/with-build-lock.sh`, as `scripts/ios-test.sh` does — re-entrant, so# a caller wrapping this script too is harmless. Set BUILD_LOCK_TIMEOUT_MIN to# cap the wait. `--prepare-only` builds nothing and takes no lock.## Exits with `swift test`'s status.set -euo pipefailHERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"# The wrapper holds the package lock through preparation and the build. CI's# default package is reused by job kind; an explicit --dir is reused under lock.if [ -z "${COTTON_STUB_LOCK_FD:-}" ]; then  exec python3 "$HERE/ci/ui-stub-workspace.py" "${BASH_SOURCE[0]}" "$@"fiUSAGE="usage: ui-tests-stub.sh [--checkout <root>] [--dir <dir>] [--list] [--prepare-only] [--home-preview <udid>] [--home-walk <udid> --walk <name> --walk-out <mp4>] [--speed <out>] [--fan-perf <out> [--fan-sim <udid>]] [--scroll-perf <out> [--fan-sim <udid>]] [--voice <out> [--recording <audio> --script <json> | --manifest <json>]] [--summary] [-- <swift test args>]"CHECKOUT="$(cd "$HERE/.." && pwd)"DIR=""MODE=runSPEED_OUT=""SUMMARY=""EXTRA=()while [ $# -gt 0 ]; do  case "$1" in    --checkout) CHECKOUT="$(cd "${2:?$USAGE}" && pwd)"; shift 2 ;;    --dir) DIR="${2:?$USAGE}"; shift 2 ;;    --speed) MODE=speed; SPEED_OUT="${2:?--speed needs an output folder}"; shift 2 ;;    --fan-perf) MODE=fanperf; SPEED_OUT="${2:?--fan-perf needs an output folder}"; shift 2 ;;    --scroll-perf) MODE=scrollperf; SPEED_OUT="${2:?--scroll-perf needs an output folder}"; shift 2 ;;    --fan-sim) FAN_SIM="${2:?--fan-sim needs a simulator udid}"; shift 2 ;;    --voice) MODE=voice; SPEED_OUT="${2:?--voice needs an output folder}"; shift 2 ;;    --recording) export VOICEGATE_RECORDING="$(cd "$(dirname "${2:?--recording needs a file}")" && pwd)/$(basename "$2")"; shift 2 ;;    --script) export VOICEGATE_SCRIPT="$(cd "$(dirname "${2:?--script needs a file}")" && pwd)/$(basename "$2")"; shift 2 ;;    --manifest) export VOICEGATE_MANIFEST="$(cd "$(dirname "${2:?--manifest needs a file}")" && pwd)/$(basename "$2")"; shift 2 ;;    --list) MODE=list; shift ;;    --home-preview) MODE=preview; PREVIEW_SIM="${2:?--home-preview needs a simulator udid}"; shift 2 ;;    --home-walk) MODE=walk; PREVIEW_SIM="${2:?--home-walk needs a simulator udid}"; shift 2 ;;    --walk) WALK="${2:?--walk needs a walk name}"; shift 2 ;;    --walk-out) WALK_OUT="$(cd "$(dirname "${2:?--walk-out needs a file}")" && pwd)/$(basename "$2")"; shift 2 ;;    --prepare-only) MODE=prepare; shift ;;    --summary) SUMMARY=1; shift ;;    --) shift; EXTRA=("$@"); break ;;    -h|--help) echo "$USAGE"; exit 0 ;;    *) echo "$USAGE" >&2; exit 64 ;;  esacdonepython3 "$CHECKOUT/scripts/gen-swift-definition-types.py"APP="$CHECKOUT/apps/cotton"MANIFEST="$APP/Package.swift"[ -f "$MANIFEST" ] || { echo "ui-tests-stub: no $MANIFEST" >&2; exit 66; }[ -d "$APP/Tests/CottonUITests" ] || { echo "ui-tests-stub: no $APP/Tests/CottonUITests" >&2; exit 66; }if [ -z "$DIR" ]; then  HASH="$(printf '%s' "$CHECKOUT" | shasum | cut -c1-12)"  DIR="${TMPDIR:-/tmp}"  DIR="${DIR%/}/cotton-ui-tests-stub/$HASH"fi# `--dir` and TMPDIR move this folder, and the script deletes inside it (the# rsync below, the build plan further down), so it must not be a home folder.. "$HERE/lib/owned-root.sh"refuse_wide_root "the stub package's folder (--dir)" "$DIR"mkdir -p "$DIR"DIR="$(cd "$DIR" && pwd -P)"CHECKOUT_REAL="$(cd "$CHECKOUT" && pwd -P)"case "$DIR/" in  "$CHECKOUT_REAL/"*) echo "ui-tests-stub: --dir must be outside the checkout" >&2; exit 2 ;;esacSTUB_APP="$DIR/apps/cotton"mkdir -p "$DIR/Tests/Check" "$STUB_APP"STUB_APP="$(cd "$STUB_APP" && pwd -P)"APP_REAL="$(cd "$APP" && pwd -P)"# Refuse a pre-existing symlink that makes rsync read and delete in one tree.case "$STUB_APP/" in "$APP_REAL/"*) echo "ui-tests-stub: private package overlaps the checkout" >&2; exit 2 ;; esaccase "$APP_REAL/" in "$STUB_APP/"*) echo "ui-tests-stub: private package overlaps the checkout" >&2; exit 2 ;; esac# /build/ is the app's own derived data (`xcodebuild -derivedDataPath build`,# 7 GB and more): copied, it filled one Mac's disk to its floor on 15 Oct 2026.rsync -a --delete --exclude=.ffi/ --exclude=.build/ --exclude=.swiftpm/ \  --exclude=/build/ --exclude=out/ --exclude=node_modules/ "$APP/" "$STUB_APP/"# Loom, the package apps/cotton depends on by path (`../loom`), beside it, so# the private copy resolves its sibling exactly as the checkout does.mkdir -p "$DIR/apps/loom"rsync -a --delete --exclude=.build/ --exclude=.swiftpm/ "$CHECKOUT/apps/loom/" "$DIR/apps/loom/"TOOLS="$(head -n 1 "$MANIFEST")"case "$TOOLS" in  "// swift-tools-version"*) ;;  *) echo "ui-tests-stub: $MANIFEST does not open with a swift-tools-version line" >&2; exit 65 ;;esacPLATFORMS="$(grep -m 1 -E '^[[:space:]]*platforms:' "$MANIFEST" | sed -E 's/^[[:space:]]*//; s/,[[:space:]]*$//')"[ -n "$PLATFORMS" ] || { echo "ui-tests-stub: no platforms line in $MANIFEST" >&2; exit 65; }# The package identity of a path dependency is its directory name: "cotton".# Written only when it changed, so an unchanged manifest is not re-evaluated.NEW="$DIR/Package.swift.new"cat > "$NEW" <<EOF$TOOLS// Written by scripts/ui-tests-stub.sh — regenerated on every run; edits are lost.import PackageDescriptionlet package = Package(    name: "CottonUITestsStub",    $PLATFORMS,    dependencies: [.package(path: "$STUB_APP")],    targets: [        .testTarget(            name: "Check",            dependencies: [                .product(name: "CottonUI", package: "cotton"),            ],            path: "Tests/Check"        ),    ])EOFif cmp -s "$NEW" "$DIR/Package.swift"; then rm "$NEW"; else mv "$NEW" "$DIR/Package.swift"; firsync -a --delete "$APP/Tests/CottonUITests/" "$DIR/Tests/Check/"echo "ui-tests-stub: $DIR ← ${APP#"$CHECKOUT/"}/Tests/CottonUITests"[ "$MODE" = prepare ] && exit 0# ffi-stub.sh roots its output beside the script. Its private copy therefore# writes $DIR/apps/cotton/.ffi, never the checkout's retained real framework.mkdir -p "$DIR/scripts"cp "$CHECKOUT/scripts/ffi-stub.sh" "$DIR/scripts/ffi-stub.sh"bash "$DIR/scripts/ffi-stub.sh" >/dev/null# A CHANGED STUB OR PATH DROPS WHAT THIS PACKAGE BUILT WITH THE ONE BEFORE. Swift# Build reads the XCFramework's Info.plist while PLANNING and caches the plan# by the request, never by the bytes at that path — so a stub replaced by a# real archive (or by a stub in a newer shape) went on being planned as the one# before it, and an archive that could not be loaded kept failing after a good# one was in place (12 Oct 2026). The products go with the plan: the headers a# real archive put among them stay importable after the archive is gone, and# CottonKit then compiles against a core the stub does not link ("Undefined# symbols … _cotton_call"). `scripts/build-xcframework.sh` drops the plan of# apps/cotton's own .build; this package's .build is another directory, so it# is done here, whenever the archive's Info.plist is not the one the last run# built with. Include its path, so a package prepared by the old script using# the checkout also drops cached real headers on its first private-stub run.# A rebuilt archive with the same slices has the same Info.plist# and costs nothing. The resolved dependencies stay.FFI_PLIST="$STUB_APP/.ffi/CottonFFI.xcframework/Info.plist"FFI_NOW="$FFI_PLIST:$([ -f "$FFI_PLIST" ] && shasum "$FFI_PLIST" | cut -c1-40 || true)"FFI_SEEN="$DIR/.ffi-plist"if [ "$FFI_NOW" != "$(cat "$FFI_SEEN" 2>/dev/null || true)" ]; then  rm -rf "$DIR/.build/manifest.pif" "$DIR/.build/out"  printf '%s\n' "$FFI_NOW" > "$FFI_SEEN"fi# A resolved dependency with no manifest is one the Mac's temp sweep emptied:# the folder stays and every file not read for three days goes, so the nightly# swift-guards failed on SwiftTerm's Package.swift on 7 Nov 2026. SwiftPM# trusts its recorded state over the tree, so that state goes with the# checkouts and the clones they came from, and this build resolves again.for checkout in "$DIR"/.build/checkouts/*/; do  [ -d "$checkout" ] || continue  if [ ! -f "${checkout}Package.swift" ]; then    echo "ui-tests-stub: ${checkout} has no manifest; resolving the dependencies again" >&2    rm -rf "$DIR/.build/checkouts" "$DIR/.build/repositories" "$DIR/.build/workspace-state.json"    break  fidoneif [ "$MODE" = speed ]; then  BUILD_LOCK_LABEL=speedgate bash "$HERE/with-build-lock.sh" bash "$HERE/speedgate/run-simulator.sh" "$DIR" "$SPEED_OUT" "$CHECKOUT"  exit $?fiif [ "$MODE" = fanperf ]; then  BUILD_LOCK_LABEL=fan-perf bash "$HERE/with-build-lock.sh" bash "$HERE/perf/run-simulator.sh" "$DIR" "$SPEED_OUT" "$CHECKOUT" "${FAN_SIM:-}"  exit $?fiif [ "$MODE" = scrollperf ]; then  BUILD_LOCK_LABEL=scroll-perf bash "$HERE/with-build-lock.sh" bash "$HERE/perf/run-scroll.sh" "$DIR" "$SPEED_OUT" "$CHECKOUT" "${FAN_SIM:-}"  exit $?fiif [ "$MODE" = preview ]; then  BUILD_LOCK_LABEL=home-preview bash "$HERE/with-build-lock.sh" bash "$HERE/home-preview/run.sh" "$DIR" "$PREVIEW_SIM" "$CHECKOUT" ${EXTRA[@]+"${EXTRA[@]}"}  exit $?fiif [ "$MODE" = walk ]; then  BUILD_LOCK_LABEL=home-walk bash "$HERE/with-build-lock.sh" bash "$HERE/home-preview/walk.sh" "$DIR" "$PREVIEW_SIM" "$CHECKOUT" \    "${WALK_OUT:?--home-walk needs --walk-out}" "${WALK:?--home-walk needs --walk}" ${EXTRA[@]+"${EXTRA[@]}"}  exit $?fiif [ "$MODE" = voice ]; then  BUILD_LOCK_LABEL=voicegate bash "$HERE/with-build-lock.sh" bash "$HERE/voicegate/run.sh" "$DIR" "$SPEED_OUT" "$CHECKOUT"  exit $?fiif [ "$MODE" = list ]; then  CMD=(swift test list)else  CMD=(swift test)fi[ ${#EXTRA[@]} -gt 0 ] && CMD+=("${EXTRA[@]}")LOG="$DIR/last-run.log"set +e(cd "$DIR" && COTTON_UI_TESTS_REPO_ROOT="$CHECKOUT" BUILD_LOCK_LABEL="${BUILD_LOCK_LABEL:-ui-tests-stub}" \  bash "$HERE/with-build-lock.sh" "${CMD[@]}") 2>&1 | tee "$LOG"status=${PIPESTATUS[0]}set -eif [ -n "$SUMMARY" ] && [ "$MODE" = run ]; then  # XCTest's last "Executed" line is the whole run's count.  # No such line means the build failed or nothing ran — never a green "0 failed".  # A skipped test puts "with 1 test skipped and N failures" in that line.  TOTALS="$(grep -E 'Executed [0-9]+ tests?, with ([0-9]+ tests? skipped and )?[0-9]+ failures?' "$LOG" | tail -n 1 || true)"  if [ -z "$TOTALS" ]; then    echo "ui-tests-stub: NO TESTS RAN — read $LOG"  else    RUN="$(sed -E 's/.*Executed ([0-9]+) tests?.*/\1/' <<<"$TOTALS")"    FAILED="$(sed -E 's/.*(with|and) ([0-9]+) failures?.*/\2/' <<<"$TOTALS")"    echo "ui-tests-stub: $RUN run, $FAILED failed"  fi  grep -oE "Test Case '-\[[^]]+\]' failed" "$LOG" | sed -E "s/Test Case '-\[(.*)\]' failed/ui-tests-stub: FAILED \1/" | sort -u || truefiexit "$status"