refactor(build): unify SDK configuration and release tooling
Gitea CI / Check code and tests (pull_request) Failing after 8m56s
Gitea CI / Build Android APK (pull_request) Skipped
Gitea CI / Build Windows x64 app (pull_request) Skipped
Gitea CI / Audit and package Windows x64 (pull_request) Skipped
Gitea CI / Assemble and validate CI artifacts (pull_request) Skipped
Gitea CI / Gitea CI passed (pull_request) Failing after 4s

Pin Flutter with FVM and share local environment loading across IDE, Python, and Dart entrypoints. Keep CI on the verified preinstalled SDK and skip local overrides.

Extract common build presets, process execution, and file hashing. Propagate project roots through SDK selection and release commands, and migrate macOS release, signing, and DMG orchestration to Python.

Reuse local check suites in CI, support Android source overrides, and update documentation and regression tests.
This commit is contained in:
lingjhf committed 2026-10-06 22:24:32 +08:00
1 parent ca2efdaf18
commit 152c051a29
57 files changed
+1858 -375

No files matched your search

+25
View File
@@ -0,0 +1,25 @@
"""Build, sign, audit and package the macOS production app as ZIP/DMG."""
import argparse
from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from common.process import ROOT, cli
from project_tools import project_environment
from release import build_release, print_artifact, require_macos
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('runtime', type=Path)
parser.add_argument('output', type=Path, nargs='?', default=ROOT / 'dist/macos')
args = parser.parse_args()
require_macos()
app, archive, dmg = build_release(args.runtime, args.output, environment=project_environment())
print(f'App: {app}')
print_artifact('Archive', archive)
print_artifact('DMG', dmg)
if __name__ == '__main__':
sys.exit(cli(main))
-85
View File
@@ -1,85 +0,0 @@
#!/bin/bash
set -euo pipefail
if [ "$#" -eq 1 ] && { [ "$1" = "--help" ] || [ "$1" = "-h" ]; }; then
echo "Usage: $0 <processing-runtime-directory> [output-directory]"
exit 0
fi
if [[ $# -lt 1 || $# -gt 2 ]]; then
echo "Usage: $0 <processing-runtime-directory> [output-directory]" >&2
exit 2
fi
repo_root="$(cd "$(dirname "$0")/../.." && pwd)"
runtime_root="$(cd "$1" && pwd)"
output_root="${2:-$repo_root/dist/macos}"
signing_identity="${CUTDEX_CODESIGN_IDENTITY:--}"
python="${PYTHON:-python3}"
flutter="${FLUTTER:-flutter}"
app="$repo_root/build/macos/Build/Products/Release-production/cutdex.app"
resources="$app/Contents/Resources"
embedded_runtime="$resources/processing"
mkdir -p "$output_root"
output_root="$(cd "$output_root" && pwd)"
archive="$output_root/cutdex-macos14-arm64.zip"
dmg="$output_root/cutdex-macos14-arm64.dmg"
if [[ -n "${CUTDEX_NOTARY_PROFILE:-}" && "$signing_identity" == "-" ]]; then
echo "CUTDEX_NOTARY_PROFILE requires a Developer ID signing identity" >&2
exit 1
fi
if [[ -n "${CUTDEX_UPDATE_FEED_URL:-}${CUTDEX_UPDATE_PUBLIC_KEY:-}" ]]; then
if [[ -z "${CUTDEX_UPDATE_FEED_URL:-}" || -z "${CUTDEX_UPDATE_PUBLIC_KEY:-}" ]]; then
echo "Set both CUTDEX_UPDATE_FEED_URL and CUTDEX_UPDATE_PUBLIC_KEY" >&2
exit 1
fi
fi
# Fail before the Flutter build if a worker or a transitive library is missing.
"$python" "$repo_root/tool/macos/check_macos_release.py" --runtime "$runtime_root"
cd "$repo_root"
bash "$repo_root/tool/macos/check_macos_build_target.sh" "$app/Contents/MacOS/cutdex"
rm -rf "$embedded_runtime"
"$flutter" build macos --release --flavor production \
--split-debug-info=build/symbols/macos
mkdir -p "$resources" "$output_root"
ditto "$runtime_root" "$embedded_runtime"
if [[ -n "${CUTDEX_UPDATE_FEED_URL:-}" ]]; then
"$python" "$repo_root/tool/macos/macos_updates.py" configure --app "$app" \
--feed "$CUTDEX_UPDATE_FEED_URL" --public-key "$CUTDEX_UPDATE_PUBLIC_KEY"
fi
bash "$repo_root/tool/macos/sign_macos_app.sh" "$app"
"$python" "$repo_root/tool/macos/check_macos_release.py" --app "$app" \
--report "$output_root/package-check.json"
rm -f "$archive"
ditto -c -k --sequesterRsrc --keepParent "$app" "$archive"
if [[ -n "${CUTDEX_NOTARY_PROFILE:-}" ]]; then
xcrun notarytool submit "$archive" \
--keychain-profile "$CUTDEX_NOTARY_PROFILE" --wait
xcrun stapler staple "$app"
rm -f "$archive"
ditto -c -k --sequesterRsrc --keepParent "$app" "$archive"
fi
bash "$repo_root/tool/macos/create_macos_dmg.sh" "$app" "$dmg"
if [[ -n "${CUTDEX_NOTARY_PROFILE:-}" ]]; then
xcrun notarytool submit "$dmg" \
--keychain-profile "$CUTDEX_NOTARY_PROFILE" --wait
xcrun stapler staple "$dmg"
xcrun stapler validate "$dmg"
fi
echo "App: $app"
echo "Archive: $archive"
shasum -a 256 "$archive"
echo "DMG: $dmg"
shasum -a 256 "$dmg"
+24
View File
@@ -0,0 +1,24 @@
"""Create and verify a compressed DMG with application and volume icons."""
import argparse
from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from common.process import cli
from project_tools import project_environment
from release import create_dmg, print_artifact, require_macos
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('app', type=Path)
parser.add_argument('output', type=Path)
args = parser.parse_args()
if args.output.suffix != '.dmg':
parser.error('output must have a .dmg extension')
require_macos()
print_artifact('DMG', create_dmg(args.app, args.output, environment=project_environment()))
if __name__ == '__main__':
sys.exit(cli(main))
-61
View File
@@ -1,61 +0,0 @@
#!/bin/bash
set -euo pipefail
if [ "$#" -eq 1 ] && { [ "$1" = "--help" ] || [ "$1" = "-h" ]; }; then
echo "Usage: $0 <cutdex.app> <output.dmg>"
exit 0
fi
if [[ $# -ne 2 ]]; then
echo "Usage: $0 <cutdex.app> <output.dmg>" >&2
exit 2
fi
app="$(cd "$(dirname "$1")" && pwd)/$(basename "$1")"
output="$2"
if [[ ! -f "$app/Contents/Info.plist" ]]; then
echo "Missing macOS application: $app" >&2
exit 1
fi
icon="$app/Contents/Resources/AppIcon.icns"
if [[ ! -f "$icon" ]]; then
echo "Missing application icon: $icon" >&2
exit 1
fi
if [[ "$output" != *.dmg ]]; then
echo "Output must have a .dmg extension: $output" >&2
exit 2
fi
mkdir -p "$(dirname "$output")"
output="$(cd "$(dirname "$output")" && pwd)/$(basename "$output")"
stage="$(mktemp -d "${TMPDIR:-/tmp}/cutdex-dmg.XXXXXX")"
source="$stage/source"
mount="$stage/mounted"
mounted=false
cleanup() {
if [[ "$mounted" == true ]]; then
hdiutil detach -quiet "$mount" || true
fi
rm -rf "$stage"
}
trap cleanup EXIT
mkdir "$source" "$mount"
ditto "$app" "$source/$(basename "$app")"
ln -s /Applications "$source/Applications"
ditto "$icon" "$source/.VolumeIcon.icns"
hdiutil create -quiet -format UDRW -volname Cutdex -srcfolder "$source" "$stage/uncompressed.dmg"
hdiutil attach -quiet -readwrite -nobrowse -mountpoint "$mount" "$stage/uncompressed.dmg"
mounted=true
xcrun SetFile -a C "$mount"
hdiutil detach -quiet "$mount"
mounted=false
hdiutil convert -quiet "$stage/uncompressed.dmg" -format UDZO -o "$output" -ov
hdiutil verify -quiet "$output"
swift "$(dirname "$0")/set_macos_file_icon.swift" "$icon" "$output"
echo "DMG: $output"
shasum -a 256 "$output"
+11 -8
View File
@@ -6,11 +6,14 @@ from pathlib import Path
import plistlib
import re
import shutil
import subprocess
import sys
import tempfile
from urllib.parse import urlsplit
import xml.etree.ElementTree as ET
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from common.process import cli, run
SPARKLE = 'http://www.andymatuschak.org/xml-namespaces/sparkle'
@@ -65,10 +68,10 @@ def validate_app(app, local=False):
for file in ['Sparkle', 'Autoupdate', 'Updater.app/Contents/MacOS/Updater']:
if not (framework / file).is_file():
raise ValueError(f'Missing Sparkle component: {file}')
subprocess.run(['codesign', '--verify', '--deep', '--strict', str(app)], check=True)
run(['codesign', '--verify', '--deep', '--strict', str(app)], cwd=Path.cwd(), check=True)
if not local:
subprocess.run(['xcrun', 'stapler', 'validate', str(app)], check=True)
subprocess.run(['spctl', '--assess', '--type', 'execute', str(app)], check=True)
run(['xcrun', 'stapler', 'validate', str(app)], cwd=Path.cwd(), check=True)
run(['spctl', '--assess', '--type', 'execute', str(app)], cwd=Path.cwd(), check=True)
return info
@@ -108,14 +111,14 @@ def publish(app, output, base_url, tools, key_file=None, local=False):
raise ValueError(f'Refusing to replace published archive: {archive}')
with tempfile.TemporaryDirectory(prefix='cutdex-update-') as directory:
stage = Path(directory)
subprocess.run(['ditto', '-c', '-k', '--sequesterRsrc', '--keepParent',
str(app), str(stage / filename)], check=True)
run(['ditto', '-c', '-k', '--sequesterRsrc', '--keepParent',
str(app), str(stage / filename)], cwd=Path.cwd(), check=True)
command = [str(tools / 'generate_appcast'), '--maximum-deltas', '0',
'--download-url-prefix', base_url.rstrip('/') + '/',
'-o', str(stage / 'appcast.xml')]
if key_file:
command.extend(['--ed-key-file', str(key_file)])
subprocess.run([*command, str(stage)], check=True)
run([*command, str(stage)], cwd=Path.cwd(), check=True)
tree = ET.parse(stage / 'appcast.xml')
if tree.findall(f'.//{{{SPARKLE}}}deltas'):
raise ValueError('This release pipeline only permits full updates')
@@ -154,4 +157,4 @@ def main():
if __name__ == '__main__':
main()
sys.exit(cli(main))
+161
View File
@@ -0,0 +1,161 @@
"""macOS release implementation shared by packaging and smoke tools."""
from pathlib import Path
import shutil
import sys
import tempfile
from common.build import build_application
from common.files import file_sha256
from common.process import ROOT, run
MACH_O = {b'\xfe\xed\xfa\xce', b'\xce\xfa\xed\xfe',
b'\xfe\xed\xfa\xcf', b'\xcf\xfa\xed\xfe',
b'\xca\xfe\xba\xbe', b'\xbe\xba\xfe\xca',
b'\xca\xfe\xba\xbf', b'\xbf\xba\xfe\xca'}
BUNDLES = {'.framework', '.appex', '.xpc', '.app'}
def require_macos():
if sys.platform != 'darwin':
raise RuntimeError('This operation requires macOS.')
def sign_app(app, *, environment, root=ROOT):
root = Path(root).resolve()
app = Path(app).resolve()
contents = app / 'Contents'
if not contents.is_dir():
raise RuntimeError('Missing macOS application bundle.')
paths = sorted(contents.rglob('*'))
if any(path.is_symlink() and not path.resolve().is_relative_to(app) for path in paths):
raise RuntimeError('Application symlink escapes the bundle.')
engine = contents / 'Frameworks/FlutterMacOS.framework/Versions/A/FlutterMacOS'
if not engine.is_file():
raise RuntimeError('Missing Flutter macOS engine.')
commands = run(['/usr/bin/otool', '-l', engine], cwd=root, env=environment,
capture_output=True, text=True, timeout=60).stdout
if 'path /usr/local/lib/. (offset' in commands:
run(['/usr/bin/install_name_tool', '-delete_rpath', '/usr/local/lib/.', engine], cwd=root, env=environment)
identity = environment.get('CUTDEX_CODESIGN_IDENTITY') or '-'
arguments = ['codesign', '--force', '--sign', identity]
arguments += ['--timestamp=none'] if identity == '-' else ['--timestamp', '--options', 'runtime']
for path in paths:
if path.is_file() and not path.is_symlink():
with path.open('rb') as stream:
native = stream.read(4) in MACH_O
if native:
run([*arguments, '--preserve-metadata=entitlements', path], cwd=root, env=environment)
bundles = [path for path in paths if path.is_dir() and not path.is_symlink() and path.suffix in BUNDLES]
for bundle in sorted(bundles, key=lambda path: (len(path.parts), str(path)), reverse=True):
run([*arguments, '--preserve-metadata=entitlements', bundle], cwd=root, env=environment)
run([*arguments, '--entitlements', root / 'macos/Runner/Release.entitlements', app], cwd=root, env=environment)
def create_dmg(app, output, *, environment, root=ROOT):
root = Path(root).resolve()
app, output = Path(app).resolve(), Path(output).absolute()
icon = app / 'Contents/Resources/AppIcon.icns'
if not (app / 'Contents/Info.plist').is_file() or not icon.is_file():
raise RuntimeError('Missing macOS application or application icon.')
if output.suffix != '.dmg':
raise RuntimeError('Output must have a .dmg extension.')
if output.resolve().is_relative_to(app):
raise RuntimeError('DMG output must be outside the application bundle.')
output.parent.mkdir(parents=True, exist_ok=True)
stage = Path(tempfile.mkdtemp(prefix='cutdex-dmg-', dir=environment.get('TMPDIR'))).resolve()
source, mount, image = stage / 'source', stage / 'mounted', stage / 'uncompressed.dmg'
mounted = False
try:
source.mkdir()
mount.mkdir()
run(['ditto', app, source / app.name], cwd=root, env=environment)
(source / 'Applications').symlink_to('/Applications', target_is_directory=True)
run(['ditto', icon, source / '.VolumeIcon.icns'], cwd=root, env=environment)
run(['hdiutil', 'create', '-quiet', '-format', 'UDRW', '-volname', 'Cutdex',
'-srcfolder', source, image], cwd=root, env=environment)
run(['hdiutil', 'attach', '-quiet', '-readwrite', '-nobrowse', '-mountpoint', mount, image], cwd=root, env=environment)
mounted = True
run(['xcrun', 'SetFile', '-a', 'C', mount], cwd=root, env=environment)
run(['hdiutil', 'detach', '-quiet', mount], cwd=root, env=environment)
mounted = False
run(['hdiutil', 'convert', '-quiet', image, '-format', 'UDZO', '-o', output, '-ov'], cwd=root, env=environment)
run(['hdiutil', 'verify', '-quiet', output], cwd=root, env=environment)
run(['swift', root / 'tool/macos/set_macos_file_icon.swift', icon, output], cwd=root, env=environment)
finally:
if mounted:
detached = run(['hdiutil', 'detach', '-quiet', mount], cwd=root, env=environment,
check=False, capture_output=True)
mounted = detached.returncode != 0
if mounted:
print(f'DMG is still mounted; temporary directory retained: {stage}', file=sys.stderr)
else:
shutil.rmtree(stage)
return output
def _archive(app, output, environment, root):
output.unlink(missing_ok=True)
run(['ditto', '-c', '-k', '--sequesterRsrc', '--keepParent', app, output], cwd=root, env=environment)
def _notarize(path, profile, environment, root):
run(['xcrun', 'notarytool', 'submit', path, '--keychain-profile', profile, '--wait'], cwd=root, env=environment)
run(['xcrun', 'stapler', 'staple', path], cwd=root, env=environment)
def build_release(runtime, output, *, environment, root=ROOT):
root, runtime, output = Path(root).resolve(), Path(runtime).resolve(), Path(output).resolve()
app = (root / 'build/macos/Build/Products/Release-production/cutdex.app').resolve()
if not app.is_relative_to(root):
raise RuntimeError('Build product must remain inside the project.')
if not runtime.is_dir() or runtime.is_relative_to(app):
raise RuntimeError('Provide a processing directory outside the application bundle.')
if output.is_relative_to(app) or output.is_relative_to(runtime):
raise RuntimeError('Output must be outside the application and processing directories.')
profile = environment.get('CUTDEX_NOTARY_PROFILE')
if profile and (environment.get('CUTDEX_CODESIGN_IDENTITY') or '-') == '-':
raise RuntimeError('CUTDEX_NOTARY_PROFILE requires a Developer ID signing identity.')
feed, key = environment.get('CUTDEX_UPDATE_FEED_URL'), environment.get('CUTDEX_UPDATE_PUBLIC_KEY')
if bool(feed) != bool(key):
raise RuntimeError('Set both CUTDEX_UPDATE_FEED_URL and CUTDEX_UPDATE_PUBLIC_KEY.')
python = sys.executable
run([python, root / 'tool/macos/check_macos_release.py', '--runtime', runtime], cwd=root, env=environment)
run(['/bin/sh', root / 'tool/macos/check_macos_build_target.sh', app / 'Contents/MacOS/cutdex'], cwd=root, env=environment)
embedded = app / 'Contents/Resources/processing'
if not embedded.parent.resolve().is_relative_to(app):
raise RuntimeError('Embedded runtime escapes the application bundle.')
# A stale bundle may contain links. Never recursively delete their targets.
if embedded.is_symlink():
embedded.unlink()
elif embedded.exists():
if not embedded.resolve().is_relative_to(app):
raise RuntimeError('Embedded runtime escapes the application bundle.')
shutil.rmtree(embedded)
build_application('macos', environment=environment, root=root)
if not embedded.parent.resolve().is_relative_to(app):
raise RuntimeError('Embedded runtime escapes the application bundle.')
embedded.parent.mkdir(parents=True, exist_ok=True)
output.mkdir(parents=True, exist_ok=True)
run(['ditto', runtime, embedded], cwd=root, env=environment)
if feed:
run([python, root / 'tool/macos/macos_updates.py', 'configure', '--app', app,
'--feed', feed, '--public-key', key], cwd=root, env=environment)
sign_app(app, environment=environment, root=root)
run([python, root / 'tool/macos/check_macos_release.py', '--app', app,
'--report', output / 'package-check.json'], cwd=root, env=environment)
archive, dmg = output / 'cutdex-macos14-arm64.zip', output / 'cutdex-macos14-arm64.dmg'
_archive(app, archive, environment, root)
if profile:
run(['xcrun', 'notarytool', 'submit', archive, '--keychain-profile', profile, '--wait'], cwd=root, env=environment)
run(['xcrun', 'stapler', 'staple', app], cwd=root, env=environment)
_archive(app, archive, environment, root)
create_dmg(app, dmg, environment=environment, root=root)
if profile:
_notarize(dmg, profile, environment, root)
run(['xcrun', 'stapler', 'validate', dmg], cwd=root, env=environment)
return app, archive, dmg
def print_artifact(label, path):
print(f'{label}: {path}')
print(f'{file_sha256(path)} {path}')
+21
View File
@@ -0,0 +1,21 @@
"""Normalize engine paths and sign native files and nested macOS bundles."""
import argparse
from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from common.process import cli
from project_tools import project_environment
from release import require_macos, sign_app
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('app', type=Path)
args = parser.parse_args()
require_macos()
sign_app(args.app, environment=project_environment())
if __name__ == '__main__':
sys.exit(cli(main))
-44
View File
@@ -1,44 +0,0 @@
#!/bin/bash
set -euo pipefail
if [ "$#" -eq 1 ] && { [ "$1" = "--help" ] || [ "$1" = "-h" ]; }; then
echo "Usage: $0 <app-bundle>"
exit 0
fi
if [[ $# != 1 ]]; then
echo "Usage: $0 <app-bundle>" >&2
exit 2
fi
repo_root="$(cd "$(dirname "$0")/../.." && pwd)"
app="$1"
signing_identity="${CUTDEX_CODESIGN_IDENTITY:--}"
# Flutter's prebuilt engine carries an unused Homebrew search path. Remove it
# from our copy before signing; the audit rejects any remaining external paths.
engine="$app/Contents/Frameworks/FlutterMacOS.framework/Versions/A/FlutterMacOS"
if /usr/bin/otool -l "$engine" | grep -F 'path /usr/local/lib/. (offset' >/dev/null; then
/usr/bin/install_name_tool -delete_rpath /usr/local/lib/. "$engine"
fi
codesign_args=(--force --sign "$signing_identity")
if [[ "$signing_identity" == "-" ]]; then
codesign_args+=(--timestamp=none)
else
codesign_args+=(--timestamp --options runtime)
fi
while IFS= read -r binary; do
if file "$binary" | grep -q 'Mach-O'; then
codesign "${codesign_args[@]}" --preserve-metadata=entitlements "$binary"
fi
done < <(find "$app/Contents" -type f -print | sort)
# Every nested bundle must use the same identity as the outer app. Mixing the
# Xcode development signature with an ad-hoc or Developer ID signature causes
# dyld to reject FlutterMacOS.framework on a clean launch.
while IFS= read -r bundle; do
codesign "${codesign_args[@]}" --preserve-metadata=entitlements "$bundle"
done < <(find "$app/Contents" -type d \( \
-name '*.framework' -o -name '*.appex' -o -name '*.xpc' -o -name '*.app' \
\) -print | awk '{ print length, $0 }' | sort -rn | cut -d' ' -f2-)
codesign "${codesign_args[@]}" \
--entitlements "$repo_root/macos/Runner/Release.entitlements" "$app"
+15 -10
View File
@@ -2,19 +2,23 @@
The JSON config supplies WHISPER_SOURCE, M2M100_SOURCE, MELBAND_SOURCE and
CUTDEX_ASR_FIXTURE. Models are copied into the app-managed resource layout.
Run build_macos_release.sh afterwards to produce the normal application.
Run build_macos_release.py afterwards to produce the normal application.
"""
import argparse
import json
import os
import shutil
from pathlib import Path
import subprocess
import tempfile
import sys
from functools import partial
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from project_tools import project_environment, tool_command
from common.process import cli, run as run_command
from release import sign_app
def run(command, **kwargs):
subprocess.run(list(map(str, command)), check=True, timeout=900, **kwargs)
run = partial(run_command, timeout=900)
def main():
@@ -24,14 +28,15 @@ def main():
parser.add_argument('--report', type=Path, required=True)
args = parser.parse_args()
repo = Path(__file__).resolve().parents[2]
config = json.loads(args.config.read_text())
config = json.loads(args.config.read_text(encoding='utf-8'))
model_keys = ['WHISPER_SOURCE', 'M2M100_SOURCE', 'MELBAND_SOURCE']
for key in model_keys + ['CUTDEX_ASR_FIXTURE']:
if not Path(config[key]).is_absolute() or not Path(config[key]).exists():
raise ValueError(f'Missing absolute input path: {key}')
runtime = args.runtime.resolve()
run([os.environ.get('FLUTTER', 'flutter'), 'build', 'macos', '--release',
'--flavor=production', '--target=tool/testing/release_smoke.dart'], cwd=repo)
environment = project_environment()
run(tool_command('flutter', ['build', 'macos', '--release',
'--flavor=production', '--target=tool/testing/release_smoke.dart']), cwd=repo, env=environment)
with tempfile.TemporaryDirectory(prefix='cutdex relocated release ') as temporary:
root = Path(temporary)
app = root / 'cutdex.app'
@@ -41,8 +46,8 @@ def main():
if embedded.exists():
shutil.rmtree(embedded)
run(['/usr/bin/ditto', runtime, embedded])
run(['/bin/bash', repo / 'tool/macos/sign_macos_app.sh', app])
run([os.environ.get('PYTHON', 'python3'), repo / 'tool/macos/check_macos_release.py', '--app', app])
sign_app(app, environment=environment)
run([sys.executable, repo / 'tool/macos/check_macos_release.py', '--app', app], env=environment)
results = []
for configured in [False, True]:
home = root / ('with-models' if configured else 'without-models')
@@ -79,4 +84,4 @@ def main():
if __name__ == '__main__':
main()
sys.exit(cli(main))
+7 -3
View File
@@ -3,10 +3,14 @@
import argparse
from functools import partial
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
import os
from pathlib import Path
import plistlib
import subprocess
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from project_tools import project_environment
from release import sign_app
from macos_updates import configure, publish
@@ -24,6 +28,7 @@ class UpdateHandler(SimpleHTTPRequestHandler):
def prepare(source, root, tools, port):
repository = Path(__file__).resolve().parents[2]
root = root.resolve()
environment = project_environment()
public = root / 'public'
keys = root / 'keys'
if (root / 'installed').exists() or public.exists():
@@ -43,8 +48,7 @@ def prepare(source, root, tools, port):
bundle['CFBundleVersion'] = version
path.write_bytes(plistlib.dumps(bundle))
configure(app, feed, public_key, local=True)
subprocess.run(['bash', str(repository / 'tool/macos/sign_macos_app.sh'), str(app)],
env={**os.environ, 'CUTDEX_CODESIGN_IDENTITY': '-'}, check=True)
sign_app(app, environment={**environment, 'CUTDEX_CODESIGN_IDENTITY': '-'})
publish(root / 'candidate/cutdex.app', public, f'http://localhost:{port}',
tools.resolve(), keys / 'private.key', local=True)
print(f'Open: {root / "installed/cutdex.app"}', flush=True)
+40 -1
View File
@@ -2,6 +2,7 @@
import base64
from pathlib import Path
import plistlib
import subprocess
import tempfile
import unittest
from unittest.mock import patch
@@ -51,6 +52,44 @@ class UpdateConfigurationTests(unittest.TestCase):
class PublicationVersionTests(unittest.TestCase):
def test_publication_writes_signed_archive_and_preserves_feed_on_tool_failure(self):
for failure in (False, True):
with self.subTest(failure=failure), tempfile.TemporaryDirectory() as directory:
output = Path(directory)
feed = output / 'appcast.xml'
original = (f'<rss xmlns:sparkle="{SPARKLE}"><channel><item>'
'<sparkle:version>1</sparkle:version>'
'</item></channel></rss>').encode()
feed.write_bytes(original)
generated = (f'<rss xmlns:sparkle="{SPARKLE}"><channel><item>'
'<sparkle:version>2</sparkle:version>'
'<enclosure sparkle:edSignature="test-signature"/>'
'</item></channel></rss>').encode()
def generate(command, *, cwd, check):
self.assertEqual(cwd, Path.cwd())
self.assertTrue(check)
if command[0] == 'ditto':
Path(command[-1]).write_bytes(b'archive')
elif failure:
raise subprocess.CalledProcessError(19, command)
else:
Path(command[command.index('-o') + 1]).write_bytes(generated)
with patch('macos_updates.validate_app', return_value={'CFBundleVersion': '2'}), \
patch('macos_updates.run', side_effect=generate):
if failure:
with self.assertRaises(subprocess.CalledProcessError) as raised:
publish(Path('app'), output, 'https://example.com/', Path('tools'))
self.assertEqual(raised.exception.returncode, 19)
self.assertEqual(feed.read_bytes(), original)
self.assertEqual(list(output.glob('*.zip')), [])
else:
archive = publish(Path('app'), output, 'https://example.com/', Path('tools'))
self.assertEqual(archive.read_bytes(), b'archive')
self.assertEqual(feed.read_bytes(), generated)
self.assertFalse((output / 'appcast.xml.pending').exists())
def test_older_or_equivalent_build_cannot_replace_current_feed(self):
for current, candidate in [('900002', '900001'), ('2', '2.0'), ('2.10', '2.9')]:
with self.subTest(current=current, candidate=candidate), tempfile.TemporaryDirectory() as directory:
@@ -70,7 +109,7 @@ class PublicationVersionTests(unittest.TestCase):
'<enclosure sparkle:edSignature="test-signature"/>'
'</item></channel></rss>')
with patch('macos_updates.validate_app', return_value={'CFBundleVersion': candidate}), \
patch('macos_updates.subprocess.run', side_effect=generate) as run:
patch('macos_updates.run', side_effect=generate) as run:
with self.assertRaisesRegex(ValueError, 'newer'):
publish(Path('app'), output, 'https://example.com/', Path('tools'))
run.assert_not_called()
+196
View File
@@ -0,0 +1,196 @@
"""Exercise macOS release ordering and failure recovery without native tools."""
import contextlib
import io
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import release
from common.process import cli
class ReleaseTests(unittest.TestCase):
def setUp(self):
temporary = tempfile.TemporaryDirectory(prefix='cutdex macos flow ')
self.addCleanup(temporary.cleanup)
self.root = Path(temporary.name).resolve()
self.runtime = self.root / 'runtime'
(self.runtime / 'bin').mkdir(parents=True)
(self.runtime / 'bin/worker').write_bytes(b'\xcf\xfa\xed\xfeworker')
self.output = self.root / 'dist'
self.app = self.root / 'build/macos/Build/Products/Release-production/cutdex.app'
self.environment = {'TMPDIR': str(self.root), 'CUTDEX_TEST_CONFIG': 'shared'}
self.calls = []
self.mounts = []
self.archives = []
self.fail = lambda args: False
self.patches = [patch('release.run', side_effect=self.run_native),
patch('release.build_application', side_effect=self.build),
patch.object(Path, 'symlink_to', self.fake_link)]
for mock in self.patches:
mock.start()
self.addCleanup(mock.stop)
@staticmethod
def fake_link(path, target, **kwargs):
# Native link privilege is irrelevant to process-order/failure tests.
path.write_text(str(target), encoding='utf-8')
def make_app(self):
contents = self.app / 'Contents'
(contents / 'Resources').mkdir(parents=True, exist_ok=True)
(contents / 'Info.plist').write_bytes(b'plist')
(contents / 'Resources/AppIcon.icns').write_bytes(b'icon')
engine = contents / 'Frameworks/FlutterMacOS.framework/Versions/A/FlutterMacOS'
engine.parent.mkdir(parents=True, exist_ok=True)
engine.write_bytes(b'\xcf\xfa\xed\xfeengine')
nested = contents / 'Frameworks/Outer.framework/Helpers/Inner.xpc'
nested.mkdir(parents=True, exist_ok=True)
(nested / 'helper').write_bytes(b'\xca\xfe\xba\xbehelper')
def build(self, platform, **kwargs):
self.assertEqual(kwargs['root'], self.root)
self.calls.append((['build', platform], kwargs['environment']))
self.make_app()
return subprocess.CompletedProcess([], 0)
def run_native(self, command, *, env, cwd, check=True, **kwargs):
self.assertEqual(cwd, self.root)
args = list(map(str, command))
self.calls.append((args, env))
if self.fail(args):
if check:
raise subprocess.CalledProcessError(23, args)
return subprocess.CompletedProcess(args, 23, '', '')
if args[0] == 'ditto':
if '-c' in args:
output = Path(args[-1])
stapled = (Path(args[-2]) / 'stapled').exists()
output.write_bytes(b'archive-stapled' if stapled else b'archive')
self.archives.append(stapled)
elif Path(args[1]).is_dir():
shutil.copytree(args[1], args[2])
else:
shutil.copy2(args[1], args[2])
if args[:2] == ['hdiutil', 'attach']:
self.mounts.append(Path(args[args.index('-mountpoint') + 1]))
if args[:2] == ['hdiutil', 'convert']:
Path(args[args.index('-o') + 1]).write_bytes(b'dmg')
if args[:3] == ['xcrun', 'stapler', 'staple'] and Path(args[-1]).is_dir():
(Path(args[-1]) / 'stapled').write_text('stapled')
if '--report' in args:
Path(args[args.index('--report') + 1]).write_text('{}')
return subprocess.CompletedProcess(args, 0, 'path /usr/local/lib/. (offset 12)', '')
def build_release(self):
return release.build_release(self.runtime, self.output,
environment=self.environment, root=self.root)
def test_ad_hoc_release_audits_before_build_and_emits_valid_artifacts(self):
app, archive, dmg = self.build_release()
commands = [args for args, env in self.calls]
self.assertIn('--runtime', commands[0])
self.assertIn('check_macos_build_target.sh', commands[1][1])
self.assertEqual(commands[2], ['build', 'macos'])
self.assertTrue((app / 'Contents/Resources/processing/bin/worker').is_file())
self.assertEqual(archive.read_bytes(), b'archive')
self.assertEqual(dmg.read_bytes(), b'dmg')
self.assertTrue((self.output / 'package-check.json').is_file())
self.assertFalse(any('notarytool' in command for command in commands))
self.assertTrue(all(env is self.environment for args, env in self.calls))
self.assertTrue(all(not mount.parent.exists() for mount in self.mounts))
def test_signing_preserves_metadata_and_signs_children_before_parent(self):
self.make_app()
release.sign_app(self.app, environment=self.environment, root=self.root)
commands = [args for args, env in self.calls]
self.assertEqual(commands[1][:3], ['/usr/bin/install_name_tool', '-delete_rpath', '/usr/local/lib/.'])
signs = [args for args in commands if args[0] == 'codesign']
nested = self.app / 'Contents/Frameworks/Outer.framework/Helpers/Inner.xpc'
outer = self.app / 'Contents/Frameworks/Outer.framework'
targets = [args[-1] for args in signs]
self.assertLess(targets.index(str(nested)), targets.index(str(outer)))
self.assertEqual(targets[-1], str(self.app))
self.assertTrue(all('--preserve-metadata=entitlements' in args for args in signs[:-1]))
self.assertIn('--entitlements', signs[-1])
self.assertTrue(all('--timestamp=none' in args for args in signs))
def test_notarization_rebuilds_zip_after_stapling_app(self):
self.environment.update(CUTDEX_CODESIGN_IDENTITY='Developer ID with spaces', CUTDEX_NOTARY_PROFILE='profile')
app, archive, dmg = self.build_release()
self.assertEqual(self.archives, [False, True])
self.assertEqual(archive.read_bytes(), b'archive-stapled')
commands = [args for args, env in self.calls]
signs = [args for args in commands if args[0] == 'codesign']
self.assertTrue(all('--options' in args and 'runtime' in args for args in signs))
self.assertEqual(commands[-1], ['xcrun', 'stapler', 'validate', str(dmg)])
def test_invalid_notarization_or_partial_update_config_fails_before_build(self):
for config in [{'CUTDEX_NOTARY_PROFILE': 'profile'}, {'CUTDEX_UPDATE_FEED_URL': 'https://example.com/feed'},
{'CUTDEX_UPDATE_PUBLIC_KEY': 'key'}]:
with self.subTest(config=config):
self.environment = config
with self.assertRaises(RuntimeError):
self.build_release()
self.assertEqual(self.calls, [])
self.assertFalse(self.output.exists())
def test_audit_failure_preserves_exit_code_and_prevents_build(self):
self.fail = lambda args: '--runtime' in args
with contextlib.redirect_stderr(io.StringIO()) as diagnostics:
self.assertEqual(cli(self.build_release), 23)
self.assertNotIn('build', [args[0] for args, env in self.calls])
self.assertNotIn('shared', diagnostics.getvalue())
def test_native_sign_failure_prevents_artifact_creation(self):
self.fail = lambda args: args[0] == 'codesign'
with self.assertRaises(subprocess.CalledProcessError):
self.build_release()
self.assertEqual(self.archives, [])
self.assertFalse((self.output / 'cutdex-macos14-arm64.dmg').exists())
def test_dmg_failure_detaches_and_cleans_owned_stage(self):
self.make_app()
self.fail = lambda args: args[:2] == ['xcrun', 'SetFile']
with self.assertRaises(subprocess.CalledProcessError):
release.create_dmg(self.app, self.output / 'failure.dmg',
environment=self.environment, root=self.root)
self.assertEqual(len(self.mounts), 1)
self.assertFalse(self.mounts[0].parent.exists())
self.assertEqual(self.calls[-1][0], ['hdiutil', 'detach', '-quiet', str(self.mounts[0])])
def test_failed_detach_retains_stage_without_deleting_mounted_contents(self):
self.make_app()
self.fail = lambda args: args[:2] in (['xcrun', 'SetFile'], ['hdiutil', 'detach'])
with contextlib.redirect_stderr(io.StringIO()) as diagnostics:
with self.assertRaises(subprocess.CalledProcessError):
release.create_dmg(self.app, self.output / 'failure.dmg',
environment=self.environment, root=self.root)
self.assertTrue(self.mounts[0].parent.is_dir())
self.assertIn('temporary directory retained', diagnostics.getvalue())
def test_input_runtime_inside_app_is_rejected_before_deletion(self):
self.make_app()
runtime = self.app / 'Contents/Resources/processing'
runtime.mkdir()
marker = runtime / 'worker'
marker.write_bytes(b'preserve')
with self.assertRaises(RuntimeError):
release.build_release(runtime, self.output, environment=self.environment, root=self.root)
self.assertEqual(marker.read_bytes(), b'preserve')
self.assertEqual(self.calls, [])
def test_dmg_rejects_output_inside_app_before_native_calls(self):
self.make_app()
with self.assertRaises(RuntimeError):
release.create_dmg(self.app, self.app / 'output.dmg', environment=self.environment)
self.assertEqual(self.calls, [])
if __name__ == '__main__':
unittest.main()