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
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:
1 parent
ca2efdaf18
commit
152c051a29
57 files changed
+1858
-375
No files matched your search
+55
-12
@@ -1,6 +1,6 @@
|
||||
# 仓库工具
|
||||
|
||||
使用 Python 3.11 或更新版本,在 cutdex 仓库根目录运行下列入口。通用检查为 `python3 tool/check.py`;可用 `FLUTTER` 指定 Flutter 可执行文件。它检查 Python/Shell 语法、Python 业务/CLI 单测及 macOS Swift 辅助工具回归和 `lib test integration_test test_driver tool` 的 Dart 静态分析,只会在临时目录编译 Swift 测试辅助程序并生成测试密钥,不执行应用打包、签名、上传或真实模型推理。Windows 没有 bash 时会明确跳过 Shell 语法检查。
|
||||
使用 Python 3.11 或更新版本,先在 cutdex 仓库根目录运行 `fvm use`。通用检查为 `python3 tool/check.py`,与 CI 共用 `analyze`、`flutter`、`tools` 三个检查套件:严格静态分析、应用及内部包 Flutter 测试、源码卫生与 Python/Shell/CLI 工具检查。可通过 `--suite analyze|flutter|tools` 单独重试;macOS Swift 回归仅在宿主能力可用时运行。检查不执行应用打包、上传或真实模型推理。Windows 没有 bash 时会明确跳过 Shell 语法检查。
|
||||
|
||||
## 源码检查
|
||||
|
||||
@@ -8,32 +8,74 @@
|
||||
|
||||
## 稳定客户端入口
|
||||
|
||||
`dart run tool/mcp_stdio.dart` 由外部 MCP 客户端启动,通过 `CUTDEX_MCP_PORT` 和 `CUTDEX_MCP_TOKEN` 连接正在运行的 Cutdex。客户端配置见 [MCP 连接指南](../docs/mcp-connection.md),可用工具与参数由客户端连接后发现。
|
||||
先在仓库根目录运行 `fvm use`,按 `.fvmrc` 准备项目 SDK。本地 Flutter 启动与构建
|
||||
使用 `fvm dart tool/flutter_local.dart <Flutter 参数>`,或 VS Code
|
||||
的 Debug/Profile/Release 启动项。入口将 `.env.local` 注入 Flutter 子进程,并保留
|
||||
标准输入输出、全部参数和退出码;CI 不读取该文件。配置与优先级见
|
||||
[开发指南](../docs/development.md#运行应用)。`tool/flutter-local.bat` 和
|
||||
`tool/flutter-local.sh` 是 IDE 使用的薄启动入口;两者均通过 `.fvm/flutter_sdk`
|
||||
使用项目的 Dart/Flutter,不读取 `FLUTTER` 环境变量或回退到全局 SDK。
|
||||
|
||||
Python 构建工具通过 `project_tools.py` → `project_tools.dart` 共用同一个 Dart
|
||||
环境加载器。本地始终使用项目 SDK;CI 使用已通过 `.fvmrc` 校验的预装 SDK,
|
||||
且跳过 `.env.local`。SDK 的 bin 放在子进程 PATH 首位,跨语言测试也使用相同版本。
|
||||
`python3 tool/project_tools.py dart <参数>` 可运行 Dart 工具,保留当前工作目录。
|
||||
macOS 打包在整个流水线开始前加载配置,签名、公证和更新配置均可从文件读取。
|
||||
|
||||
## 工具结构
|
||||
|
||||
```text
|
||||
tool/
|
||||
build.py / check.py 应用编译与检查入口
|
||||
project_tools.py SDK 与环境加载的 Python 适配
|
||||
common/ 构建预设、公共进程调用、退出码和文件哈希
|
||||
macos/ macOS 发布、签名、DMG 与平台验证
|
||||
windows/ Windows 打包、更新与 Sandbox 验证
|
||||
gitea/ CI 与 Release 产物管理
|
||||
```
|
||||
|
||||
平台 CLI 只解析参数并调用实现。macOS 的共享发布实现位于 `macos/release.py`,
|
||||
调用 `common/build.py` 的同一构建预设;`build.py` 只负责命令行解析,签名和更新
|
||||
验证也复用平台实现。公共构建 API 的 `root` 决定 SDK、环境加载器与默认工作目录,
|
||||
独立验证工程可通过 `cwd` 单独指定构建目录。`common/process.py`
|
||||
统一子进程失败退出码与诊断,不输出完整命令参数或环境。公共调用默认不增加超时,
|
||||
真实 smoke 检查可自行限定时长。`common/files.py` 在各平台按流计算文件 SHA256。
|
||||
HTTP 传输和平台格式验证保留在所属模块中。
|
||||
|
||||
应用构建统一使用 `python3 tool/build.py android|windows|macos`。默认是
|
||||
production/release;可选 `--flavor development`、`--mode debug|profile|release`,
|
||||
Android 可选 `--split-per-abi`,附加 Flutter 参数放在 `--` 后。Android 固定支持
|
||||
ARM64/x86_64,macOS 默认输出分离符号。CI 与本地发布共用这些预设;真实更新
|
||||
验证仍保留独立工程、测试入口和专用版本号。
|
||||
|
||||
`fvm dart run tool/mcp_stdio.dart` 由外部 MCP 客户端启动,通过 `CUTDEX_MCP_PORT` 和 `CUTDEX_MCP_TOKEN` 连接正在运行的 Cutdex。客户端配置见 [MCP 连接指南](../docs/mcp-connection.md),可用工具与参数由客户端连接后发现。
|
||||
|
||||
## macOS
|
||||
|
||||
| 脚本 | 责任 |
|
||||
| --- | --- |
|
||||
| macos/build_macos_release.sh | 检查 processing 包、构建 production、签名、审计、生成 ZIP/DMG;可按配置公证 |
|
||||
| macos/build_macos_release.py | 检查 processing 包、构建 production、签名、审计、生成 ZIP/DMG;可按配置公证 |
|
||||
| macos/check_macos_build_target.sh | 拒绝覆盖正在运行的目标 App;Xcode 构建阶段直接调用 |
|
||||
| macos/check_macos_release.py | 检查 arm64、macOS 14 最低版本约束、动态依赖、签名与 worker |
|
||||
| macos/sign_macos_app.sh | 处理引擎搜索路径并统一签名嵌套二进制与 App |
|
||||
| macos/create_macos_dmg.sh | 从现有 App 生成安装磁盘映像 |
|
||||
| macos/sign_macos_app.py | 处理引擎搜索路径并统一签名嵌套二进制与 App |
|
||||
| macos/create_macos_dmg.py | 从现有 App 生成安装磁盘映像 |
|
||||
| macos/release.py | 构建、签名、DMG、公证的共享实现,供平台 CLI 和验证工具调用 |
|
||||
| macos/set_macos_file_icon.swift | DMG 脚本调用的文件图标辅助程序 |
|
||||
| macos/macos_updates.py | 配置更新源并生成应用更新产物 |
|
||||
| macos/test_macos_release.py | 构建独立 smoke App,搬迁后验证无模型及有模型启动 |
|
||||
| macos/test_check_macos_release.py | 需要真实 processing 包的发布审计故障注入测试 |
|
||||
| macos/test_macos_updates_unit.py | 更新配置、版本与发布规则的纯 Python 单测 |
|
||||
| macos/test_release_unit.py | 使用模拟系统命令验证发布顺序、签名策略与失败清理,无需 macOS |
|
||||
| macos/test_macos_updates.py | 本地更新模拟与测试服务器,需 App/Sparkle 工具 |
|
||||
| macos/sparkle_test_key.swift | 更新模拟专用临时密钥工具,不写系统钥匙串 |
|
||||
|
||||
正常应用打包入口:
|
||||
|
||||
```sh
|
||||
bash tool/macos/build_macos_release.sh /absolute/path/to/processing-runtime
|
||||
python3 tool/macos/build_macos_release.py /absolute/path/to/processing-runtime
|
||||
```
|
||||
|
||||
默认输出到 `dist/macos/`,第二个参数可指定输出目录。`FLUTTER`、`PYTHON` 可指定工具;最终签名使用 `CUTDEX_CODESIGN_IDENTITY`,公证使用 `CUTDEX_NOTARY_PROFILE`。开发签名配置见 [开发指南](../docs/development.md)。
|
||||
默认输出到 `dist/macos/`,第二个参数可指定输出目录。Flutter 使用项目 FVM SDK,子工具复用当前 Python 解释器;最终签名使用 `CUTDEX_CODESIGN_IDENTITY`,公证使用 `CUTDEX_NOTARY_PROFILE`。这些构建配置可放在 `.env.local`。开发签名配置见 [开发指南](../docs/development.md)。
|
||||
|
||||
发布验证使用 `check_macos_release.py` 和 `test_macos_release.py`,参数见 `--help`。后者构建独立测试入口,完成后重新打包正常应用;搬迁启动不能代替干净 Mac 上的安装验证。
|
||||
|
||||
@@ -53,7 +95,7 @@ bash tool/macos/build_macos_release.sh /absolute/path/to/processing-runtime
|
||||
正常发行包组装入口,构建机还需安装 `pefile`:
|
||||
|
||||
```powershell
|
||||
flutter build windows --release --flavor production
|
||||
python tool/build.py windows
|
||||
python tool/windows/package_windows_release.py `
|
||||
--app build/windows/x64/production/runner/Release `
|
||||
--processing D:\packages\processing `
|
||||
@@ -80,7 +122,7 @@ deskup 0.3.0 的开发更新源由 Dart 参数配置。Windows 的编译期配
|
||||
## 诊断与共享测试入口
|
||||
|
||||
- `diagnostics/frame_budget.py`:读取 `CUTDEX_FRAME_TIMINGS` JSONL,可带阶段标记文件;报告帧耗时。
|
||||
- `diagnostics/benchmark_diagnostic_store.dart`:无输入数据,比较逐条刷盘与默认批写策略的合成日志突发;`--samples=7` 设置测量轮数,JSON 输出包含同步记录耗时、排空耗时、定时器间隔与持久化追加次数。可先 `dart compile exe tool/diagnostics/benchmark_diagnostic_store.dart -o /tmp/cutdex-diagnostic-benchmark` 再运行可执行文件,排除 JIT 预热影响;不测量实际剪辑帧率。合成突发使用 320 项队列容量,其中 40 项预留给错误。
|
||||
- `diagnostics/benchmark_diagnostic_store.dart`:无输入数据,比较逐条刷盘与默认批写策略的合成日志突发;`--samples=7` 设置测量轮数,JSON 输出包含同步记录耗时、排空耗时、定时器间隔与持久化追加次数。可先 `fvm dart compile exe tool/diagnostics/benchmark_diagnostic_store.dart -o /tmp/cutdex-diagnostic-benchmark` 再运行可执行文件,排除 JIT 预热影响;不测量实际剪辑帧率。合成突发使用 320 项队列容量,其中 40 项预留给错误。
|
||||
- `diagnostics/benchmark_agent_context.dart`:读取第一个参数指定的 AgentMessage JSON 数组,比较完整历史和 Harness 投影的估算 token/字节量。
|
||||
- `testing/release_smoke.dart`:macOS/Windows 发布测试共用的 Flutter 入口,验证导出、翻译和资源配置。测试 App 不得分发;结束后使用 `lib/main.dart` 重建正式 App。
|
||||
|
||||
@@ -88,8 +130,9 @@ deskup 0.3.0 的开发更新源由 Dart 参数配置。Windows 的编译期配
|
||||
|
||||
## 语言与入口约定
|
||||
|
||||
- Shell 负责系统命令编排与临时资源清理;JSON、XML、依赖和发布规则集中在 Python。签名脚本中的文件筛选与命令排序属于签名流程,保持单一实现。
|
||||
- Swift 处理原生能力;PowerShell 处理 Windows 桌面与进程环境;Dart 入口用于应用连接与 Flutter 测试。
|
||||
- Python 负责构建和发布编排、临时资源清理及格式/依赖验证;参数、环境和进程调用使用公共层。签名筛选和顺序只有一份 macOS 实现。
|
||||
- Shell/BAT 保留 IDE 启动入口及 Xcode/原生平台检查,PowerShell 保留 Windows 环境准备和 Sandbox;Flutter 自动生成的脚本由 Flutter 管理。
|
||||
- Swift 处理原生能力;Dart 入口用于应用连接、本地环境加载、Flutter 启动与测试。
|
||||
- 普通 Python、Shell、Swift 和 Dart 诊断入口支持 `--help`(Shell/Swift/Dart 也支持 `-h`),帮助不启动构建、服务器或发布操作。PowerShell 使用 `Get-Help <脚本> -Full`。
|
||||
- 普通 CLI:成功/帮助为 0,参数格式或数量错误为 2,工具主动判定的运行失败为 1。外部子命令失败保留其非零状态,不承诺所有第三方退出码均为 1;调用方按非零失败处理。
|
||||
- 人类诊断写 stderr;JSON、报告路径等结果写 stdout 或显式报告文件;密钥和凭据不得出现在输出中。
|
||||
@@ -100,4 +143,4 @@ deskup 0.3.0 的开发更新源由 Dart 参数配置。Windows 的编译期配
|
||||
|
||||
桌面原生标题栏回归工具由 [cutdex_native](../packages/cutdex_native/README.md#原生回归) 维护。
|
||||
|
||||
Flutter 侧使用 `flutter test test/editor_window_chrome_test.dart test/adaptive_workspace_test.dart test/localization_resources_test.dart`。Windows 构建和 Flutter 测试请顺序运行,避免测试进程占用构建需要替换的 SQLite DLL。
|
||||
Flutter 侧使用 `fvm dart tool/flutter_local.dart test test/editor_window_chrome_test.dart test/adaptive_workspace_test.dart test/localization_resources_test.dart`。Windows 构建和 Flutter 测试请顺序运行,避免测试进程占用构建需要替换的 SQLite DLL。
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Build the application with shared development/production presets."""
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
from common.build import build_application
|
||||
from common.process import cli
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('platform', choices=['android', 'windows', 'macos'])
|
||||
parser.add_argument('--flavor', choices=['development', 'production'], default='production')
|
||||
parser.add_argument('--mode', choices=['debug', 'profile', 'release'], default='release')
|
||||
parser.add_argument('--split-per-abi', action='store_true')
|
||||
# Explicit separator keeps custom Flutter arguments distinct from presets.
|
||||
arguments = sys.argv[1:]
|
||||
separator = arguments.index('--') if '--' in arguments else len(arguments)
|
||||
extra = arguments[separator + 1:]
|
||||
args = parser.parse_args(arguments[:separator])
|
||||
if args.split_per_abi and args.platform != 'android':
|
||||
parser.error('--split-per-abi is only available for Android')
|
||||
return build_application(args.platform, flavor=args.flavor, mode=args.mode,
|
||||
split_per_abi=args.split_per_abi, extra=extra).returncode
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(cli(main))
|
||||
+33
-19
@@ -1,33 +1,28 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check repository tooling without building, signing, or publishing an app."""
|
||||
"""Check code, application/package tests and tools without building or publishing an app."""
|
||||
import argparse
|
||||
import ast
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
from project_tools import ROOT, host_bash, project_environment, tool_command
|
||||
from common.process import cli, run as run_command
|
||||
|
||||
|
||||
def run(command):
|
||||
print('+ ' + ' '.join(map(str, command)), flush=True)
|
||||
subprocess.run(command, cwd=ROOT, check=True)
|
||||
run_command(command)
|
||||
|
||||
|
||||
def main():
|
||||
argparse.ArgumentParser(description=__doc__).parse_args()
|
||||
if sys.version_info < (3, 11):
|
||||
raise SystemExit('Python 3.11 or newer is required for repository tooling.')
|
||||
def check_tools():
|
||||
tool_roots = [ROOT / 'tool', *(ROOT / 'packages').glob('*/tool')]
|
||||
for path in sorted(path for directory in tool_roots for path in directory.rglob('*.py')):
|
||||
ast.parse(path.read_text(encoding='utf-8'), filename=str(path))
|
||||
print('Python syntax: passed', flush=True)
|
||||
bash = shutil.which('bash')
|
||||
bash = host_bash()
|
||||
if bash:
|
||||
for path in sorted(path for directory in tool_roots for path in directory.rglob('*.sh')):
|
||||
run([bash, '-n', str(path)])
|
||||
run([bash, '-n', path.as_posix()])
|
||||
else:
|
||||
print('Shell syntax: skipped (bash unavailable)', flush=True)
|
||||
python = sys.executable
|
||||
@@ -41,14 +36,33 @@ def main():
|
||||
('tool/gitea', 'test_*.py'),
|
||||
]:
|
||||
run([python, '-m', 'unittest', 'discover', '-s', directory, '-p', pattern])
|
||||
flutter = os.environ.get('FLUTTER') or shutil.which('flutter')
|
||||
if not flutter:
|
||||
raise SystemExit('Flutter is required; set FLUTTER to its executable path.')
|
||||
run([flutter, 'analyze', 'lib', 'test', 'integration_test', 'test_driver', 'tool', 'packages'])
|
||||
|
||||
|
||||
def check_analyze():
|
||||
run(tool_command('dart', ['analyze', '--fatal-infos']))
|
||||
|
||||
|
||||
def check_flutter():
|
||||
package_tests = sorted(str(path.relative_to(ROOT)) for path in (ROOT / 'packages').glob('*/test'))
|
||||
if package_tests:
|
||||
run([flutter, 'test', *package_tests])
|
||||
run(tool_command('flutter', ['test', '--reporter', 'expanded', 'test', *package_tests]))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--suite', choices=['all', 'analyze', 'flutter', 'tools'], default='all',
|
||||
help='CI runs the same suites as the default local check')
|
||||
args = parser.parse_args()
|
||||
if sys.version_info < (3, 11):
|
||||
raise SystemExit('Python 3.11 or newer is required for repository tooling.')
|
||||
environment = project_environment()
|
||||
# Cross-language tests and child scripts inherit this same SDK and config.
|
||||
os.environ.clear()
|
||||
os.environ.update(environment)
|
||||
suites = {'analyze': check_analyze, 'flutter': check_flutter, 'tools': check_tools}
|
||||
for name, check in suites.items():
|
||||
if args.suite in ('all', name):
|
||||
check()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
sys.exit(cli(main))
|
||||
@@ -69,7 +69,7 @@ def check(root):
|
||||
for package, allowed in RUNTIME.items():
|
||||
directory = root / 'packages' / package
|
||||
manifest_path = directory / 'pubspec.yaml'
|
||||
manifest = manifest_path.read_text()
|
||||
manifest = manifest_path.read_text(encoding='utf-8')
|
||||
dependencies = dependency_names(manifest, 'dependencies')
|
||||
dev_dependencies = dependency_names(manifest, 'dev_dependencies')
|
||||
for dependency in sorted(dependencies - allowed):
|
||||
@@ -84,7 +84,7 @@ def check(root):
|
||||
if area != 'lib':
|
||||
declared |= dev_dependencies
|
||||
for source in (directory / area).rglob('*.dart'):
|
||||
for kind, uri in directives(source.read_text()):
|
||||
for kind, uri in directives(source.read_text(encoding='utf-8')):
|
||||
if uri.startswith('package:'):
|
||||
dependency, path = package_uri(uri)
|
||||
if dependency not in declared:
|
||||
@@ -99,7 +99,7 @@ def check(root):
|
||||
|
||||
for area in ['lib', 'test', 'integration_test', 'test_driver', 'tool']:
|
||||
for source in (root / area).rglob('*.dart'):
|
||||
for kind, uri in directives(source.read_text()):
|
||||
for kind, uri in directives(source.read_text(encoding='utf-8')):
|
||||
if uri.startswith('package:'):
|
||||
dependency, path = package_uri(uri)
|
||||
if dependency != 'cutdex' and (path == 'src' or path.startswith('src/')):
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Shared infrastructure for repository command-line tools."""
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Application build presets shared by CLI and platform release workflows."""
|
||||
from common.process import ROOT
|
||||
from project_tools import run_tool
|
||||
|
||||
|
||||
def build_arguments(platform, *, flavor='production', mode='release', split_per_abi=False):
|
||||
target = 'apk' if platform == 'android' else platform
|
||||
arguments = ['build', target, f'--{mode}', '--flavor', flavor]
|
||||
if platform == 'android':
|
||||
arguments += ['--target-platform', 'android-arm64,android-x64']
|
||||
if split_per_abi:
|
||||
arguments.append('--split-per-abi')
|
||||
if platform == 'macos':
|
||||
arguments.append('--split-debug-info=build/symbols/macos')
|
||||
return arguments
|
||||
|
||||
|
||||
def build_application(platform, *, flavor='production', mode='release',
|
||||
split_per_abi=False, extra=(), environment=None, root=ROOT, cwd=None):
|
||||
"""Use root's SDK/configuration; an isolated build may override cwd."""
|
||||
return run_tool('flutter', build_arguments(
|
||||
platform, flavor=flavor, mode=mode, split_per_abi=split_per_abi) + list(extra),
|
||||
root=root, cwd=cwd, env=environment, check=True)
|
||||
@@ -0,0 +1,7 @@
|
||||
"""Streaming hashes for platform package files."""
|
||||
import hashlib
|
||||
|
||||
|
||||
def file_sha256(path):
|
||||
with path.open('rb') as stream:
|
||||
return hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Run argument vectors and report failures without logging credentials."""
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def run(command, *, cwd=ROOT, env=None, check=True, timeout=None, **kwargs):
|
||||
return subprocess.run(list(map(str, command)), cwd=cwd, env=env,
|
||||
check=check, timeout=timeout, **kwargs)
|
||||
|
||||
|
||||
def cli(main):
|
||||
"""Shared exit contract; argparse continues to own help and usage errors."""
|
||||
try:
|
||||
return main() or 0
|
||||
except subprocess.CalledProcessError as error:
|
||||
print(f'Command failed (exit {error.returncode}).', file=sys.stderr)
|
||||
return error.returncode
|
||||
except subprocess.TimeoutExpired:
|
||||
print('Command timed out.', file=sys.stderr)
|
||||
return 1
|
||||
except (RuntimeError, ValueError) as error:
|
||||
print(error, file=sys.stderr)
|
||||
return 1
|
||||
except OSError:
|
||||
print('Required tool or file is unavailable; check paths and permissions.', file=sys.stderr)
|
||||
return 1
|
||||
except KeyboardInterrupt:
|
||||
return 130
|
||||
@@ -0,0 +1,9 @@
|
||||
@echo off
|
||||
setlocal
|
||||
set "dart_executable=%~dp0..\.fvm\flutter_sdk\bin\cache\dart-sdk\bin\dart.exe"
|
||||
if not exist "%dart_executable%" (
|
||||
echo Project Dart SDK is missing. Run fvm use first. 1>&2
|
||||
exit /b 1
|
||||
)
|
||||
"%dart_executable%" "%~dp0flutter_local.dart" %*
|
||||
exit /b %ERRORLEVEL%
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
dart_executable="$script_dir/../.fvm/flutter_sdk/bin/cache/dart-sdk/bin/dart"
|
||||
if [ ! -x "$dart_executable" ]; then
|
||||
echo 'Project Dart SDK is missing. Run fvm use first.' >&2
|
||||
exit 1
|
||||
fi
|
||||
exec "$dart_executable" "$script_dir/flutter_local.dart" "$@"
|
||||
@@ -0,0 +1,25 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'src/local_environment.dart';
|
||||
|
||||
Future<void> main(List<String> arguments) async {
|
||||
try {
|
||||
exitCode = await runLocalFlutter(
|
||||
arguments,
|
||||
root: Directory.fromUri(Platform.script.resolve('../')),
|
||||
inherited: Platform.environment,
|
||||
);
|
||||
} on FormatException catch (error) {
|
||||
stderr.writeln(error.message);
|
||||
exitCode = 2;
|
||||
} on FileSystemException {
|
||||
stderr.writeln('Cannot read .env.local; check the file permissions.');
|
||||
exitCode = 1;
|
||||
} on StateError catch (error) {
|
||||
stderr.writeln(error.message);
|
||||
exitCode = 1;
|
||||
} on ProcessException {
|
||||
stderr.writeln('Cannot start the project Flutter SDK. Run fvm use first.');
|
||||
exitCode = 1;
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ def packaging_change(path):
|
||||
'packages/cutdex_native/windows/',
|
||||
'lib/integrations/app_update',
|
||||
'lib/features/settings/update'))
|
||||
or PurePosixPath(path).name in {'pubspec.yaml', 'pubspec.lock', '.metadata'}
|
||||
or PurePosixPath(path).name in {'pubspec.yaml', 'pubspec.lock', '.metadata', '.fvmrc'}
|
||||
or (path.startswith('test/') and 'update' in path)
|
||||
)
|
||||
|
||||
|
||||
@@ -11,6 +11,9 @@ import zipfile
|
||||
from release_artifacts import AUDIT, FEED, INSTALLER, PORTABLE, METADATA, app_versions, checksum_lines, validate_artifact
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT / 'tool'))
|
||||
from common.files import file_sha256
|
||||
from common.process import cli
|
||||
|
||||
|
||||
def validate_apk(apk):
|
||||
@@ -36,8 +39,7 @@ def package_windows(windows, vpk, windows_version):
|
||||
checksums = {}
|
||||
for path in sorted(staged.rglob('*')):
|
||||
if path.is_file():
|
||||
with path.open('rb') as stream:
|
||||
checksums[path.relative_to(staged).as_posix()] = hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
checksums[path.relative_to(staged).as_posix()] = file_sha256(path)
|
||||
(staged / 'checksums.json').write_text(json.dumps(checksums), encoding='utf-8')
|
||||
result = package_app(staged, releases, vpk, require_processing=False)
|
||||
if result['version'] != windows_version:
|
||||
@@ -105,4 +107,4 @@ def main():
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
sys.exit(cli(main))
|
||||
@@ -32,7 +32,7 @@ class ScopeTests(unittest.TestCase):
|
||||
for path in ('.gitea/workflows/ci.yml', '.gitea/actions/upload-artifact/action.yml',
|
||||
'tool/gitea/ci_scope.py', 'tool/windows/windows_updates.py',
|
||||
'windows/runner/main.cpp.in', 'android/app/build.gradle.kts',
|
||||
'pubspec.yaml', 'pubspec.lock', 'packages/cutdex_ui/pubspec.yaml',
|
||||
'pubspec.yaml', 'pubspec.lock', '.fvmrc', 'packages/cutdex_ui/pubspec.yaml',
|
||||
'packages/cutdex_native/windows/CMakeLists.txt',
|
||||
'lib/integrations/app_update_bridge.dart',
|
||||
'lib/features/settings/update_controller.dart', 'test/app_updates_test.dart'):
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Verify the runner's Flutter version against the exact project .fvmrc pin."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from common.process import cli, run
|
||||
|
||||
VERSION = re.compile(r'\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?')
|
||||
|
||||
|
||||
def verify_version(config):
|
||||
try:
|
||||
required = json.loads(config.read_text(encoding='utf-8'))['flutter']
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
raise RuntimeError('.fvmrc must pin an exact Flutter framework version.') from None
|
||||
if not isinstance(required, str) or not VERSION.fullmatch(required):
|
||||
raise RuntimeError('.fvmrc must pin an exact Flutter framework version.')
|
||||
flutter = shutil.which('flutter')
|
||||
if not flutter:
|
||||
raise RuntimeError('Cannot read Flutter version; Flutter is missing on PATH.')
|
||||
try:
|
||||
result = run([flutter, '--version', '--machine'], cwd=config.parent,
|
||||
capture_output=True, text=True, encoding='utf-8', timeout=60)
|
||||
installed = json.loads(result.stdout)['frameworkVersion']
|
||||
except (OSError, subprocess.SubprocessError, ValueError, KeyError, TypeError):
|
||||
raise RuntimeError('Cannot read Flutter version.') from None
|
||||
if not isinstance(installed, str) or not VERSION.fullmatch(installed):
|
||||
raise RuntimeError('Cannot read Flutter framework version.')
|
||||
if installed != required:
|
||||
raise RuntimeError(f'Flutter {required} required by .fvmrc; found {installed}.')
|
||||
return required
|
||||
|
||||
|
||||
def main():
|
||||
argparse.ArgumentParser(description=__doc__).parse_args()
|
||||
version = verify_version(Path.cwd() / '.fvmrc')
|
||||
print(f'Flutter {version} matches .fvmrc.')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(cli(main))
|
||||
@@ -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))
|
||||
@@ -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"
|
||||
@@ -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))
|
||||
@@ -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"
|
||||
@@ -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))
|
||||
@@ -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}')
|
||||
@@ -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))
|
||||
@@ -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"
|
||||
@@ -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))
|
||||
@@ -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)
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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()
|
||||
@@ -0,0 +1,56 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'src/local_environment.dart';
|
||||
|
||||
Future<void> main(List<String> arguments) async {
|
||||
const usage =
|
||||
'Usage: project_tools.dart [--directory PATH] flutter|dart|exec <arguments>';
|
||||
if (arguments.length == 1 && ['--help', '-h'].contains(arguments.first)) {
|
||||
stdout.writeln(usage);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
final root = Directory.fromUri(Platform.script.resolve('../'));
|
||||
var workingDirectory = root;
|
||||
if (arguments.isNotEmpty && arguments.first == '--directory') {
|
||||
if (arguments.length < 3) throw const FormatException(usage);
|
||||
workingDirectory = Directory(arguments[1]).absolute;
|
||||
arguments = arguments.sublist(2);
|
||||
}
|
||||
if (arguments.isEmpty) throw const FormatException(usage);
|
||||
if (arguments.length == 1 && arguments.first == 'environment') {
|
||||
// Internal pipe for Python tools. Never log or persist this payload.
|
||||
final bin = projectSdkBin(root, allowCiSdk: true);
|
||||
stdout.writeln(
|
||||
jsonEncode(projectEnvironment(root, Platform.environment, bin)),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!['flutter', 'dart', 'exec'].contains(arguments.first)) {
|
||||
throw const FormatException(usage);
|
||||
}
|
||||
exitCode = await runProjectTool(
|
||||
arguments.first,
|
||||
arguments.sublist(1),
|
||||
root: root,
|
||||
inherited: Platform.environment,
|
||||
workingDirectory: workingDirectory,
|
||||
allowCiSdk: true,
|
||||
);
|
||||
} on FormatException catch (error) {
|
||||
stderr.writeln(error.message);
|
||||
exitCode = 2;
|
||||
} on FileSystemException {
|
||||
stderr.writeln(
|
||||
'Cannot read project configuration; check file permissions.',
|
||||
);
|
||||
exitCode = 1;
|
||||
} on StateError catch (error) {
|
||||
stderr.writeln(error.message);
|
||||
exitCode = 1;
|
||||
} on ProcessException {
|
||||
stderr.writeln('Cannot start the project tool; check the SDK and command.');
|
||||
exitCode = 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Python adapter to the shared Dart SDK/environment launcher."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sys
|
||||
|
||||
from common.process import ROOT, cli, run
|
||||
|
||||
|
||||
def host_bash():
|
||||
if os.name == 'nt':
|
||||
# WSL's system32/bash.exe cannot consume native Windows paths.
|
||||
git = shutil.which('git')
|
||||
if git:
|
||||
for relative in ('bin/bash.exe', 'usr/bin/bash.exe'):
|
||||
candidate = Path(git).resolve().parent.parent / relative
|
||||
if candidate.is_file():
|
||||
return str(candidate)
|
||||
bash = shutil.which('bash')
|
||||
if bash and Path(bash).resolve().parent != Path(os.environ.get('WINDIR', 'C:/Windows')) / 'System32':
|
||||
return bash
|
||||
return None
|
||||
return shutil.which('bash')
|
||||
|
||||
|
||||
def project_dart(root=ROOT, environment=None):
|
||||
environment = os.environ if environment is None else environment
|
||||
ci = any(environment.get(key, '').lower() in {'true', '1', 'yes'}
|
||||
for key in ('CI', 'GITEA_ACTIONS', 'GITHUB_ACTIONS'))
|
||||
if ci:
|
||||
flutter = shutil.which('flutter', path=environment.get('PATH', ''))
|
||||
if not flutter:
|
||||
raise RuntimeError('CI requires a complete Flutter SDK on PATH.')
|
||||
sdk_bin = Path(flutter).resolve().parent
|
||||
else:
|
||||
sdk_bin = Path(root) / '.fvm/flutter_sdk/bin'
|
||||
dart = sdk_bin / 'cache/dart-sdk/bin' / ('dart.exe' if os.name == 'nt' else 'dart')
|
||||
if not dart.is_file():
|
||||
raise RuntimeError('Project Flutter SDK is missing. Run fvm use first.')
|
||||
return str(dart)
|
||||
|
||||
|
||||
def tool_command(tool, arguments=(), *, cwd=None, root=ROOT, environment=None):
|
||||
root = Path(root).resolve()
|
||||
cwd = root if cwd is None else Path(cwd).resolve()
|
||||
return [project_dart(root, environment), str(root / 'tool/project_tools.dart'),
|
||||
'--directory', str(cwd), tool, *map(str, arguments)]
|
||||
|
||||
|
||||
def project_environment(*, root=ROOT, environment=None):
|
||||
root = Path(root).resolve()
|
||||
result = run(
|
||||
[project_dart(root, environment), str(root / 'tool/project_tools.dart'), 'environment'],
|
||||
cwd=root, env=environment, check=False, capture_output=True, text=True, encoding='utf-8', timeout=30)
|
||||
if result.returncode:
|
||||
# Diagnostics contain no configuration values; do not expose the JSON pipe.
|
||||
raise RuntimeError(result.stderr.strip() or 'Cannot load project environment.')
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def run_tool(tool, arguments=(), *, root=ROOT, cwd=None, **kwargs):
|
||||
root = Path(root).resolve()
|
||||
cwd = root if cwd is None else Path(cwd).resolve()
|
||||
command = tool_command(tool, arguments, root=root, cwd=cwd, environment=kwargs.get('env'))
|
||||
return run(command, cwd=cwd, **kwargs)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('tool', choices=['flutter', 'dart', 'exec'])
|
||||
parser.add_argument('arguments', nargs=argparse.REMAINDER)
|
||||
args = parser.parse_args()
|
||||
return run_tool(args.tool, args.arguments, cwd=Path.cwd()).returncode
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(cli(main))
|
||||
@@ -0,0 +1,195 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
Map<String, String> parseLocalEnvironment(String source) {
|
||||
final values = <String, String>{};
|
||||
final lines = const LineSplitter().convert(
|
||||
source.replaceFirst(RegExp(r'^\uFEFF'), ''),
|
||||
);
|
||||
final assignment = RegExp(
|
||||
r'^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$',
|
||||
);
|
||||
for (var index = 0; index < lines.length; index++) {
|
||||
final line = lines[index].trim();
|
||||
if (line.isEmpty || line.startsWith('#')) continue;
|
||||
final match = assignment.firstMatch(line);
|
||||
if (match == null) {
|
||||
throw FormatException(
|
||||
'Invalid .env.local assignment on line ${index + 1}.',
|
||||
);
|
||||
}
|
||||
final key = match[1]!;
|
||||
if (values.containsKey(key)) {
|
||||
throw FormatException('Duplicate .env.local key on line ${index + 1}.');
|
||||
}
|
||||
var value = match[2]!;
|
||||
if (value.startsWith('"') || value.startsWith("'")) {
|
||||
final end = value.indexOf(value[0], 1);
|
||||
if (end == -1 ||
|
||||
(value.substring(end + 1).trim().isNotEmpty &&
|
||||
!value.substring(end + 1).trim().startsWith('#'))) {
|
||||
throw FormatException(
|
||||
'Invalid .env.local quotes on line ${index + 1}.',
|
||||
);
|
||||
}
|
||||
value = value.substring(1, end);
|
||||
} else {
|
||||
value = value.split(RegExp(r'\s+#')).first.trimRight();
|
||||
}
|
||||
values[key] = value;
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
bool isContinuousIntegration(Map<String, String> environment) => [
|
||||
'CI',
|
||||
'GITEA_ACTIONS',
|
||||
'GITHUB_ACTIONS',
|
||||
].any((key) => ['true', '1', 'yes'].contains(environment[key]?.toLowerCase()));
|
||||
|
||||
Map<String, String> mergeLocalEnvironment(
|
||||
Map<String, String> inherited,
|
||||
Map<String, String> local, {
|
||||
required bool windows,
|
||||
}) {
|
||||
final result = Map<String, String>.of(inherited);
|
||||
final existing = inherited.keys
|
||||
.map((key) => windows ? key.toUpperCase() : key)
|
||||
.toSet();
|
||||
for (final entry in local.entries) {
|
||||
final key = windows ? entry.key.toUpperCase() : entry.key;
|
||||
if (existing.add(key)) result[entry.key] = entry.value;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
Map<String, String> loadLocalEnvironment(
|
||||
Directory root,
|
||||
Map<String, String> inherited, {
|
||||
required bool windows,
|
||||
}) {
|
||||
// Check the parent environment before opening any local file in CI.
|
||||
if (isContinuousIntegration(inherited)) return Map.of(inherited);
|
||||
final file = File.fromUri(root.uri.resolve('.env.local'));
|
||||
return mergeLocalEnvironment(
|
||||
inherited,
|
||||
file.existsSync() ? parseLocalEnvironment(file.readAsStringSync()) : {},
|
||||
windows: windows,
|
||||
);
|
||||
}
|
||||
|
||||
Future<int> runLocalFlutter(
|
||||
List<String> arguments, {
|
||||
required Directory root,
|
||||
required Map<String, String> inherited,
|
||||
}) async {
|
||||
return runProjectTool('flutter', arguments, root: root, inherited: inherited);
|
||||
}
|
||||
|
||||
Directory projectSdkBin(Directory root, {bool allowCiSdk = false}) {
|
||||
final bin = allowCiSdk && isContinuousIntegration(Platform.environment)
|
||||
? File(Platform.resolvedExecutable).parent.parent.parent.parent
|
||||
: Directory.fromUri(root.uri.resolve('.fvm/flutter_sdk/bin/'));
|
||||
if (!File.fromUri(
|
||||
bin.uri.resolve(Platform.isWindows ? 'flutter.bat' : 'flutter'),
|
||||
).existsSync() ||
|
||||
!File.fromUri(
|
||||
bin.uri.resolve(
|
||||
'cache/dart-sdk/bin/${Platform.isWindows ? 'dart.exe' : 'dart'}',
|
||||
),
|
||||
).existsSync()) {
|
||||
throw StateError(
|
||||
'Project Flutter SDK is missing. Run fvm use first; CI requires a complete Flutter SDK.',
|
||||
);
|
||||
}
|
||||
return bin;
|
||||
}
|
||||
|
||||
Map<String, String> projectEnvironment(
|
||||
Directory root,
|
||||
Map<String, String> inherited,
|
||||
Directory sdkBin,
|
||||
) {
|
||||
final environment = loadLocalEnvironment(
|
||||
root,
|
||||
inherited,
|
||||
windows: Platform.isWindows,
|
||||
);
|
||||
final pathKey = environment.keys
|
||||
.where(
|
||||
(key) =>
|
||||
Platform.isWindows ? key.toUpperCase() == 'PATH' : key == 'PATH',
|
||||
)
|
||||
.firstOrNull;
|
||||
final path = pathKey == null ? '' : environment.remove(pathKey)!;
|
||||
environment['PATH'] = '${sdkBin.path}${Platform.isWindows ? ';' : ':'}$path';
|
||||
return environment;
|
||||
}
|
||||
|
||||
Future<int> runProjectTool(
|
||||
String tool,
|
||||
List<String> arguments, {
|
||||
required Directory root,
|
||||
required Map<String, String> inherited,
|
||||
Directory? workingDirectory,
|
||||
bool allowCiSdk = false,
|
||||
}) async {
|
||||
final bin = projectSdkBin(root, allowCiSdk: allowCiSdk);
|
||||
final environment = projectEnvironment(root, inherited, bin);
|
||||
final String executable;
|
||||
switch (tool) {
|
||||
case 'flutter':
|
||||
executable = File.fromUri(
|
||||
bin.uri.resolve(Platform.isWindows ? 'flutter.bat' : 'flutter'),
|
||||
).path;
|
||||
case 'dart':
|
||||
executable = File.fromUri(
|
||||
bin.uri.resolve(
|
||||
'cache/dart-sdk/bin/${Platform.isWindows ? 'dart.exe' : 'dart'}',
|
||||
),
|
||||
).path;
|
||||
case 'exec':
|
||||
if (arguments.isEmpty) {
|
||||
throw const FormatException('exec requires a command.');
|
||||
}
|
||||
executable = arguments.first;
|
||||
arguments = arguments.sublist(1);
|
||||
default:
|
||||
throw const FormatException('Expected flutter, dart or exec.');
|
||||
}
|
||||
var command = executable;
|
||||
var commandArguments = arguments;
|
||||
if (Platform.isWindows &&
|
||||
(executable.toLowerCase().endsWith('.bat') ||
|
||||
executable.toLowerCase().endsWith('.cmd'))) {
|
||||
// cmd expands this variable once. Keeping the quoted command in the
|
||||
// environment avoids expanding literal %VAR% in Flutter arguments.
|
||||
environment['CUTDEX_LOCAL_FLUTTER_COMMAND'] = [
|
||||
executable,
|
||||
...arguments,
|
||||
].map(_quoteWindowsBatchArgument).join(' ');
|
||||
command = 'cmd.exe';
|
||||
commandArguments = ['/d', '/v:off', '/c', '%CUTDEX_LOCAL_FLUTTER_COMMAND%'];
|
||||
}
|
||||
final process = await Process.start(
|
||||
command,
|
||||
commandArguments,
|
||||
workingDirectory: (workingDirectory ?? root).path,
|
||||
environment: environment,
|
||||
includeParentEnvironment: false,
|
||||
mode: ProcessStartMode.inheritStdio,
|
||||
);
|
||||
return process.exitCode;
|
||||
}
|
||||
|
||||
String _quoteWindowsBatchArgument(String argument) {
|
||||
if (argument.contains('\n') || argument.contains('\r')) {
|
||||
throw const FormatException('Flutter arguments cannot contain newlines.');
|
||||
}
|
||||
// Always quote, including shell metacharacters and empty arguments. Inside
|
||||
// quotes Windows' C argument parser accepts doubled quotes as literal quotes.
|
||||
final escaped = argument
|
||||
.replaceAllMapped(RegExp(r'(\\*)"'), (match) => '${match[1]! * 2}""')
|
||||
.replaceAllMapped(RegExp(r'(\\+)$'), (match) => match[1]! * 2);
|
||||
return '"$escaped"';
|
||||
}
|
||||
@@ -8,17 +8,20 @@ import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT / 'tool'))
|
||||
from project_tools import host_bash, tool_command
|
||||
|
||||
|
||||
class CliTests(unittest.TestCase):
|
||||
def test_python_help_and_unknown_option(self):
|
||||
scripts = [
|
||||
'check.py', 'macos/check_macos_release.py', 'macos/macos_updates.py',
|
||||
'check.py', 'build.py', 'project_tools.py', 'macos/check_macos_release.py', 'macos/macos_updates.py',
|
||||
'macos/build_macos_release.py', 'macos/sign_macos_app.py', 'macos/create_macos_dmg.py',
|
||||
'macos/test_macos_release.py', 'macos/test_macos_updates.py',
|
||||
'macos/test_check_macos_release.py', 'windows/check_windows_release.py',
|
||||
'windows/package_windows_release.py', 'windows/prepare_windows_sandbox.py',
|
||||
'windows/windows_updates.py', 'windows/test_windows_updates.py',
|
||||
'gitea/package-app.py',
|
||||
'gitea/package-app.py', 'gitea/verify_flutter_version.py',
|
||||
'diagnostics/frame_budget.py',
|
||||
]
|
||||
for name in scripts:
|
||||
@@ -29,10 +32,8 @@ class CliTests(unittest.TestCase):
|
||||
self.assertEqual(result.returncode, code, result.stderr)
|
||||
self.assertIn('usage:', (result.stdout + result.stderr).lower())
|
||||
|
||||
@unittest.skipUnless(shutil.which('dart'), 'Dart SDK unavailable')
|
||||
def test_context_diagnostic_arguments_and_json_output(self):
|
||||
command = [shutil.which('dart'), 'run',
|
||||
str(ROOT / 'tool/diagnostics/benchmark_agent_context.dart')]
|
||||
command = tool_command('dart', ['run', ROOT / 'tool/diagnostics/benchmark_agent_context.dart'])
|
||||
for arguments, code in [(['--help'], 0), ([], 2)]:
|
||||
result = subprocess.run(command + arguments, cwd=ROOT, capture_output=True,
|
||||
text=True, timeout=60)
|
||||
@@ -46,15 +47,15 @@ class CliTests(unittest.TestCase):
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(json.loads(result.stdout)['messages'], 0)
|
||||
|
||||
@unittest.skipUnless(shutil.which('bash'), 'bash unavailable')
|
||||
@unittest.skipUnless(host_bash(), 'native bash unavailable')
|
||||
def test_shell_help_and_argument_count(self):
|
||||
for script in (ROOT / 'tool/macos').glob('*.sh'):
|
||||
with self.subTest(script=script.name):
|
||||
result = subprocess.run(['bash', str(script), '--help'],
|
||||
result = subprocess.run([host_bash(), script.as_posix(), '--help'],
|
||||
capture_output=True, text=True, timeout=10)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn('Usage:', result.stdout)
|
||||
result = subprocess.run(['bash', str(script), 'one', 'two', 'three'],
|
||||
result = subprocess.run([host_bash(), script.as_posix(), 'one', 'two', 'three'],
|
||||
capture_output=True, text=True, timeout=10)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Shared process/CLI contracts used by application and platform entrypoints."""
|
||||
import contextlib
|
||||
import hashlib
|
||||
import io
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from common.files import file_sha256
|
||||
from common.process import cli, run
|
||||
|
||||
|
||||
class CommonToolsTests(unittest.TestCase):
|
||||
def test_process_arguments_directory_and_child_environment_are_preserved(self):
|
||||
with tempfile.TemporaryDirectory(prefix='cutdex common process ') as directory:
|
||||
code = "import os,sys; print(os.getcwd()); print(os.environ['CUTDEX_TEST']); print(repr(sys.argv[1:]))"
|
||||
arguments = ['A&B with spaces', 'with "quotes"', '', '%literal%']
|
||||
result = run([sys.executable, '-c', code, *arguments], cwd=directory,
|
||||
env={'CUTDEX_TEST': 'child'}, capture_output=True, text=True)
|
||||
lines = result.stdout.splitlines()
|
||||
self.assertEqual(Path(lines[0]), Path(directory))
|
||||
self.assertEqual(lines[1], 'child')
|
||||
self.assertEqual(lines[2], repr(arguments))
|
||||
|
||||
def test_cli_preserves_child_failure_without_exposing_arguments(self):
|
||||
def fail():
|
||||
run([sys.executable, '-c', 'import sys; sys.exit(17)', 'secret-token'], capture_output=True)
|
||||
with contextlib.redirect_stderr(io.StringIO()) as diagnostics:
|
||||
self.assertEqual(cli(fail), 17)
|
||||
self.assertIn('exit 17', diagnostics.getvalue())
|
||||
self.assertNotIn('secret-token', diagnostics.getvalue())
|
||||
|
||||
def test_child_stdout_and_stderr_remain_separate(self):
|
||||
result = run([sys.executable, '-c', "import sys; print('result'); print('diagnostic', file=sys.stderr)"],
|
||||
capture_output=True, text=True)
|
||||
self.assertEqual(result.stdout.strip(), 'result')
|
||||
self.assertEqual(result.stderr.strip(), 'diagnostic')
|
||||
|
||||
def test_cli_reports_validation_failure_without_a_traceback(self):
|
||||
def fail():
|
||||
raise ValueError('Release files differ from the audited manifest')
|
||||
with contextlib.redirect_stderr(io.StringIO()) as diagnostics:
|
||||
self.assertEqual(cli(fail), 1)
|
||||
self.assertEqual(diagnostics.getvalue(), 'Release files differ from the audited manifest\n')
|
||||
|
||||
def test_streamed_file_hash_matches_binary_contents(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / 'artifact'
|
||||
payload = bytes(range(256)) * 32768
|
||||
path.write_bytes(payload)
|
||||
self.assertEqual(file_sha256(path), hashlib.sha256(payload).hexdigest())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,75 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
CHECKER = ROOT / 'tool/gitea/verify_flutter_version.py'
|
||||
|
||||
|
||||
class FlutterVersionTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temporary = tempfile.TemporaryDirectory(prefix='cutdex ci version ')
|
||||
self.addCleanup(self.temporary.cleanup)
|
||||
self.root = Path(self.temporary.name)
|
||||
self.config = self.root / '.fvmrc'
|
||||
self.probe = self.root / 'flutter-called'
|
||||
self.runner = self.root / ('flutter.bat' if os.name == 'nt' else 'flutter')
|
||||
probe = self.root / 'probe.py'
|
||||
probe.write_text("import os, sys\nfrom pathlib import Path\nassert sys.argv[1:] == ['--version', '--machine']\nPath(os.environ['CUTDEX_TEST_FLUTTER_PROBE']).write_text('called')\nprint(os.environ['CUTDEX_TEST_FLUTTER_JSON'])\nsys.exit(int(os.environ['CUTDEX_TEST_FLUTTER_EXIT']))\n", encoding='utf-8')
|
||||
if os.name == 'nt':
|
||||
self.runner.write_text(f'@echo off\n"{sys.executable}" "%~dp0probe.py" %*\nexit /b %ERRORLEVEL%\n')
|
||||
else:
|
||||
self.runner.write_text(f'#!/bin/sh\nexec "{sys.executable}" "{probe}" "$@"\n')
|
||||
self.runner.chmod(0o755)
|
||||
|
||||
def run_check(self, installed='3.47.5', exit_code=0):
|
||||
environment = dict(os.environ)
|
||||
environment.update(CUTDEX_TEST_FLUTTER_PROBE=str(self.probe),
|
||||
CUTDEX_TEST_FLUTTER_JSON=json.dumps({'frameworkVersion': installed}),
|
||||
CUTDEX_TEST_FLUTTER_EXIT=str(exit_code))
|
||||
environment['PATH'] = str(self.root) + os.pathsep + environment.get('PATH', '')
|
||||
return subprocess.run([sys.executable, str(CHECKER)], cwd=self.root, env=environment,
|
||||
capture_output=True, text=True, encoding='utf-8', timeout=30)
|
||||
|
||||
def test_project_pin_accepts_matching_stable_and_prerelease_sdk(self):
|
||||
for version in ('3.47.5', '3.47.0-1.0.pre'):
|
||||
with self.subTest(version=version):
|
||||
self.config.write_text(json.dumps({'flutter': version}))
|
||||
result = self.run_check(installed=version)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn(f'Flutter {version} matches .fvmrc.', result.stdout)
|
||||
self.assertTrue(self.probe.is_file())
|
||||
|
||||
def test_version_change_requires_matching_runner_sdk(self):
|
||||
self.config.write_text(json.dumps({'flutter': '3.47.6'}))
|
||||
result = self.run_check(installed='3.47.5')
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn('Flutter 3.47.6 required by .fvmrc; found 3.47.5', result.stderr)
|
||||
|
||||
def test_invalid_project_pin_fails_before_invoking_flutter(self):
|
||||
for content in ('not json', '{}', '{"flutter": 3}', '{"flutter": ""}', '{"flutter": "stable"}'):
|
||||
with self.subTest(content=content):
|
||||
self.config.write_text(content)
|
||||
result = self.run_check()
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertFalse(self.probe.exists())
|
||||
|
||||
def test_missing_project_pin_fails_before_invoking_flutter(self):
|
||||
result = self.run_check()
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertFalse(self.probe.exists())
|
||||
|
||||
def test_failed_flutter_probe_cannot_pass_version_validation(self):
|
||||
self.config.write_text(json.dumps({'flutter': '3.47.5'}))
|
||||
result = self.run_check(exit_code=7)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn('Cannot read Flutter version', result.stderr)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,269 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class LocalFlutterTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.dart = shutil.which('dart')
|
||||
if not self.dart:
|
||||
self.skipTest('Dart executable unavailable')
|
||||
bundled = Path(self.dart).parent / 'cache/dart-sdk/bin' / ('dart.exe' if os.name == 'nt' else 'dart')
|
||||
if bundled.is_file():
|
||||
self.dart = str(bundled)
|
||||
self.dart_sdk = Path(self.dart).resolve().parent.parent
|
||||
if not (self.dart_sdk / 'lib').is_dir():
|
||||
self.skipTest('Cannot locate a complete Dart SDK')
|
||||
self.temporary = tempfile.TemporaryDirectory(prefix='cutdex env test ')
|
||||
self.addCleanup(self.temporary.cleanup)
|
||||
self.root = Path(self.temporary.name)
|
||||
(self.root / 'tool/src').mkdir(parents=True)
|
||||
(self.root / 'tool/common').mkdir()
|
||||
sdk_bin = self.root / '.fvm/flutter_sdk/bin'
|
||||
(sdk_bin / 'cache').mkdir(parents=True)
|
||||
dart_link = sdk_bin / 'cache/dart-sdk'
|
||||
if os.name == 'nt':
|
||||
# Directory junctions also work for Windows runners without the
|
||||
# privilege required to create symbolic links.
|
||||
subprocess.run(['cmd.exe', '/d', '/c', 'mklink', '/J', str(dart_link), str(self.dart_sdk)],
|
||||
check=True, capture_output=True)
|
||||
else:
|
||||
os.symlink(self.dart_sdk, dart_link, target_is_directory=True)
|
||||
for name in ('flutter_local.dart', 'flutter-local.bat', 'flutter-local.sh',
|
||||
'project_tools.dart', 'project_tools.py', 'build.py',
|
||||
'common/__init__.py', 'common/process.py', 'common/build.py',
|
||||
'src/local_environment.dart'):
|
||||
shutil.copy2(ROOT / 'tool' / name, self.root / 'tool' / name)
|
||||
fake = sdk_bin / 'fake_flutter.py'
|
||||
fake.write_text('''import json, os, sys
|
||||
print(json.dumps({'args': sys.argv[1:], 'cwd': os.getcwd(),
|
||||
'file': os.environ.get('CUTDEX_ENV_FILE_TEST'),
|
||||
'android': os.environ.get('CUTDEX_ANDROID_PATH'),
|
||||
'parent': os.environ.get('CUTDEX_ENV_PARENT_TEST'),
|
||||
'input': sys.stdin.readline().strip()}), flush=True)
|
||||
print('flutter-diagnostic', file=sys.stderr)
|
||||
sys.exit(7 if 'fail' in sys.argv else 0)
|
||||
''', encoding='utf-8')
|
||||
self.flutter = sdk_bin / ('flutter.bat' if os.name == 'nt' else 'flutter')
|
||||
if os.name == 'nt':
|
||||
self.flutter.write_text(f'@echo off\n"{sys.executable}" "%~dp0fake_flutter.py" %*\nexit /b %ERRORLEVEL%\n')
|
||||
else:
|
||||
self.flutter.write_text(f'#!/bin/sh\nexec "{sys.executable}" "{fake}" "$@"\n')
|
||||
self.flutter.chmod(0o755)
|
||||
self.environment = {key: value for key, value in os.environ.items()
|
||||
if key not in {'CI', 'GITEA_ACTIONS', 'GITHUB_ACTIONS', 'CUTDEX_ANDROID_PATH'}}
|
||||
self.environment['CUTDEX_ENV_PARENT_TEST'] = 'parent'
|
||||
|
||||
def run_cli(self, *args, shim=False):
|
||||
if shim:
|
||||
script = self.root / 'tool' / ('flutter-local.bat' if os.name == 'nt' else 'flutter-local.sh')
|
||||
script.chmod(0o755)
|
||||
command = [str(script), *args]
|
||||
else:
|
||||
command = [self.dart, str(self.root / 'tool/flutter_local.dart'), *args]
|
||||
return subprocess.run(command, cwd=self.temporary.name, env=self.environment,
|
||||
input='daemon-request\n', capture_output=True, text=True,
|
||||
encoding='utf-8', timeout=40)
|
||||
|
||||
def test_cli_injects_environment_before_build_and_preserves_machine_io(self):
|
||||
(self.root / '.env.local').write_text(
|
||||
'CUTDEX_ENV_FILE_TEST="C:/My SDK/native"\nCUTDEX_ENV_PARENT_TEST=file\n'
|
||||
'CUTDEX_ANDROID_PATH="C:/My SDK/cutdex_android"\n',
|
||||
encoding='utf-8')
|
||||
result = self.run_cli('run', '--machine', '--profile', '--dart-define=VALUE=with space')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
data = json.loads(result.stdout)
|
||||
self.assertEqual(data['args'], ['run', '--machine', '--profile', '--dart-define=VALUE=with space'])
|
||||
self.assertEqual(data['file'], 'C:/My SDK/native')
|
||||
self.assertEqual(data['parent'], 'parent')
|
||||
self.assertEqual(data['android'], 'C:/My SDK/cutdex_android')
|
||||
self.assertEqual(data['input'], 'daemon-request')
|
||||
self.assertEqual(Path(data['cwd']), self.root)
|
||||
self.assertEqual(result.stderr.strip(), 'flutter-diagnostic')
|
||||
|
||||
def test_ide_shim_uses_the_same_loader_and_preserves_arguments(self):
|
||||
(self.root / '.env.local').write_text('CUTDEX_ENV_FILE_TEST=from-ide\n')
|
||||
result = self.run_cli('run', '--machine', '--release', '--dart-define=VALUE=with space', shim=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
data = json.loads(result.stdout)
|
||||
self.assertEqual(data['file'], 'from-ide')
|
||||
self.assertEqual(data['args'], ['run', '--machine', '--release', '--dart-define=VALUE=with space'])
|
||||
|
||||
def test_cli_preserves_literal_shell_characters_quotes_and_empty_arguments(self):
|
||||
args = ['run', '', '--dart-define=VALUE=A&B|C<test>^!',
|
||||
'--dart-define=VALUE=%CUTDEX_ENV_PARENT_TEST%',
|
||||
'--dart-define=VALUE=with "quotes"&text', 'C:\\spaces dir\\',
|
||||
'backslash\\"quote']
|
||||
result = self.run_cli(*args)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(json.loads(result.stdout)['args'], args)
|
||||
|
||||
def test_project_sdk_wins_over_path_and_obsolete_flutter_override(self):
|
||||
wrong_bin = self.root / 'Other SDK/bin'
|
||||
wrong_bin.mkdir(parents=True)
|
||||
wrong_flutter = wrong_bin / self.flutter.name
|
||||
wrong_flutter.write_text('@exit /b 9\n' if os.name == 'nt' else '#!/bin/sh\nexit 9\n')
|
||||
wrong_flutter.chmod(0o755)
|
||||
self.environment['FLUTTER'] = str(wrong_flutter)
|
||||
self.environment['PATH'] = str(wrong_bin) + os.pathsep + self.environment.get('PATH', '')
|
||||
result = self.run_cli('--version')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(json.loads(result.stdout)['args'], ['--version'])
|
||||
|
||||
def test_missing_project_sdk_fails_without_using_global_flutter(self):
|
||||
self.flutter.unlink()
|
||||
result = self.run_cli('--version')
|
||||
self.assertEqual(result.returncode, 1)
|
||||
self.assertEqual(result.stdout, '')
|
||||
self.assertIn('fvm use', result.stderr)
|
||||
|
||||
def test_child_failure_exit_code_is_preserved(self):
|
||||
self.assertEqual(self.run_cli('fail').returncode, 7)
|
||||
|
||||
def test_ci_ignores_invalid_local_configuration(self):
|
||||
(self.root / '.env.local').write_text('invalid-secret-data')
|
||||
self.environment['CI'] = 'true'
|
||||
result = self.run_cli('--version')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIsNone(json.loads(result.stdout)['file'])
|
||||
|
||||
def test_invalid_file_fails_before_flutter_without_echoing_values(self):
|
||||
(self.root / '.env.local').write_text('invalid-secret-data')
|
||||
result = self.run_cli('run')
|
||||
self.assertEqual(result.returncode, 2)
|
||||
self.assertEqual(result.stdout, '')
|
||||
self.assertNotIn('invalid-secret-data', result.stderr)
|
||||
self.assertIn('line 1', result.stderr)
|
||||
|
||||
def run_project_tool(self, *arguments):
|
||||
return subprocess.run([sys.executable, str(self.root / 'tool/project_tools.py'), *arguments],
|
||||
cwd=self.root, env=self.environment, input='daemon-request\n',
|
||||
capture_output=True, text=True, encoding='utf-8', timeout=40)
|
||||
|
||||
def test_python_adapter_and_exec_share_config_with_all_child_processes(self):
|
||||
(self.root / '.env.local').write_text('CUTDEX_ENV_FILE_TEST=from-whole-pipeline\n')
|
||||
result = self.run_project_tool('exec', sys.executable, self.flutter.parent / 'fake_flutter.py')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
data = json.loads(result.stdout)
|
||||
self.assertEqual(data['file'], 'from-whole-pipeline')
|
||||
self.assertEqual(data['parent'], 'parent')
|
||||
self.assertEqual(data['input'], 'daemon-request')
|
||||
|
||||
def test_isolated_build_keeps_its_working_directory_and_project_configuration(self):
|
||||
source = self.root / 'isolated source'
|
||||
source.mkdir()
|
||||
(source / '.env.local').write_text('CUTDEX_ENV_FILE_TEST=wrong-project\n')
|
||||
(self.root / '.env.local').write_text('CUTDEX_ENV_FILE_TEST=main-project\n')
|
||||
result = subprocess.run([self.dart, str(self.root / 'tool/project_tools.dart'),
|
||||
'--directory', str(source), 'flutter', 'build', 'windows'],
|
||||
env=self.environment, input='request\n', capture_output=True,
|
||||
text=True, encoding='utf-8', timeout=40)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
data = json.loads(result.stdout)
|
||||
self.assertEqual(Path(data['cwd']), source)
|
||||
self.assertEqual(data['file'], 'main-project')
|
||||
self.assertEqual(data['args'], ['build', 'windows'])
|
||||
|
||||
def test_python_adapter_preserves_batch_arguments_and_failure_status(self):
|
||||
arguments = ['fail', '', 'A&B|C<>^!', '%CUTDEX_ENV_PARENT_TEST%', 'with "quotes"']
|
||||
result = self.run_project_tool('flutter', *arguments)
|
||||
self.assertEqual(result.returncode, 7, result.stderr)
|
||||
self.assertEqual(json.loads(result.stdout)['args'], arguments)
|
||||
|
||||
def test_shared_build_presets_use_project_sdk_and_configuration(self):
|
||||
(self.root / '.env.local').write_text('CUTDEX_ENV_FILE_TEST=build-config\n')
|
||||
for arguments, expected in [
|
||||
(['android'], ['build', 'apk', '--release', '--flavor', 'production',
|
||||
'--target-platform', 'android-arm64,android-x64']),
|
||||
(['android', '--flavor', 'development', '--mode', 'debug', '--split-per-abi'],
|
||||
['build', 'apk', '--debug', '--flavor', 'development',
|
||||
'--target-platform', 'android-arm64,android-x64', '--split-per-abi']),
|
||||
(['windows', '--', '--dart-define=VALUE=A&B with space'],
|
||||
['build', 'windows', '--release', '--flavor', 'production',
|
||||
'--dart-define=VALUE=A&B with space']),
|
||||
(['macos'], ['build', 'macos', '--release', '--flavor', 'production',
|
||||
'--split-debug-info=build/symbols/macos']),
|
||||
]:
|
||||
with self.subTest(arguments=arguments):
|
||||
result = subprocess.run([sys.executable, str(self.root / 'tool/build.py'), *arguments],
|
||||
cwd=self.root, env=self.environment, input='request\n',
|
||||
capture_output=True, text=True, encoding='utf-8', timeout=40)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
data = json.loads(result.stdout)
|
||||
self.assertEqual(data['args'], expected)
|
||||
self.assertEqual(data['file'], 'build-config')
|
||||
|
||||
def test_invalid_build_preset_fails_before_launching_flutter(self):
|
||||
result = subprocess.run([sys.executable, str(self.root / 'tool/build.py'),
|
||||
'windows', '--split-per-abi'], env=self.environment,
|
||||
capture_output=True, text=True, timeout=10)
|
||||
self.assertEqual(result.returncode, 2)
|
||||
self.assertEqual(result.stdout, '')
|
||||
|
||||
def test_build_api_uses_selected_projects_sdk_configuration_and_working_directory(self):
|
||||
(self.root / '.env.local').write_text('CUTDEX_ENV_FILE_TEST=selected-project\n')
|
||||
source = self.root / 'isolated source'
|
||||
source.mkdir()
|
||||
(source / '.env.local').write_text('CUTDEX_ENV_FILE_TEST=wrong-working-directory\n')
|
||||
# Import the original checkout's library, then build another project.
|
||||
# A root override must switch the SDK/loader as well as the build cwd.
|
||||
probe = ("import sys; from common.build import build_application; "
|
||||
"sys.exit(build_application('macos', root=sys.argv[1], "
|
||||
"cwd=sys.argv[2] if len(sys.argv)>2 else None).returncode)")
|
||||
environment = dict(self.environment, PYTHONPATH=str(ROOT / 'tool'))
|
||||
for cwd in (None, source):
|
||||
with self.subTest(cwd=cwd):
|
||||
arguments = [sys.executable, '-c', probe, str(self.root)]
|
||||
if cwd is not None:
|
||||
arguments.append(str(cwd))
|
||||
result = subprocess.run(arguments, cwd=ROOT, env=environment, input='request\n',
|
||||
capture_output=True, text=True, encoding='utf-8', timeout=40)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
data = json.loads(result.stdout)
|
||||
self.assertEqual(Path(data['cwd']), self.root if cwd is None else cwd)
|
||||
self.assertEqual(data['file'], 'selected-project')
|
||||
self.assertEqual(data['input'], 'request')
|
||||
self.assertEqual(data['args'], ['build', 'macos', '--release', '--flavor', 'production',
|
||||
'--split-debug-info=build/symbols/macos'])
|
||||
|
||||
def test_python_environment_bridge_uses_the_shared_parser_without_logging(self):
|
||||
(self.root / '.env.local').write_text('CUTDEX_ENV_FILE_TEST="literal # path"\n')
|
||||
probe = "import project_tools; e=project_tools.project_environment(); print(e['CUTDEX_ENV_FILE_TEST'])"
|
||||
environment = dict(self.environment, PYTHONPATH=str(self.root / 'tool'))
|
||||
result = subprocess.run([sys.executable, '-c', probe], cwd=self.root, env=environment,
|
||||
capture_output=True, text=True, timeout=40)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(result.stdout.strip(), 'literal # path')
|
||||
self.assertEqual(result.stderr, '')
|
||||
|
||||
def test_ci_adapter_uses_preinstalled_sdk_and_skips_invalid_local_file(self):
|
||||
(self.root / '.env.local').write_text('invalid-secret-data')
|
||||
self.flutter.unlink() # CI must work without a prepared project FVM SDK.
|
||||
self.environment['CI'] = 'true'
|
||||
self.environment['PATH'] = str(self.dart_sdk.parent.parent) + os.pathsep + self.environment['PATH']
|
||||
result = self.run_project_tool('exec', sys.executable, self.flutter.parent / 'fake_flutter.py')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIsNone(json.loads(result.stdout)['file'])
|
||||
self.assertNotIn('invalid-secret-data', result.stdout + result.stderr)
|
||||
|
||||
def test_dart_adapter_preserves_package_working_directory(self):
|
||||
package = self.root / 'packages/test package'
|
||||
package.mkdir(parents=True)
|
||||
probe = package / 'probe.dart'
|
||||
probe.write_text("import 'dart:io'; void main() { stdout.writeln(Directory.current.path); }\n")
|
||||
result = subprocess.run([sys.executable, str(self.root / 'tool/project_tools.py'), 'dart', str(probe)],
|
||||
cwd=package, env=self.environment, capture_output=True, text=True, timeout=40)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(Path(result.stdout.strip()), package)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -80,6 +80,12 @@ dev_dependencies:
|
||||
"import 'package:cutdex_ui/widgets.dart';\nimport 'package:flutter_test/flutter_test.dart';")
|
||||
self.assertEqual(boundaries.check(self.root), [])
|
||||
|
||||
def test_utf8_sources_are_read_independently_of_windows_locale(self):
|
||||
source = self.root / 'lib/app.dart'
|
||||
source.parent.mkdir(parents=True)
|
||||
source.write_text("const label = '剪辑 🎬';\n", encoding='utf-8')
|
||||
self.assertEqual(boundaries.check(self.root), [])
|
||||
|
||||
def test_conditional_imports_and_exports_cannot_hide_private_sources(self):
|
||||
self.write('lib/app.dart', "import 'stub.dart' if (dart.library.io) 'package:cutdex_ui/src/widgets/app_item.dart';")
|
||||
self.write('lib/export.dart', "export 'stub.dart' if (dart.library.io) 'package:cutdex_native/src/file_drop.dart';")
|
||||
|
||||
@@ -3,10 +3,14 @@
|
||||
Requires pefile on the build host. Models remain separate from the application.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from common.files import file_sha256
|
||||
from common.process import cli
|
||||
|
||||
from check_windows_release import audit
|
||||
|
||||
@@ -27,8 +31,7 @@ def main():
|
||||
path = (runtime / name).resolve()
|
||||
if not path.is_relative_to(runtime):
|
||||
raise ValueError(f'Invalid processing manifest path: {name}')
|
||||
with path.open('rb') as stream:
|
||||
actual = hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
actual = file_sha256(path)
|
||||
if actual.lower() != expected.lower():
|
||||
raise ValueError(f'Processing checksum mismatch: {name}')
|
||||
# Older Flutter builds can retain the unused JNI plugin from Android's
|
||||
@@ -40,11 +43,10 @@ def main():
|
||||
manifest = {}
|
||||
for path in sorted(output.rglob('*')):
|
||||
if path.is_file():
|
||||
with path.open('rb') as stream:
|
||||
manifest[path.relative_to(output).as_posix()] = hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
manifest[path.relative_to(output).as_posix()] = file_sha256(path)
|
||||
(output / 'checksums.json').write_text(json.dumps(manifest, indent=2) + '\n', encoding='utf-8')
|
||||
print(f'Portable package staged: {output} ({len(manifest)} files)')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
sys.exit(cli(main))
|
||||
@@ -15,6 +15,9 @@ import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from project_tools import project_environment, tool_command
|
||||
|
||||
from windows_updates import ROOT, check_tool, pack_release, resolved_deskup, update_version, verify_sdk_version, vpk_command
|
||||
|
||||
|
||||
@@ -38,7 +41,6 @@ class TestHandler(SimpleHTTPRequestHandler):
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--vpk', type=Path, required=True)
|
||||
parser.add_argument('--flutter', default=shutil.which('flutter'))
|
||||
parser.add_argument('--work', type=Path, default=ROOT / '.local/windows-update-test')
|
||||
parser.add_argument('--port', type=int, default=8765)
|
||||
parser.add_argument('--offline', action='store_true', help='Use already cached Flutter packages')
|
||||
@@ -56,7 +58,7 @@ def main():
|
||||
definitions = work / 'defines.json'
|
||||
definitions.write_text(json.dumps({'CUTDEX_UPDATE_SMOKE_ROOT': work.as_posix(),
|
||||
'CUTDEX_WINDOWS_UPDATE_URL': f'http://127.0.0.1:{args.port}'}), encoding='utf-8')
|
||||
environment = dict(os.environ)
|
||||
environment = project_environment()
|
||||
# Isolate Flutter caches, generated runner files and output from live builds.
|
||||
source = work / 'source'
|
||||
source.mkdir()
|
||||
@@ -74,13 +76,13 @@ def main():
|
||||
entry = source / 'tool/testing/windows_update_smoke.dart'
|
||||
entry.parent.mkdir(parents=True)
|
||||
shutil.copyfile(ROOT / 'tool/testing/windows_update_smoke.dart', entry)
|
||||
subprocess.run([args.flutter, 'pub', 'get'] + (['--offline'] if args.offline else []),
|
||||
subprocess.run(tool_command('flutter', ['pub', 'get'] + (['--offline'] if args.offline else []), cwd=source),
|
||||
cwd=source, env=environment, check=True)
|
||||
# Keep test packages separate from the app's normal release output.
|
||||
for build in [900001, 900002]:
|
||||
subprocess.run([args.flutter, 'build', 'windows', '--no-pub', '--release', '--flavor', 'development',
|
||||
subprocess.run(tool_command('flutter', ['build', 'windows', '--no-pub', '--release', '--flavor', 'development',
|
||||
'--target', 'tool/testing/windows_update_smoke.dart', '--build-name', '1.0.0',
|
||||
'--build-number', str(build), '--dart-define-from-file', str(definitions)],
|
||||
'--build-number', str(build), '--dart-define-from-file', str(definitions)], cwd=source),
|
||||
cwd=source, env=environment, check=True)
|
||||
app = source / 'build/windows/x64/development/runner/Release'
|
||||
release = work / ('baseline' if build == 900001 else 'public')
|
||||
|
||||
@@ -21,7 +21,7 @@ class UpdatePublicationTests(unittest.TestCase):
|
||||
def test_packaging_tool_check_does_not_resolve_flutter_dependencies(self):
|
||||
from subprocess import CompletedProcess
|
||||
with patch('windows_updates.resolved_deskup', side_effect=AssertionError('No Flutter config')), \
|
||||
patch('windows_updates.subprocess.run', return_value=CompletedProcess([], 0, f'vpk {SDK_VERSION}', '')):
|
||||
patch('windows_updates.run', return_value=CompletedProcess([], 0, f'vpk {SDK_VERSION}', '')):
|
||||
check_tool(['vpk'])
|
||||
|
||||
def test_build_sdk_check_rejects_mismatched_and_missing_versions(self):
|
||||
@@ -53,7 +53,7 @@ class UpdatePublicationTests(unittest.TestCase):
|
||||
def test_missing_package_config_requests_pub_get(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
with patch('windows_updates.ROOT', Path(directory)):
|
||||
with self.assertRaisesRegex(ValueError, 'flutter pub get'):
|
||||
with self.assertRaisesRegex(ValueError, 'flutter_local.dart pub get'):
|
||||
resolved_deskup()
|
||||
|
||||
def test_display_version_conversion_is_shared_and_ordered(self):
|
||||
@@ -64,7 +64,7 @@ class UpdatePublicationTests(unittest.TestCase):
|
||||
update_version(version, build)
|
||||
|
||||
def test_invalid_pack_version_never_starts_vpk(self):
|
||||
with patch('windows_updates.subprocess.run') as run:
|
||||
with patch('windows_updates.run') as run:
|
||||
with self.assertRaises(ValueError):
|
||||
pack_release(['vpk'], app=Path('app'), output=Path('release'),
|
||||
package_id='Cutdex', version='1.0.0.42', title='Cutdex')
|
||||
|
||||
@@ -1,27 +1,28 @@
|
||||
"""Package audited Windows releases with Velopack, or serve a loopback test feed."""
|
||||
import argparse
|
||||
from functools import partial
|
||||
import hashlib
|
||||
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from urllib.parse import urljoin, urlparse
|
||||
from urllib.request import url2pathname
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from common.files import file_sha256
|
||||
from common.process import ROOT, cli, run
|
||||
|
||||
from check_windows_release import audit
|
||||
from update_versions import numeric_version, update_version
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SDK_VERSION = '1.2.161'
|
||||
|
||||
|
||||
def resolved_deskup():
|
||||
config = ROOT / '.dart_tool/package_config.json'
|
||||
if not config.is_file():
|
||||
raise ValueError('Run flutter pub get before using Windows update tools')
|
||||
raise ValueError('Run fvm dart tool/flutter_local.dart pub get before using Windows update tools')
|
||||
packages = json.loads(config.read_text(encoding='utf-8'))['packages']
|
||||
package = next(item for item in packages if item['name'] == 'deskup')
|
||||
uri = urlparse(urljoin(config.as_uri(), package['rootUri']))
|
||||
@@ -48,7 +49,7 @@ def vpk_command(path):
|
||||
|
||||
|
||||
def check_tool(command):
|
||||
result = subprocess.run(command + ['--help'], capture_output=True, text=True,
|
||||
result = run(command + ['--help'], cwd=Path.cwd(), capture_output=True, text=True,
|
||||
encoding='utf-8', errors='replace', check=True, timeout=30)
|
||||
if not re.search(rf'(?<![\d.]){re.escape(SDK_VERSION)}(?![\d.])', result.stdout + result.stderr):
|
||||
raise ValueError(f'Use vpk {SDK_VERSION} to match the native SDK')
|
||||
@@ -56,11 +57,11 @@ def check_tool(command):
|
||||
|
||||
def pack_release(command, *, app, output, package_id, version, title):
|
||||
numeric_version(version)
|
||||
subprocess.run(command + ['pack', '--packId', package_id, '--packVersion', version,
|
||||
run(command + ['pack', '--packId', package_id, '--packVersion', version,
|
||||
'--packDir', str(app), '--mainExe', 'cutdex.exe',
|
||||
'--packTitle', title, '--runtime', 'win-x64',
|
||||
'--channel', 'win-x64', '--outputDir', str(output),
|
||||
'--delta', 'none'], check=True)
|
||||
'--delta', 'none'], cwd=Path.cwd(), check=True)
|
||||
|
||||
|
||||
def file_version(app):
|
||||
@@ -103,9 +104,8 @@ def verify_manifest(app):
|
||||
file = candidate.resolve()
|
||||
if not file.is_relative_to(app) or candidate.is_symlink():
|
||||
raise ValueError(f'Invalid manifest path: {name}')
|
||||
with file.open('rb') as stream:
|
||||
if hashlib.file_digest(stream, 'sha256').hexdigest().lower() != expected.lower():
|
||||
raise ValueError(f'Release checksum mismatch: {name}')
|
||||
if file_sha256(file).lower() != expected.lower():
|
||||
raise ValueError(f'Release checksum mismatch: {name}')
|
||||
|
||||
|
||||
def package_app(app, output, vpk, *, development=False, require_processing=True):
|
||||
@@ -159,23 +159,15 @@ def main():
|
||||
server.add_argument('--directory', type=Path, required=True)
|
||||
server.add_argument('--port', type=int, default=8765)
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
if args.command == 'pack':
|
||||
verify_sdk_version()
|
||||
print(json.dumps(package_app(args.app, args.output, args.vpk,
|
||||
development=args.development)))
|
||||
elif args.command == 'verify-sdk':
|
||||
print(f'Velopack SDK {verify_sdk_version()} verified')
|
||||
else:
|
||||
serve(args.directory, args.port)
|
||||
except KeyboardInterrupt:
|
||||
return
|
||||
except (ValueError, OSError) as error:
|
||||
print(str(error), file=sys.stderr)
|
||||
raise SystemExit(1) from error
|
||||
except subprocess.CalledProcessError as error:
|
||||
raise SystemExit(error.returncode) from error
|
||||
if args.command == 'pack':
|
||||
verify_sdk_version()
|
||||
print(json.dumps(package_app(args.app, args.output, args.vpk,
|
||||
development=args.development)))
|
||||
elif args.command == 'verify-sdk':
|
||||
print(f'Velopack SDK {verify_sdk_version()} verified')
|
||||
else:
|
||||
serve(args.directory, args.port)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
sys.exit(cli(main))
|
||||
Reference in new issue
Block a user