feat: initial Cutdex application
Add the Flutter video editing application with project management, media import, timeline editing, preview, AI assistance, diagnostics and settings. Include shared UI and native host packages, platform runners, application tests and release tooling. Provide usage and contribution guides, the MIT license and third-party notices. Exclude local credentials, build outputs and validation data.
This commit is contained in:
commit
27e77fff39
718 files changed
+183958
No files matched your search
+101
@@ -0,0 +1,101 @@
|
||||
# 仓库工具
|
||||
|
||||
使用 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 语法检查。
|
||||
|
||||
## 源码检查
|
||||
|
||||
`python3 tool/check_public_repository.py` 无需 Flutter 或私有依赖,检查待提交源码中的常见凭据、本地产物和文档本地链接。它已接入 `check.py`;检查范围与限制见 [测试指南](../docs/testing.md)。
|
||||
|
||||
## 稳定客户端入口
|
||||
|
||||
`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/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/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_macos_updates.py | 本地更新模拟与测试服务器,需 App/Sparkle 工具 |
|
||||
| macos/sparkle_test_key.swift | 更新模拟专用临时密钥工具,不写系统钥匙串 |
|
||||
|
||||
正常应用打包入口:
|
||||
|
||||
```sh
|
||||
bash tool/macos/build_macos_release.sh /absolute/path/to/processing-runtime
|
||||
```
|
||||
|
||||
默认输出到 `dist/macos/`,第二个参数可指定输出目录。`FLUTTER`、`PYTHON` 可指定工具;最终签名使用 `CUTDEX_CODESIGN_IDENTITY`,公证使用 `CUTDEX_NOTARY_PROFILE`。开发签名配置见 [开发指南](../docs/development.md)。
|
||||
|
||||
发布验证使用 `check_macos_release.py` 和 `test_macos_release.py`,参数见 `--help`。后者构建独立测试入口,完成后重新打包正常应用;搬迁启动不能代替干净 Mac 上的安装验证。
|
||||
|
||||
## Windows
|
||||
|
||||
| 脚本 | 责任 |
|
||||
| --- | --- |
|
||||
| windows/package_windows_release.py | 校验 processing 哈希,组装便携发行包 |
|
||||
| windows/check_windows_release.py | 检查 PE 依赖和发行包完整性;真实审计需 pefile |
|
||||
| windows/test_check_windows_release.py | 注入依赖读取器验证缺库与系统库规则 |
|
||||
| windows/prepare_windows_sandbox.py | 生成 Windows Sandbox 配置并部署对应测试脚本 |
|
||||
| windows/test_windows_release.ps1 | 在干净 Windows 环境执行发布 smoke 测试 |
|
||||
| windows/windows_updates.py | 生成应用更新产物,或启动本地测试更新源 |
|
||||
| windows/test_windows_updates.py | 独立构建两个测试版本,验证损坏包拒绝、重试、安装和重启 |
|
||||
| windows/test_windows_updates_unit.py | 发布版本递增、包身份与审计后完整性规则测试 |
|
||||
|
||||
正常发行包组装入口,构建机还需安装 `pefile`:
|
||||
|
||||
```powershell
|
||||
flutter build windows --release --flavor production
|
||||
python tool/windows/package_windows_release.py `
|
||||
--app build/windows/x64/production/runner/Release `
|
||||
--processing D:\packages\processing `
|
||||
--output D:\packages\Cutdex
|
||||
```
|
||||
|
||||
提供完整 Release 目录和 processing 包,输出必须是新目录。依赖审计后再在独立 Windows 环境验证;`prepare_windows_sandbox.py --help` 提供 Sandbox 入口。真实界面检查需交互桌面,不能用 SSH 构建或进程存活代替。
|
||||
|
||||
## 应用更新产物
|
||||
|
||||
Cutdex 的更新构建配置为 macOS 的 `CUTDEX_UPDATE_FEED_URL` / `CUTDEX_UPDATE_PUBLIC_KEY`,Windows 的 `CUTDEX_WINDOWS_UPDATE_URL`;在构建前设置正式 HTTPS 更新源。
|
||||
|
||||
生成更新产物的应用入口:
|
||||
|
||||
```sh
|
||||
python3 tool/macos/macos_updates.py publish --help
|
||||
python3 tool/windows/windows_updates.py pack --help
|
||||
```
|
||||
|
||||
提升应用构建号,保留当前线上更新索引供版本检查;development 与 production 使用独立发布目录。脚本只生成产物,不上传。完整升级模拟使用各平台的 `test_*_updates.py`,参数见 `--help`,测试包不用于分发。
|
||||
|
||||
## 诊断与共享测试入口
|
||||
|
||||
- `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_agent_context.dart`:读取第一个参数指定的 AgentMessage JSON 数组,比较完整历史和 Harness 投影的估算 token/字节量。
|
||||
- `testing/release_smoke.dart`:macOS/Windows 发布测试共用的 Flutter 入口,验证导出、翻译和资源配置。测试 App 不得分发;结束后使用 `lib/main.dart` 重建正式 App。
|
||||
|
||||
构建前退出相同构建目录中的运行实例。真实发布/更新/处理测试可能构建应用、启动 worker 或本地服务器,按脚本参数入口运行,不由通用检查隐式执行。
|
||||
|
||||
## 语言与入口约定
|
||||
|
||||
- Shell 负责系统命令编排与临时资源清理;JSON、XML、依赖和发布规则集中在 Python。签名脚本中的文件筛选与命令排序属于签名流程,保持单一实现。
|
||||
- Swift 处理原生能力;PowerShell 处理 Windows 桌面与进程环境;Dart 入口用于应用连接与 Flutter 测试。
|
||||
- 普通 Python、Shell、Swift 和 Dart 诊断入口支持 `--help`(Shell/Swift/Dart 也支持 `-h`),帮助不启动构建、服务器或发布操作。PowerShell 使用 `Get-Help <脚本> -Full`。
|
||||
- 普通 CLI:成功/帮助为 0,参数格式或数量错误为 2,工具主动判定的运行失败为 1。外部子命令失败保留其非零状态,不承诺所有第三方退出码均为 1;调用方按非零失败处理。
|
||||
- 人类诊断写 stderr;JSON、报告路径等结果写 stdout 或显式报告文件;密钥和凭据不得出现在输出中。
|
||||
- `mcp_stdio.dart` 是协议服务入口,stdout 专用于协议,保留其环境配置错误码 64;`release_smoke.dart` 与 Swift 窗口测试是测试进程入口,不套用交互 CLI 参数规范。
|
||||
- Python 同语言测试放在所属平台目录;跨语言入口契约测试在 `tool/tests/`,统一由 `tool/check.py` 执行。缺少宿主能力时明确显示 skip,不将其当作通过。
|
||||
|
||||
内部 UI/native 包边界由 `check_package_boundaries.py` 检查依赖声明与源码引用;应用使用包的公开入口。`check.py` 同时分析 workspace 成员、检查包内脚本语法并运行包内测试。
|
||||
|
||||
桌面原生标题栏回归工具由 [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。
|
||||
@@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check repository tooling without building, signing, 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
|
||||
|
||||
|
||||
def run(command):
|
||||
print('+ ' + ' '.join(map(str, command)), flush=True)
|
||||
subprocess.run(command, cwd=ROOT, check=True)
|
||||
|
||||
|
||||
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.')
|
||||
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')
|
||||
if bash:
|
||||
for path in sorted(path for directory in tool_roots for path in directory.rglob('*.sh')):
|
||||
run([bash, '-n', str(path)])
|
||||
else:
|
||||
print('Shell syntax: skipped (bash unavailable)', flush=True)
|
||||
python = sys.executable
|
||||
run([python, 'tool/check_public_repository.py'])
|
||||
run([python, 'tool/check_package_boundaries.py'])
|
||||
for directory, pattern in [
|
||||
('tool/macos', '*_unit.py'),
|
||||
('tool/tests', '*_test.py'),
|
||||
('tool/windows', 'test_check_windows_release.py'),
|
||||
('tool/windows', '*_unit.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'])
|
||||
package_tests = sorted(str(path.relative_to(ROOT)) for path in (ROOT / 'packages').glob('*/test'))
|
||||
if package_tests:
|
||||
run([flutter, 'test', *package_tests])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,126 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check declared dependencies and public imports across workspace boundaries."""
|
||||
from pathlib import Path
|
||||
import posixpath
|
||||
import re
|
||||
from urllib.parse import unquote
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
RUNTIME = {
|
||||
'cutdex_native': {'flutter', 'path'},
|
||||
'cutdex_ui': {'flutter', 'cutdex_native', 'freezed_annotation'},
|
||||
}
|
||||
DEVELOPMENT = {
|
||||
'cutdex_native': {'flutter_test', 'flutter_lints'},
|
||||
'cutdex_ui': {'flutter_test', 'flutter_lints', 'build_runner', 'freezed'},
|
||||
}
|
||||
TOKENS = re.compile(
|
||||
r"//[^\n]*|/\*.*?\*/|"
|
||||
r"(?P<string>r?(?:\"\"\".*?\"\"\"|'''.*?'''|"
|
||||
r"\"(?:\\.|[^\"\\])*\"|'(?:\\.|[^'\\])*'))|"
|
||||
r"(?P<word>\w+)|(?P<punct>[^\s])",
|
||||
re.DOTALL,
|
||||
)
|
||||
|
||||
|
||||
def directives(source):
|
||||
"""Read URI strings in each directive, including conditional alternatives."""
|
||||
tokens = [token for token in TOKENS.finditer(source) if token.lastgroup]
|
||||
index = 0
|
||||
while index < len(tokens):
|
||||
token = tokens[index]
|
||||
kind = token.group()
|
||||
index += 1
|
||||
if token.lastgroup != 'word' or kind not in ('import', 'export', 'part'):
|
||||
continue
|
||||
if index >= len(tokens) or tokens[index].lastgroup != 'string':
|
||||
continue
|
||||
while index < len(tokens) and tokens[index].group() != ';':
|
||||
token = tokens[index]
|
||||
index += 1
|
||||
if token.lastgroup == 'string':
|
||||
value = token.group()
|
||||
if value.startswith('r'):
|
||||
value = value[1:]
|
||||
quote = value[0] * (3 if value[:3] == value[0] * 3 else 1)
|
||||
yield kind, value[len(quote):-len(quote)]
|
||||
|
||||
|
||||
def package_uri(uri):
|
||||
dependency, _, path = uri.removeprefix('package:').partition('/')
|
||||
return dependency, posixpath.normpath(unquote(path))
|
||||
|
||||
|
||||
def dependency_names(manifest, section):
|
||||
"""Read the flat dependency keys used by our workspace manifests."""
|
||||
match = re.search(rf'^{section}:\s*\n(.*?)(?=^\S|\Z)', manifest,
|
||||
flags=re.MULTILINE | re.DOTALL)
|
||||
if not match:
|
||||
return set()
|
||||
return set(re.findall(r'^ ([\w]+):', match.group(1), re.MULTILINE))
|
||||
|
||||
|
||||
def check(root):
|
||||
errors = []
|
||||
|
||||
def reject(source, message):
|
||||
errors.append(f'{source.relative_to(root)}: {message}')
|
||||
|
||||
for package, allowed in RUNTIME.items():
|
||||
directory = root / 'packages' / package
|
||||
manifest_path = directory / 'pubspec.yaml'
|
||||
manifest = manifest_path.read_text()
|
||||
dependencies = dependency_names(manifest, 'dependencies')
|
||||
dev_dependencies = dependency_names(manifest, 'dev_dependencies')
|
||||
for dependency in sorted(dependencies - allowed):
|
||||
reject(manifest_path, f'forbidden dependency {dependency}')
|
||||
for dependency in sorted(dev_dependencies - DEVELOPMENT[package]):
|
||||
reject(manifest_path, f'forbidden dev_dependency {dependency}')
|
||||
for key, value in [('name', package), ('resolution', 'workspace'), ('publish_to', 'none')]:
|
||||
if not re.search(rf'^{key}:\s*{value}\s*$', manifest, re.MULTILINE):
|
||||
reject(manifest_path, f'expected {key}: {value}')
|
||||
for area in ['lib', 'test', 'tool']:
|
||||
declared = dependencies | {package}
|
||||
if area != 'lib':
|
||||
declared |= dev_dependencies
|
||||
for source in (directory / area).rglob('*.dart'):
|
||||
for kind, uri in directives(source.read_text()):
|
||||
if uri.startswith('package:'):
|
||||
dependency, path = package_uri(uri)
|
||||
if dependency not in declared:
|
||||
reject(source, f'undeclared {kind} {uri}')
|
||||
if dependency != package and (path == 'src' or path.startswith('src/')):
|
||||
reject(source, f'private {kind} {uri}')
|
||||
elif not uri.startswith('dart:'):
|
||||
target = (source.parent / uri).resolve()
|
||||
boundary = directory / ('lib' if area == 'lib' else '')
|
||||
if not target.is_relative_to(boundary.resolve()):
|
||||
reject(source, f'escaping {kind} {uri}')
|
||||
|
||||
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()):
|
||||
if uri.startswith('package:'):
|
||||
dependency, path = package_uri(uri)
|
||||
if dependency != 'cutdex' and (path == 'src' or path.startswith('src/')):
|
||||
reject(source, f'private {kind} {uri}')
|
||||
elif not uri.startswith('dart:'):
|
||||
target = (source.parent / uri).resolve()
|
||||
boundary = root / ('lib' if area == 'lib' else '')
|
||||
if not target.is_relative_to(boundary.resolve()):
|
||||
reject(source, f'escaping {kind} {uri}')
|
||||
if any(target.is_relative_to((root / 'packages' / package).resolve())
|
||||
for package in RUNTIME):
|
||||
reject(source, f'relative workspace {kind} {uri}')
|
||||
return errors
|
||||
|
||||
|
||||
def main():
|
||||
errors = check(ROOT)
|
||||
if errors:
|
||||
raise SystemExit('\n'.join(errors))
|
||||
print('Internal package boundaries: passed')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check publishable source files without Flutter or private dependencies.
|
||||
|
||||
Uses tracked and non-ignored untracked files, leaving local inputs untouched.
|
||||
Credential checks cover recognizable formats, not arbitrary passwords or history.
|
||||
"""
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
from urllib.parse import unquote, urlsplit
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
LOCAL_DIRECTORIES = {
|
||||
'.local', '.dart_tool', '.gradle', '.build', '.swiftpm', '__pycache__',
|
||||
'build', 'coverage', 'Pods', 'ephemeral', 'xcuserdata',
|
||||
}
|
||||
PRIVATE_SUFFIXES = {'.pem', '.key', '.p8', '.p12', '.pfx', '.keystore', '.jks',
|
||||
'.mobileprovision', '.provisionprofile'}
|
||||
CREDENTIALS = re.compile(
|
||||
r'-----BEGIN (?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----|'
|
||||
r'gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|'
|
||||
r'sk-[A-Za-z0-9_-]{24,}|AKIA[0-9A-Z]{16}'
|
||||
)
|
||||
MARKDOWN_LINK = re.compile(r'!?\[[^\]]*\]\(([^\s)]+)\)')
|
||||
|
||||
|
||||
def git_files(root, *arguments):
|
||||
result = subprocess.check_output(['git', 'ls-files', '-z', *arguments], cwd=root)
|
||||
return sorted(set(result.decode('utf-8').split('\0')) - {''})
|
||||
|
||||
|
||||
def check_files(root, names):
|
||||
errors = []
|
||||
root = root.resolve()
|
||||
for name in names:
|
||||
path = root / name
|
||||
if not path.exists() and not path.is_symlink():
|
||||
continue # Worktree deletions are absent from the next source snapshot.
|
||||
if not path.resolve().is_relative_to(root):
|
||||
errors.append(f'{name}: symlink escapes repository')
|
||||
continue
|
||||
if not path.is_file():
|
||||
continue
|
||||
if (LOCAL_DIRECTORIES.intersection(path.relative_to(root).parts)
|
||||
or name.startswith(('validation/', 'test-results/', 'dist/'))
|
||||
or any(part.endswith('.cutdex') for part in path.relative_to(root).parts)
|
||||
or path.name in {'.DS_Store', 'pubspec_overrides.yaml', 'key.properties'}
|
||||
or path.suffix in PRIVATE_SUFFIXES
|
||||
or path.name == '.env'
|
||||
or (path.name.startswith('.env.')
|
||||
and not path.name.endswith(('.example', '.sample')))):
|
||||
errors.append(f'{name}: local artifact or credential configuration')
|
||||
if path.stat().st_size > 50 * 1024 * 1024:
|
||||
errors.append(f'{name}: source file exceeds 50 MiB')
|
||||
continue
|
||||
try:
|
||||
source = path.read_text(encoding='utf-8')
|
||||
except UnicodeError:
|
||||
continue
|
||||
for number, line in enumerate(source.splitlines(), 1):
|
||||
if CREDENTIALS.search(line):
|
||||
# Never echo the matched credential.
|
||||
errors.append(f'{name}:{number}: possible credential; review locally')
|
||||
if path.suffix == '.md':
|
||||
for match in MARKDOWN_LINK.finditer(source):
|
||||
target = urlsplit(match.group(1).strip('<>'))
|
||||
if target.scheme or target.netloc or not target.path:
|
||||
continue
|
||||
linked = (path.parent / unquote(target.path)).resolve()
|
||||
if not linked.is_relative_to(root) or not linked.exists():
|
||||
errors.append(f'{name}: missing or external local link {target.path}')
|
||||
return errors
|
||||
|
||||
|
||||
def main():
|
||||
names = git_files(ROOT, '-co', '--exclude-standard')
|
||||
errors = check_files(ROOT, names)
|
||||
for name in git_files(ROOT, '-ci', '--exclude-standard'):
|
||||
if (ROOT / name).exists():
|
||||
errors.append(f'{name}: ignored file is already tracked')
|
||||
if errors:
|
||||
raise SystemExit('\n'.join(errors))
|
||||
print(f'Public repository source checks: passed ({len(names)} paths considered)')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,39 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex_agent/cutdex_agent.dart';
|
||||
|
||||
void main(List<String> args) {
|
||||
const usage =
|
||||
'Usage: dart run tool/diagnostics/benchmark_agent_context.dart <history.json>';
|
||||
if (args.length == 1 && (args.single == '--help' || args.single == '-h')) {
|
||||
stdout.writeln(usage);
|
||||
return;
|
||||
}
|
||||
if (args.length != 1) {
|
||||
stderr.writeln(usage);
|
||||
exitCode = 2;
|
||||
return;
|
||||
}
|
||||
final history = (jsonDecode(File(args[0]).readAsStringSync()) as List)
|
||||
.map(
|
||||
(m) => AgentMessage.fromJson(
|
||||
Map<String, Object?>.from(m as Map<Object?, Object?>),
|
||||
),
|
||||
)
|
||||
.toList();
|
||||
final builder = HarnessContextBuilder();
|
||||
final current = builder.projectHistory(history);
|
||||
final result = {
|
||||
'messages': history.length,
|
||||
'fullHistoryTokens': builder.measureInput(system: '', history: history),
|
||||
'projectedHistoryTokens': builder.measureInput(
|
||||
system: '',
|
||||
history: current,
|
||||
),
|
||||
'originalBytes': jsonEncode(history.map((m) => m.toJson()).toList()).length,
|
||||
'projectedBytes': jsonEncode(current.map((m) => m.toJson()).toList())
|
||||
.length,
|
||||
};
|
||||
stdout.writeln(const JsonEncoder.withIndent(' ').convert(result));
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:cutdex/diagnostics/diagnostic_store.dart';
|
||||
|
||||
const _usage =
|
||||
'Usage: dart run tool/diagnostics/benchmark_diagnostic_store.dart [--samples=7]';
|
||||
|
||||
Future<void> main(List<String> args) async {
|
||||
if (args.contains('--help') || args.contains('-h')) {
|
||||
stdout.writeln(_usage);
|
||||
return;
|
||||
}
|
||||
var samples = 7;
|
||||
if (args.isNotEmpty) {
|
||||
samples = args.length == 1 && args.single.startsWith('--samples=')
|
||||
? int.tryParse(args.single.substring('--samples='.length)) ?? 0
|
||||
: 0;
|
||||
if (samples < 1 || samples > 100) {
|
||||
stderr.writeln(_usage);
|
||||
exitCode = 2;
|
||||
return;
|
||||
}
|
||||
}
|
||||
final root = await Directory.systemTemp.createTemp('cutdex-log-benchmark-');
|
||||
try {
|
||||
final output = <Object?>[];
|
||||
for (final workload in ['edit', 'error']) {
|
||||
final count = workload == 'edit' ? 256 : 64;
|
||||
final measured = <String, List<Map<String, num>>>{
|
||||
for (final mode in ['disabled', 'perEventFlush', 'batched']) mode: [],
|
||||
};
|
||||
// Warm the serializer and file APIs before collecting samples; alternate order.
|
||||
for (var round = -2; round < samples; round++) {
|
||||
final modes = measured.keys.toList();
|
||||
if (round.isOdd) {
|
||||
modes.setAll(0, modes.reversed.toList());
|
||||
}
|
||||
for (final mode in modes) {
|
||||
final result = await _sample(
|
||||
root,
|
||||
'$workload-$mode-$round',
|
||||
workload,
|
||||
count,
|
||||
mode,
|
||||
);
|
||||
if (round >= 0) measured[mode]!.add(result);
|
||||
}
|
||||
}
|
||||
output.add({
|
||||
'workload': workload,
|
||||
'records': count,
|
||||
'modes': {
|
||||
for (final mode in measured.entries)
|
||||
mode.key: {
|
||||
for (final key in mode.value.first.keys)
|
||||
key: _median(mode.value.map((sample) => sample[key]!).toList()),
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
stdout.writeln(
|
||||
const JsonEncoder.withIndent(' ').convert({
|
||||
'runtime': Platform.version,
|
||||
'os': Platform.operatingSystem,
|
||||
'samples': samples,
|
||||
'warmupRounds': 2,
|
||||
'maxPending': 320,
|
||||
'errorReserveRecords': 40,
|
||||
'maxPendingBytes': 1024 * 1024,
|
||||
'errorReserveBytes': 256 * 1024,
|
||||
'method': 'Synthetic diagnostic record bursts, same store with batchSize=1 versus defaults; disabled measures harness overhead. No Flutter frames or media decoding measured.',
|
||||
'results': output,
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
stderr.writeln('Diagnostic benchmark failed: $error');
|
||||
exitCode = 1;
|
||||
} finally {
|
||||
await root.delete(recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
Future<Map<String, num>> _sample(
|
||||
Directory root,
|
||||
String id,
|
||||
String workload,
|
||||
int count,
|
||||
String mode,
|
||||
) async {
|
||||
final directory = Directory('${root.path}/$id');
|
||||
final store = mode == 'disabled'
|
||||
? null
|
||||
: DiagnosticStore(
|
||||
directory,
|
||||
maxPending: 320,
|
||||
batchSize: mode == 'perEventFlush' ? 1 : 32,
|
||||
);
|
||||
final records = [
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
'at': '2026-10-05T00:00:00.000Z',
|
||||
'sessionId': 'session',
|
||||
'level': workload == 'edit' ? 'info' : 'error',
|
||||
'component': 'editor',
|
||||
'operation': 'split',
|
||||
'environment': {
|
||||
'platform': 'macos',
|
||||
'appVersion': '1.0.0',
|
||||
'buildMode': 'release',
|
||||
},
|
||||
'context': {
|
||||
'operationId': 'operation-$i',
|
||||
'timelineId': 'timeline',
|
||||
'sequenceId': 'sequence',
|
||||
'clipIds': ['clip'],
|
||||
'playheadTick': 5000000,
|
||||
'versionBefore': 'before',
|
||||
'versionAfter': 'after',
|
||||
},
|
||||
if (workload == 'error') ...{
|
||||
'error': {
|
||||
'type': 'StateError',
|
||||
'message': 'Decoder rejected the requested frame',
|
||||
},
|
||||
'stackTrace': List.generate(
|
||||
24,
|
||||
(line) => '#$line editor.dart:120',
|
||||
).join('\n'),
|
||||
'stderr': 'decoder failure at selected frame\n' * 256,
|
||||
},
|
||||
},
|
||||
];
|
||||
final clock = Stopwatch()..start();
|
||||
var previousTick = 0;
|
||||
var maxTimerGapUs = 0;
|
||||
final timer = Timer.periodic(const Duration(milliseconds: 1), (_) {
|
||||
final now = clock.elapsedMicroseconds;
|
||||
maxTimerGapUs = math.max(maxTimerGapUs, now - previousTick);
|
||||
previousTick = now;
|
||||
});
|
||||
final latencies = <int>[];
|
||||
final enqueueStart = clock.elapsedMicroseconds;
|
||||
for (final record in records) {
|
||||
final start = clock.elapsedMicroseconds;
|
||||
store?.record(record);
|
||||
latencies.add(clock.elapsedMicroseconds - start);
|
||||
}
|
||||
final enqueueUs = clock.elapsedMicroseconds - enqueueStart;
|
||||
final drainStart = clock.elapsedMicroseconds;
|
||||
await store?.flush();
|
||||
final drainUs = clock.elapsedMicroseconds - drainStart;
|
||||
timer.cancel();
|
||||
if (store != null) {
|
||||
var persisted = 0;
|
||||
await for (final entity in directory.list()) {
|
||||
if (entity is File && entity.path.endsWith('.jsonl')) {
|
||||
for (final line in await entity.readAsLines()) {
|
||||
jsonDecode(line);
|
||||
persisted++;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (persisted != count || store.dropped != 0 || store.writeFailures != 0) {
|
||||
throw StateError(
|
||||
'Invalid sample: expected $count, persisted $persisted, dropped ${store.dropped}, failures ${store.writeFailures}',
|
||||
);
|
||||
}
|
||||
}
|
||||
latencies.sort();
|
||||
return {
|
||||
'enqueueUs': enqueueUs,
|
||||
'recordP95Us': latencies[(count * .95).ceil() - 1],
|
||||
'drainUs': drainUs,
|
||||
'totalUs': enqueueUs + drainUs,
|
||||
'maxTimerGapUs': maxTimerGapUs,
|
||||
'durableEventAppends': store?.eventFlushes ?? 0,
|
||||
'eventBytesWritten': store?.eventBytesWritten ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
num _median(List<num> values) {
|
||||
values.sort();
|
||||
final middle = values.length ~/ 2;
|
||||
return values.length.isOdd
|
||||
? values[middle]
|
||||
: (values[middle - 1] + values[middle]) / 2;
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Summarize opt-in Release FrameTiming JSONL and optional UTC phase markers.
|
||||
|
||||
Build/raster budget misses are reported separately. Total pipeline latency is
|
||||
not a dropped-frame count. Engine timestamps are not display-present evidence.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import datetime
|
||||
import json
|
||||
|
||||
|
||||
def read_jsonl(path):
|
||||
with open(path, encoding="utf-8-sig") as source:
|
||||
return [json.loads(line) for line in source if line.strip()]
|
||||
|
||||
|
||||
def seconds(timestamp):
|
||||
return datetime.datetime.fromisoformat(timestamp.replace("Z", "+00:00")).timestamp()
|
||||
|
||||
|
||||
def summarize(name, frames):
|
||||
if not frames:
|
||||
return {"name": name, "frames": 0}
|
||||
result = {"name": name, "frames": len(frames)}
|
||||
for column, stage in [(1, "build"), (2, "raster"), (3, "total")]:
|
||||
values = sorted(frame[column] / 1000 for frame in frames)
|
||||
result[stage] = {
|
||||
f"p{int(percentile * 100)}Ms": round(
|
||||
values[int((len(values) - 1) * percentile)], 3
|
||||
)
|
||||
for percentile in [0.5, 0.95, 0.99]
|
||||
}
|
||||
result[stage].update(
|
||||
maxMs=max(values),
|
||||
over60Hz=sum(value > 1000 / 60 for value in values),
|
||||
over120Hz=sum(value > 1000 / 120 for value in values),
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("frames", help="CUTDEX_FRAME_TIMINGS output file")
|
||||
parser.add_argument("phases", nargs="?", help="Optional UTC scenario marker JSONL")
|
||||
args = parser.parse_args()
|
||||
batches = read_jsonl(args.frames)
|
||||
overall = summarize("all", [frame for batch in batches for frame in batch["frames"]])
|
||||
overall["droppedDiagnosticSamples"] = sum(batch.get("dropped", 0) for batch in batches)
|
||||
print(json.dumps(overall))
|
||||
if args.phases:
|
||||
phases = {entry["phase"]: seconds(entry["at"]) for entry in read_jsonl(args.phases)}
|
||||
for name in ["scrub", "zoom", "drag", "clip", "trim", "pan", "play"]:
|
||||
start, end = phases.get(f"{name}-start"), phases.get(f"{name}-end")
|
||||
if start is None or end is None:
|
||||
continue
|
||||
# Allow for the two-second asynchronous reporting batch boundary.
|
||||
frames = [
|
||||
frame
|
||||
for batch in batches
|
||||
if start + 2.2 < seconds(batch["at"]) < end
|
||||
for frame in batch["frames"]
|
||||
]
|
||||
print(json.dumps(summarize(name, frames)))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+85
@@ -0,0 +1,85 @@
|
||||
#!/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,19 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
if [ "$#" -eq 1 ] && { [ "$1" = "--help" ] || [ "$1" = "-h" ]; }; then
|
||||
echo "Usage: $0 <app-executable>"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Replacing native assets under a live Flutter process can load a second SQLite
|
||||
# image on a later lazy FFI lookup, mixing its globals with existing handles.
|
||||
# Check the exact build product, not other installed copies of the application.
|
||||
if [ "$#" -ne 1 ]; then
|
||||
echo 'usage: check_macos_build_target.sh <app-executable>' >&2
|
||||
exit 2
|
||||
fi
|
||||
if /bin/ps -axo comm= | /usr/bin/grep -Fx -- "$1" >/dev/null; then
|
||||
echo 'error: Cutdex is running from this build target. Save your edits and quit it (or stop the debugger), then rebuild. Hot reload does not require a native rebuild.' >&2
|
||||
exit 1
|
||||
fi
|
||||
@@ -0,0 +1,115 @@
|
||||
"""Audit a relocatable arm64 macOS app or processing runtime, without models."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import re
|
||||
import struct
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
|
||||
REQUIRED = (
|
||||
'bin/cutdex-processing-worker', 'bin/ffmpeg', 'bin/ffprobe',
|
||||
'workers/asr/cutdex-asr-worker', 'workers/audio/cutdex-audio-worker',
|
||||
'workers/translation/cutdex-m2m100-worker',
|
||||
)
|
||||
|
||||
|
||||
def output(*args, **kwargs):
|
||||
return subprocess.check_output(args, text=True, timeout=60, **kwargs)
|
||||
|
||||
|
||||
def system(path):
|
||||
return path.startswith(('/System/Library/', '/usr/lib/'))
|
||||
|
||||
|
||||
def audit(root, app=False):
|
||||
root = root.resolve()
|
||||
runtime = root / 'Contents/Resources/processing' if app else root
|
||||
for name in REQUIRED:
|
||||
path = runtime / name
|
||||
if not path.is_file() or not os.access(path, os.X_OK):
|
||||
raise RuntimeError(f'Missing executable: {path}')
|
||||
executable = runtime / REQUIRED[0]
|
||||
if app:
|
||||
info = plistlib.loads((root / 'Contents/Info.plist').read_bytes())
|
||||
executable = root / 'Contents/MacOS' / info['CFBundleExecutable']
|
||||
assets = root / 'Contents/Frameworks/App.framework/Resources/flutter_assets'
|
||||
if not executable.is_file() or not assets.is_dir():
|
||||
raise RuntimeError('Missing app executable or Flutter assets')
|
||||
output('/usr/bin/codesign', '--verify', '--deep', '--strict', str(root))
|
||||
# Check actual contents, not only the native files declared by a manifest.
|
||||
native = {}
|
||||
for path in root.rglob('*'):
|
||||
if path.is_symlink() and not path.resolve().is_relative_to(root):
|
||||
raise RuntimeError(f'Symlink escapes bundle: {path}')
|
||||
if not path.is_file() or path.is_symlink():
|
||||
continue
|
||||
with path.open('rb') as stream:
|
||||
magic = stream.read(4)
|
||||
if magic not in (b'\xcf\xfa\xed\xfe', b'\xfe\xed\xfa\xcf', b'\xca\xfe\xba\xbe', b'\xbe\xba\xfe\xca'):
|
||||
continue
|
||||
arch = output('/usr/bin/lipo', '-archs', str(path)).strip().split()
|
||||
if 'arm64' not in arch:
|
||||
raise RuntimeError(f'Missing arm64 slice: {path}: {arch}')
|
||||
commands = output('/usr/bin/otool', '-arch', 'arm64', '-l', str(path))
|
||||
versions = re.findall(r'\bminos ([\d.]+)', commands)
|
||||
versions += re.findall(r'LC_VERSION_MIN_MACOSX\s+cmdsize \d+\s+version ([\d.]+)', commands)
|
||||
if not versions or any(tuple((list(map(int, v.split('.'))) + [0, 0])[:3]) > (14, 0, 0) for v in versions):
|
||||
raise RuntimeError(f'Minimum macOS exceeds 14.0: {path}: {versions}')
|
||||
rpaths = re.findall(r'LC_RPATH\s+cmdsize \d+\s+path (.*?) \(offset', commands)
|
||||
for entry in rpaths:
|
||||
if not system(entry) and not entry.startswith(('@loader_path/', '@executable_path/')):
|
||||
raise RuntimeError(f'External runtime search path: {path}: {entry}')
|
||||
imports = output('/usr/bin/otool', '-arch', 'arm64', '-L', str(path)).splitlines()[1:]
|
||||
identity = output('/usr/bin/otool', '-arch', 'arm64', '-D', str(path)).splitlines()[1:]
|
||||
native[path] = (rpaths, [line.strip().split(' (compatibility version')[0] for line in imports if line.strip().split(' (compatibility version')[0] not in identity])
|
||||
if executable.resolve() not in native:
|
||||
raise RuntimeError(f'Not a Mach-O executable: {executable}')
|
||||
for path, (rpaths, dependencies) in native.items():
|
||||
def expand(entry, owner):
|
||||
return Path(entry.replace('@loader_path', str(owner.parent)).replace('@executable_path', str(executable.parent)))
|
||||
search = [expand(p, path) for p in rpaths]
|
||||
search += [expand(p, executable) for p in native[executable.resolve()][0]]
|
||||
for dependency in dependencies:
|
||||
if system(dependency):
|
||||
continue
|
||||
if dependency.startswith('@rpath/'):
|
||||
candidates = [p / dependency[len('@rpath/'):] for p in search]
|
||||
elif dependency.startswith(('@loader_path/', '@executable_path/')):
|
||||
candidates = [expand(dependency, path)]
|
||||
else:
|
||||
raise RuntimeError(f'External native dependency: {path}: {dependency}')
|
||||
if not any(p.resolve().is_relative_to(root) and p.is_file() for p in candidates):
|
||||
raise RuntimeError(f'Unresolved bundled dependency: {path}: {dependency}')
|
||||
with tempfile.TemporaryDirectory(prefix='cutdex-package-check-') as temporary:
|
||||
env = {'PATH': '/usr/bin:/bin', 'HOME': temporary, 'TMPDIR': temporary}
|
||||
descriptors = json.loads(output(str(runtime / REQUIRED[0]), '--capabilities', env=env))
|
||||
operations = {op for d in descriptors if d['available'] for op in d['operations']}
|
||||
if not {'transcribeAudio', 'translateSubtitles', 'separateVocals'}.issubset(operations):
|
||||
raise RuntimeError('Bundled processing capabilities unavailable')
|
||||
for name in REQUIRED[1:3]:
|
||||
output(str(runtime / name), '-version', env=env)
|
||||
for name in REQUIRED[3:5]:
|
||||
output(str(runtime / name), '--self-test', env=env)
|
||||
result = subprocess.check_output([str(runtime / REQUIRED[5]), '--self-test'], env=env, timeout=60)
|
||||
payload = '你好\r\n\x1a!'.encode('utf-8')
|
||||
if result != struct.pack('<I', len(payload)) + payload:
|
||||
raise RuntimeError('Translation worker self-test failed')
|
||||
return {'root': str(root), 'nativeFiles': len(native), 'operations': sorted(operations), 'modelsRequired': False}
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
group = parser.add_mutually_exclusive_group(required=True)
|
||||
group.add_argument('--app', type=Path)
|
||||
group.add_argument('--runtime', type=Path)
|
||||
parser.add_argument('--report', type=Path)
|
||||
args = parser.parse_args()
|
||||
result = audit(args.app or args.runtime, app=args.app is not None)
|
||||
encoded = json.dumps(result, indent=2) + '\n'
|
||||
if args.report:
|
||||
args.report.write_text(encoded)
|
||||
print(encoded, end='')
|
||||
@@ -0,0 +1,61 @@
|
||||
#!/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"
|
||||
@@ -0,0 +1,157 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Configure Sparkle before signing and prepare full-only update publications."""
|
||||
import argparse
|
||||
import base64
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
from urllib.parse import urlsplit
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
SPARKLE = 'http://www.andymatuschak.org/xml-namespaces/sparkle'
|
||||
|
||||
|
||||
def validate_url(value, local=False):
|
||||
url = urlsplit(value)
|
||||
if not url.hostname or url.username or url.password or url.fragment or url.query:
|
||||
raise ValueError('Use an absolute update URL without credentials, query or fragment')
|
||||
if url.scheme != 'https' and not (
|
||||
local and url.scheme == 'http' and url.hostname == 'localhost'
|
||||
):
|
||||
raise ValueError('Updates require HTTPS (local testing permits http://localhost only)')
|
||||
return value
|
||||
|
||||
|
||||
def validate_key(value):
|
||||
if len(base64.b64decode(value, validate=True)) != 32:
|
||||
raise ValueError('Sparkle requires a base64-encoded 32-byte public key')
|
||||
return value
|
||||
|
||||
|
||||
def configure(app, feed, public_key, local=False):
|
||||
info_path = app / 'Contents/Info.plist'
|
||||
info = plistlib.loads(info_path.read_bytes())
|
||||
if local and info['CFBundleIdentifier'] != 'app.cutdex.desktop.dev':
|
||||
raise ValueError('Local updates are restricted to the development app')
|
||||
info['DeskupAllowLocalHTTP'] = bool(local)
|
||||
info['SUFeedURL'] = validate_url(feed, local)
|
||||
info['SUPublicEDKey'] = validate_key(public_key)
|
||||
info['SUEnableAutomaticChecks'] = False
|
||||
info['SUAllowsAutomaticUpdates'] = False
|
||||
info['SUAutomaticallyUpdate'] = False
|
||||
if local:
|
||||
# Narrow ATS exception: no arbitrary network loads, never in production.
|
||||
ats = info.setdefault('NSAppTransportSecurity', {})
|
||||
ats.setdefault('NSExceptionDomains', {})['localhost'] = {
|
||||
'NSExceptionAllowsInsecureHTTPLoads': True,
|
||||
'NSIncludesSubdomains': False,
|
||||
}
|
||||
info_path.write_bytes(plistlib.dumps(info))
|
||||
|
||||
|
||||
def validate_app(app, local=False):
|
||||
info = plistlib.loads((app / 'Contents/Info.plist').read_bytes())
|
||||
validate_url(info['SUFeedURL'], local)
|
||||
validate_key(info['SUPublicEDKey'])
|
||||
expected_id = 'app.cutdex.desktop.dev' if local else 'app.cutdex.desktop'
|
||||
if info['CFBundleIdentifier'] != expected_id:
|
||||
raise ValueError('Wrong application identity for this update channel')
|
||||
if not re.fullmatch(r'[0-9]+(?:\.[0-9]+){0,2}', info['CFBundleVersion']):
|
||||
raise ValueError('Use a monotonically increasing numeric build version')
|
||||
framework = app / 'Contents/Frameworks/Sparkle.framework'
|
||||
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)
|
||||
if not local:
|
||||
subprocess.run(['xcrun', 'stapler', 'validate', str(app)], check=True)
|
||||
subprocess.run(['spctl', '--assess', '--type', 'execute', str(app)], check=True)
|
||||
return info
|
||||
|
||||
|
||||
|
||||
def version_key(version):
|
||||
if not re.fullmatch(r'[0-9]+(?:\.[0-9]+){0,2}', version):
|
||||
raise ValueError(f'Invalid numeric build version: {version}')
|
||||
parts = tuple(map(int, version.split('.')))
|
||||
return parts + (0,) * (3 - len(parts))
|
||||
|
||||
|
||||
def require_newer_build(output, version):
|
||||
feed = output / 'appcast.xml'
|
||||
if not feed.exists():
|
||||
return
|
||||
items = ET.parse(feed).findall('./channel/item')
|
||||
for item in items:
|
||||
current = item.findtext(f'{{{SPARKLE}}}version')
|
||||
if current is None:
|
||||
enclosure = item.find('enclosure')
|
||||
current = None if enclosure is None else enclosure.get(f'{{{SPARKLE}}}version')
|
||||
if current is None:
|
||||
raise ValueError('Existing appcast item is missing its build version')
|
||||
if version_key(version) <= version_key(current):
|
||||
raise ValueError(f'New build {version} must be newer than published build {current}')
|
||||
|
||||
|
||||
def publish(app, output, base_url, tools, key_file=None, local=False):
|
||||
"""Stage a complete publication; never mutate an existing version archive."""
|
||||
validate_url(base_url, local)
|
||||
info = validate_app(app, local)
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
require_newer_build(output, info['CFBundleVersion'])
|
||||
filename = f"cutdex-{info['CFBundleVersion']}-macos-arm64.zip"
|
||||
archive = output / filename
|
||||
if archive.exists():
|
||||
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)
|
||||
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)
|
||||
tree = ET.parse(stage / 'appcast.xml')
|
||||
if tree.findall(f'.//{{{SPARKLE}}}deltas'):
|
||||
raise ValueError('This release pipeline only permits full updates')
|
||||
enclosures = tree.findall('.//enclosure')
|
||||
if len(enclosures) != 1 or not enclosures[0].get(f'{{{SPARKLE}}}edSignature'):
|
||||
raise ValueError('Expected exactly one signed full update')
|
||||
# Upload archive first, appcast last. Local replacement is atomic too.
|
||||
shutil.copy2(stage / filename, archive)
|
||||
pending = output / 'appcast.xml.pending'
|
||||
shutil.copy2(stage / 'appcast.xml', pending)
|
||||
pending.replace(output / 'appcast.xml')
|
||||
return archive
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
commands = parser.add_subparsers(dest='command', required=True)
|
||||
config = commands.add_parser('configure')
|
||||
config.add_argument('--app', type=Path, required=True)
|
||||
config.add_argument('--feed', required=True)
|
||||
config.add_argument('--public-key', required=True)
|
||||
config.add_argument('--local', action='store_true')
|
||||
release = commands.add_parser('publish')
|
||||
release.add_argument('--app', type=Path, required=True)
|
||||
release.add_argument('--output', type=Path, required=True)
|
||||
release.add_argument('--base-url', required=True)
|
||||
release.add_argument('--tools', type=Path, required=True, help='Sparkle bin directory')
|
||||
release.add_argument('--key-file', type=Path)
|
||||
release.add_argument('--local', action='store_true')
|
||||
args = parser.parse_args()
|
||||
if args.command == 'configure':
|
||||
configure(args.app, args.feed, args.public_key, args.local)
|
||||
else:
|
||||
print(publish(args.app, args.output, args.base_url, args.tools.resolve(),
|
||||
args.key_file, args.local))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,19 @@
|
||||
import AppKit
|
||||
import Foundation
|
||||
|
||||
let arguments = Array(CommandLine.arguments.dropFirst())
|
||||
let usage = "Usage: swift set_macos_file_icon.swift <icon-file> <target-file>\n"
|
||||
if arguments == ["--help"] || arguments == ["-h"] {
|
||||
print(usage, terminator: "")
|
||||
exit(0)
|
||||
}
|
||||
guard arguments.count == 2 else {
|
||||
fputs(usage, stderr)
|
||||
exit(2)
|
||||
}
|
||||
guard FileManager.default.fileExists(atPath: arguments[1]),
|
||||
let icon = NSImage(contentsOfFile: arguments[0]),
|
||||
NSWorkspace.shared.setIcon(icon, forFile: arguments[1], options: []) else {
|
||||
fputs("Failed to set file icon: verify the icon and target paths\n", stderr)
|
||||
exit(1)
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
#!/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"
|
||||
@@ -0,0 +1,44 @@
|
||||
// Local simulation only. Creates an isolated key file; never touches Keychain.
|
||||
import CryptoKit
|
||||
import Foundation
|
||||
|
||||
let arguments = Array(CommandLine.arguments.dropFirst())
|
||||
let usage = "Usage: swift sparkle_test_key.swift <test-key-directory>\n"
|
||||
if arguments == ["--help"] || arguments == ["-h"] {
|
||||
print(usage, terminator: "")
|
||||
exit(0)
|
||||
}
|
||||
guard arguments.count == 1 else {
|
||||
fputs(usage, stderr)
|
||||
exit(2)
|
||||
}
|
||||
|
||||
do {
|
||||
let directory = URL(fileURLWithPath: arguments[0], isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true,
|
||||
attributes: [.posixPermissions: 0o700])
|
||||
let privateURL = directory.appendingPathComponent("private.key")
|
||||
let key: Curve25519.Signing.PrivateKey
|
||||
if FileManager.default.fileExists(atPath: privateURL.path) {
|
||||
let encoded = try String(contentsOf: privateURL, encoding: .utf8)
|
||||
guard let data = Data(base64Encoded: encoded) else {
|
||||
fputs("Invalid test key file\n", stderr)
|
||||
exit(1)
|
||||
}
|
||||
key = try Curve25519.Signing.PrivateKey(rawRepresentation: data)
|
||||
} else {
|
||||
key = Curve25519.Signing.PrivateKey()
|
||||
guard FileManager.default.createFile(atPath: privateURL.path,
|
||||
contents: key.rawRepresentation.base64EncodedData(),
|
||||
attributes: [.posixPermissions: 0o600]) else {
|
||||
fputs("Could not write test key file\n", stderr)
|
||||
exit(1)
|
||||
}
|
||||
}
|
||||
try key.publicKey.rawRepresentation.base64EncodedString().write(
|
||||
to: directory.appendingPathComponent("public.key"), atomically: true, encoding: .utf8)
|
||||
} catch {
|
||||
// Do not print private key contents in diagnostics.
|
||||
fputs("Could not create or read test key files\n", stderr)
|
||||
exit(1)
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Fault injection against a real extracted runtime; never modifies the source."""
|
||||
import argparse
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
spec = importlib.util.spec_from_file_location('release_check', Path(__file__).with_name('check_macos_release.py'))
|
||||
check = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(check)
|
||||
|
||||
|
||||
def rejected(root, expected):
|
||||
try:
|
||||
check.audit(root)
|
||||
except RuntimeError as error:
|
||||
if expected not in str(error):
|
||||
raise
|
||||
print(f'Correctly rejected: {expected}')
|
||||
else:
|
||||
raise AssertionError(f'Did not reject: {expected}')
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--runtime', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
with tempfile.TemporaryDirectory(prefix='cutdex-audit-faults-') as temporary:
|
||||
root = Path(temporary) / 'runtime'
|
||||
shutil.copytree(args.runtime, root, symlinks=True)
|
||||
worker = root / 'workers/asr/cutdex-asr-worker'
|
||||
held = worker.with_suffix('.held')
|
||||
worker.rename(held)
|
||||
rejected(root, 'Missing executable')
|
||||
held.rename(worker)
|
||||
# Use the actual package's version instead of pinning FFmpeg's ABI.
|
||||
library = next((root / 'lib').glob('libavcodec.*.dylib'))
|
||||
saved = Path(temporary) / library.name
|
||||
library.rename(saved)
|
||||
rejected(root, 'Unresolved bundled dependency')
|
||||
saved.rename(library)
|
||||
link = root / 'external-library'
|
||||
link.symlink_to('/usr/lib')
|
||||
rejected(root, 'Symlink escapes bundle')
|
||||
link.unlink()
|
||||
backup = Path(temporary) / 'asr-backup'
|
||||
shutil.copy2(worker, backup)
|
||||
subprocess.run(['/usr/bin/install_name_tool', '-add_rpath', '/tmp/developer-libraries', str(worker)], check=True)
|
||||
rejected(root, 'External runtime search path')
|
||||
shutil.copy2(backup, worker)
|
||||
print(check.audit(root))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Build and relocate a Release smoke app; exercise no-model and configured-model startup.
|
||||
|
||||
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.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
|
||||
def run(command, **kwargs):
|
||||
subprocess.run(list(map(str, command)), check=True, timeout=900, **kwargs)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--runtime', type=Path, required=True)
|
||||
parser.add_argument('--config', type=Path, required=True)
|
||||
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())
|
||||
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)
|
||||
with tempfile.TemporaryDirectory(prefix='cutdex relocated release ') as temporary:
|
||||
root = Path(temporary)
|
||||
app = root / 'cutdex.app'
|
||||
run(['/usr/bin/ditto', repo / 'build/macos/Build/Products/Release-production/cutdex.app', app])
|
||||
# A previous release build may have embedded a different runtime.
|
||||
embedded = app / 'Contents/Resources/processing'
|
||||
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])
|
||||
results = []
|
||||
for configured in [False, True]:
|
||||
home = root / ('with-models' if configured else 'without-models')
|
||||
home.mkdir()
|
||||
report = home / 'result.json'
|
||||
env = {'PATH': '/usr/bin:/bin', 'HOME': str(home), 'TMPDIR': str(home),
|
||||
'CUTDEX_SMOKE_REPORT': str(report), 'CUTDEX_SMOKE_MODELS': str(int(configured)),
|
||||
'CUTDEX_SMOKE_MEDIA': config['CUTDEX_ASR_FIXTURE']}
|
||||
# No CUTDEX_PROCESSING_ROOT: exercise the executable-relative Bundle default.
|
||||
if configured:
|
||||
processing = home / 'Documents/Cutdex/Resources/Processing'
|
||||
shutil.copytree(config['WHISPER_SOURCE'],
|
||||
processing / 'Transcription/whisper-turbo/1')
|
||||
shutil.copytree(config['M2M100_SOURCE'],
|
||||
processing / 'Translation/m2m100-418m/1')
|
||||
vocals = processing / 'VocalSeparation/melband/1'
|
||||
vocals.mkdir(parents=True)
|
||||
shutil.copy2(config['MELBAND_SOURCE'], vocals / 'melband.pt')
|
||||
with (home / 'app.log').open('w') as log:
|
||||
try:
|
||||
run([app / 'Contents/MacOS/cutdex'], env=env, stdout=log, stderr=subprocess.STDOUT)
|
||||
except Exception:
|
||||
print((home / 'app.log').read_text())
|
||||
if report.exists():
|
||||
print(report.read_text())
|
||||
raise
|
||||
result = json.loads(report.read_text())
|
||||
if not result['passed']:
|
||||
raise RuntimeError(result)
|
||||
results.append(result)
|
||||
args.report.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.report.write_text(json.dumps(results, indent=2) + '\n')
|
||||
print('Release smoke passed: no models; three configured capabilities and real translation.')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,84 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Prepare two development apps and serve a signed full update on localhost."""
|
||||
import argparse
|
||||
from functools import partial
|
||||
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
|
||||
import os
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import subprocess
|
||||
|
||||
from macos_updates import configure, publish
|
||||
|
||||
|
||||
class UpdateHandler(SimpleHTTPRequestHandler):
|
||||
def end_headers(self):
|
||||
self.send_header('Cache-Control', 'no-store')
|
||||
super().end_headers()
|
||||
|
||||
def list_directory(self, path):
|
||||
self.send_error(404)
|
||||
return None
|
||||
|
||||
|
||||
def prepare(source, root, tools, port):
|
||||
repository = Path(__file__).resolve().parents[2]
|
||||
root = root.resolve()
|
||||
public = root / 'public'
|
||||
keys = root / 'keys'
|
||||
if (root / 'installed').exists() or public.exists():
|
||||
raise ValueError('Use a fresh output directory to preserve existing test installs')
|
||||
subprocess.run(['swift', str(repository / 'tool/macos/sparkle_test_key.swift'), str(keys)], check=True)
|
||||
public_key = (keys / 'public.key').read_text()
|
||||
feed = f'http://localhost:{port}/appcast.xml'
|
||||
info = plistlib.loads((source / 'Contents/Info.plist').read_bytes())
|
||||
if info['CFBundleIdentifier'] != 'app.cutdex.desktop.dev':
|
||||
raise ValueError('Build with --flavor development first')
|
||||
for folder, version in [('installed', '900001'), ('candidate', '900002')]:
|
||||
app = root / folder / 'cutdex.app'
|
||||
app.parent.mkdir(parents=True)
|
||||
subprocess.run(['ditto', str(source), str(app)], check=True)
|
||||
path = app / 'Contents/Info.plist'
|
||||
bundle = plistlib.loads(path.read_bytes())
|
||||
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)
|
||||
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)
|
||||
print('Settings → Check for updates: 900001 → 900002 (full ZIP)', flush=True)
|
||||
return public
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--app', type=Path, help='Built development app')
|
||||
parser.add_argument('--tools', type=Path, help='Sparkle bin directory')
|
||||
parser.add_argument('--output', type=Path, default=Path('.local/update-test'))
|
||||
parser.add_argument('--port', type=int, default=8765)
|
||||
parser.add_argument('--serve-only', action='store_true')
|
||||
args = parser.parse_args()
|
||||
if args.serve_only:
|
||||
public = args.output.resolve() / 'public'
|
||||
else:
|
||||
if not args.app or not args.tools:
|
||||
parser.error('--app and --tools are required unless --serve-only')
|
||||
public = prepare(args.app, args.output, args.tools, args.port)
|
||||
if not (public / 'appcast.xml').is_file():
|
||||
parser.error('No prepared appcast.xml')
|
||||
# Only public artifacts are served. Private keys live outside this root.
|
||||
server = ThreadingHTTPServer(('127.0.0.1', args.port),
|
||||
partial(UpdateHandler, directory=str(public)))
|
||||
print(f'Serving http://localhost:{args.port}/appcast.xml', flush=True)
|
||||
try:
|
||||
server.serve_forever()
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
server.server_close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Release channel isolation and full update validation regression tests."""
|
||||
import base64
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from macos_updates import configure, validate_url, publish, SPARKLE
|
||||
|
||||
|
||||
class UpdateConfigurationTests(unittest.TestCase):
|
||||
def test_production_rejects_local_feed(self):
|
||||
with self.assertRaises(ValueError):
|
||||
validate_url('http://localhost:8765/appcast.xml')
|
||||
with self.assertRaises(ValueError):
|
||||
validate_url('http://example.com/appcast.xml', local=True)
|
||||
with self.assertRaises(ValueError):
|
||||
validate_url('https://user:password@example.com/appcast.xml')
|
||||
|
||||
def test_local_configuration_is_scoped_to_development(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
app = Path(directory) / 'cutdex.app'
|
||||
(app / 'Contents').mkdir(parents=True)
|
||||
path = app / 'Contents/Info.plist'
|
||||
key = base64.b64encode(bytes(range(32))).decode()
|
||||
original = {'CFBundleIdentifier': 'app.cutdex.desktop'}
|
||||
path.write_bytes(plistlib.dumps(original))
|
||||
with self.assertRaises(ValueError):
|
||||
configure(app, 'http://localhost:8765/appcast.xml', key, local=True)
|
||||
self.assertEqual(plistlib.loads(path.read_bytes()), original)
|
||||
original['CFBundleIdentifier'] += '.dev'
|
||||
path.write_bytes(plistlib.dumps(original))
|
||||
configure(app, 'http://localhost:8765/appcast.xml', key, local=True)
|
||||
info = plistlib.loads(path.read_bytes())
|
||||
self.assertFalse(info['SUAllowsAutomaticUpdates'])
|
||||
self.assertFalse(info['SUEnableAutomaticChecks'])
|
||||
self.assertNotIn('NSAllowsArbitraryLoads', info['NSAppTransportSecurity'])
|
||||
self.assertEqual(set(info['NSAppTransportSecurity']['NSExceptionDomains']), {'localhost'})
|
||||
|
||||
def test_invalid_public_key_does_not_change_app(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
app = Path(directory)
|
||||
(app / 'Contents').mkdir()
|
||||
path = app / 'Contents/Info.plist'
|
||||
original = plistlib.dumps({'CFBundleIdentifier': 'app.cutdex.desktop'})
|
||||
path.write_bytes(original)
|
||||
with self.assertRaises(ValueError):
|
||||
configure(app, 'https://updates.example.com/appcast.xml', 'YQ==')
|
||||
self.assertEqual(path.read_bytes(), original)
|
||||
|
||||
|
||||
class PublicationVersionTests(unittest.TestCase):
|
||||
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:
|
||||
output = Path(directory)
|
||||
feed = output / 'appcast.xml'
|
||||
original = (f'<rss xmlns:sparkle="{SPARKLE}"><channel><item>'
|
||||
f'<sparkle:version>{current}</sparkle:version>'
|
||||
'</item></channel></rss>').encode()
|
||||
feed.write_bytes(original)
|
||||
def generate(command, **kwargs):
|
||||
if command[0] == 'ditto':
|
||||
Path(command[-1]).write_bytes(b'archive')
|
||||
else:
|
||||
Path(command[command.index('-o') + 1]).write_text(
|
||||
f'<rss xmlns:sparkle="{SPARKLE}"><channel><item>'
|
||||
f'<sparkle:version>{candidate}</sparkle:version>'
|
||||
'<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:
|
||||
with self.assertRaisesRegex(ValueError, 'newer'):
|
||||
publish(Path('app'), output, 'https://example.com/', Path('tools'))
|
||||
run.assert_not_called()
|
||||
self.assertEqual(feed.read_bytes(), original)
|
||||
self.assertEqual(list(output.glob('*.zip')), [])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,47 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
/// Launch this from an MCP client while the configured Cutdex editor is open.
|
||||
Future<void> main() async {
|
||||
final port = int.tryParse(Platform.environment['CUTDEX_MCP_PORT'] ?? '');
|
||||
final token = Platform.environment['CUTDEX_MCP_TOKEN'];
|
||||
if (port == null ||
|
||||
port < 1 ||
|
||||
port > 65535 ||
|
||||
token == null ||
|
||||
token.length < 32 ||
|
||||
token.length > 1024 ||
|
||||
token.contains('\n') ||
|
||||
token.contains('\r')) {
|
||||
stderr.writeln(
|
||||
'Set CUTDEX_MCP_PORT and CUTDEX_MCP_TOKEN to match the running app.',
|
||||
);
|
||||
exitCode = 64;
|
||||
return;
|
||||
}
|
||||
Socket? socket;
|
||||
StreamSubscription<List<int>>? input;
|
||||
try {
|
||||
final connection = await Socket.connect(
|
||||
InternetAddress.loopbackIPv4,
|
||||
port,
|
||||
timeout: const Duration(seconds: 5),
|
||||
);
|
||||
socket = connection;
|
||||
connection.add(utf8.encode('$token\n'));
|
||||
input = stdin.listen(
|
||||
connection.add,
|
||||
onDone: connection.destroy,
|
||||
onError: (Object _) => connection.destroy(),
|
||||
);
|
||||
await stdout.addStream(connection);
|
||||
await stdout.flush();
|
||||
} catch (_) {
|
||||
stderr.writeln('Could not connect to the Cutdex MCP endpoint.');
|
||||
exitCode = 1;
|
||||
} finally {
|
||||
await input?.cancel();
|
||||
socket?.destroy();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
// A separate Release test entrypoint. Never included in the distributed app.
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:cutdex/integrations/runtime/processing_configuration.dart';
|
||||
import 'package:cutdex/workspace/persistence/project_workspace.dart';
|
||||
import 'package:cutdex/workspace/persistence/timeline_creation_names.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/preview.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
|
||||
void require(bool condition, String message) {
|
||||
if (!condition) throw StateError(message);
|
||||
}
|
||||
|
||||
Future<void> waitFor(bool Function() complete) async {
|
||||
final timer = Stopwatch()..start();
|
||||
while (!complete()) {
|
||||
if (timer.elapsed > const Duration(minutes: 2)) {
|
||||
throw StateError('Release smoke test timed out');
|
||||
}
|
||||
await Future<void>.delayed(const Duration(milliseconds: 30));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
final report = File(Platform.environment['CUTDEX_SMOKE_REPORT']!);
|
||||
final root = await Directory.systemTemp.createTemp('cutdex-release-smoke-');
|
||||
ProjectWorkspace? workspace;
|
||||
PreviewController? preview;
|
||||
var code = 1;
|
||||
try {
|
||||
final config = ProcessingConfiguration.configured(
|
||||
resourcesRoot: Platform.environment['CUTDEX_SMOKE_RESOURCES'],
|
||||
);
|
||||
require(config != null, 'Bundled processing runtime was not found');
|
||||
final models = Platform.environment['CUTDEX_SMOKE_MODELS'] == '1';
|
||||
require(
|
||||
(config!.transcriptionModel != null) == models,
|
||||
'ASR configuration',
|
||||
);
|
||||
require(
|
||||
(config.translationModel != null) == models,
|
||||
'Translation configuration',
|
||||
);
|
||||
require(
|
||||
(config.vocalSeparationModel != null) == models,
|
||||
'Vocals configuration',
|
||||
);
|
||||
workspace = ProjectWorkspace(
|
||||
processing: config,
|
||||
creationNames: const TimelineCreationNames(
|
||||
timeline: 'Timeline 1',
|
||||
sequence: 'Main sequence',
|
||||
storyline: 'Main storyline',
|
||||
),
|
||||
);
|
||||
await workspace.open('${root.path}/Smoke.cutdex', name: 'Release smoke');
|
||||
final timelines = await workspace.createTimeline('Playback');
|
||||
final project = workspace.project!;
|
||||
final source = File(Platform.environment['CUTDEX_SMOKE_MEDIA']!);
|
||||
final video = Platform.environment['CUTDEX_SMOKE_VIDEO'] == '1';
|
||||
final asset = await project.importFile(source, name: 'Audio');
|
||||
final document = await workspace.loadTimeline(
|
||||
project.info.id,
|
||||
timelines.last.id,
|
||||
);
|
||||
final session = await workspace.openTimelineSession(
|
||||
project.info.id,
|
||||
document,
|
||||
);
|
||||
final media = await workspace
|
||||
.prepareMedia(project.info.id, asset.id)
|
||||
.timeout(const Duration(minutes: 2));
|
||||
session.insertAsset(
|
||||
sequenceId: session.activeSequenceId!,
|
||||
assetId: asset.id,
|
||||
assetName: 'Audio',
|
||||
uri: media.uri,
|
||||
duration: media.duration,
|
||||
position: 0,
|
||||
kind: video ? 'video' : 'audio',
|
||||
hasAudio: true,
|
||||
clipId: ElementId('audio'),
|
||||
);
|
||||
for (final operation in [
|
||||
EditorOperation.startTranscription,
|
||||
EditorOperation.startSubtitleTranslation,
|
||||
EditorOperation.startVocalSeparation,
|
||||
]) {
|
||||
require(
|
||||
session.supportedCommandOperations.contains(operation) == models,
|
||||
'Capability: $operation',
|
||||
);
|
||||
}
|
||||
preview = PreviewController(
|
||||
timeline: session,
|
||||
activeSequence: () => session.activeSequenceId,
|
||||
viewForSequence: session.view,
|
||||
runtime: CutdexRuntime(),
|
||||
);
|
||||
await preview.initialize();
|
||||
require(
|
||||
preview.ready && preview.error == null,
|
||||
'Native preview initialization',
|
||||
);
|
||||
final canvasKey = GlobalKey();
|
||||
if (video) {
|
||||
runApp(
|
||||
ProviderScope(
|
||||
child: Directionality(
|
||||
textDirection: TextDirection.ltr,
|
||||
child: RepaintBoundary(
|
||||
key: canvasKey,
|
||||
child: RuntimePreview(session: preview.session!),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
final activePreview = preview;
|
||||
await preview.controlPreview(session.activeSequenceId!, PreviewAction.play);
|
||||
await waitFor(
|
||||
() =>
|
||||
activePreview.positionTick > TimelineClock.ticksPerSecond ~/ 5 ||
|
||||
activePreview.error != null,
|
||||
);
|
||||
require(preview.error == null, 'Native playback: ${preview.error}');
|
||||
await preview.controlPreview(
|
||||
session.activeSequenceId!,
|
||||
PreviewAction.pause,
|
||||
);
|
||||
if (video) {
|
||||
await WidgetsBinding.instance.endOfFrame.timeout(
|
||||
const Duration(seconds: 20),
|
||||
);
|
||||
final boundary =
|
||||
canvasKey.currentContext!.findRenderObject()!
|
||||
as RenderRepaintBoundary;
|
||||
final image = await boundary.toImage();
|
||||
try {
|
||||
final rgba = await image.toByteData();
|
||||
final pixels = rgba!.buffer.asUint8List();
|
||||
final colors = <int>{};
|
||||
for (var i = 0; i < pixels.length; i += 4) {
|
||||
colors.add((pixels[i] << 16) | (pixels[i + 1] << 8) | pixels[i + 2]);
|
||||
if (colors.length > 32) break;
|
||||
}
|
||||
require(colors.length > 32, 'Preview is blank or has too few colors');
|
||||
final png = await image.toByteData(format: ui.ImageByteFormat.png);
|
||||
await File('${report.path}.png')
|
||||
.writeAsBytes(png!.buffer.asUint8List());
|
||||
} finally {
|
||||
image.dispose();
|
||||
}
|
||||
final output = await session.exports.start(
|
||||
session.activeSequenceId!,
|
||||
ExportProject(destination: '${report.path}.mp4'),
|
||||
);
|
||||
final exported = await CutdexRuntime().probe(
|
||||
MediaReference(id: 'exported', uri: output),
|
||||
);
|
||||
require(exported.videoTrackCount == 1, 'Exported video track');
|
||||
require(exported.audioTrackCount == 1, 'Exported audio track');
|
||||
require(
|
||||
(exported.duration.seconds - media.duration.seconds).abs() < .2,
|
||||
'Exported duration',
|
||||
);
|
||||
}
|
||||
if (models) {
|
||||
final subtitles = File('${root.path}/subtitles.json');
|
||||
await subtitles.writeAsString(
|
||||
jsonEncode({
|
||||
'schemaVersion': 1,
|
||||
'language': 'en',
|
||||
'cues': [
|
||||
{
|
||||
'startMs': 0,
|
||||
'endMs': 1000,
|
||||
'text': 'Hello, welcome to the video.',
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
final task = await session.transcriptions!.startTranslation(
|
||||
StartSubtitleTranslation(
|
||||
source: subtitles.path,
|
||||
sourceLanguage: 'en',
|
||||
targetLanguage: 'zh',
|
||||
threads: 2,
|
||||
),
|
||||
);
|
||||
await waitFor(() => task.terminal);
|
||||
require(
|
||||
task.status == TranscriptionStatus.succeeded,
|
||||
'Translation: ${task.error}',
|
||||
);
|
||||
require(task.result!.document.cues.isNotEmpty, 'Translated cues');
|
||||
}
|
||||
await report.writeAsString(
|
||||
jsonEncode({
|
||||
'passed': true,
|
||||
'models': models,
|
||||
'videoPreviewAndExport': video,
|
||||
'playbackTick': preview.positionTick,
|
||||
'executable': Platform.resolvedExecutable,
|
||||
}),
|
||||
);
|
||||
code = 0;
|
||||
} catch (error, stack) {
|
||||
await report.writeAsString(
|
||||
jsonEncode({'passed': false, 'error': '$error', 'stack': '$stack'}),
|
||||
);
|
||||
} finally {
|
||||
await preview?.close();
|
||||
await workspace?.close();
|
||||
await root.delete(recursive: true);
|
||||
}
|
||||
exit(code);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
// Dedicated test app: never distribute its release packages.
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
const channel = MethodChannel('deskup');
|
||||
const smokeRoot = String.fromEnvironment('CUTDEX_UPDATE_SMOKE_ROOT');
|
||||
|
||||
void main() {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
// The isolated smoke fixture depends only on Flutter, without Riverpod.
|
||||
// ignore: riverpod_lint/missing_provider_scope
|
||||
runApp(
|
||||
const MaterialApp(
|
||||
home: Scaffold(body: Center(child: Text('Cutdex update test'))),
|
||||
),
|
||||
);
|
||||
unawaited(runSmoke());
|
||||
}
|
||||
|
||||
Future<Map<String, Object?>> status() async =>
|
||||
await channel.invokeMapMethod<String, Object?>('status') ?? {};
|
||||
|
||||
Future<Map<String, Object?>> waitFor(
|
||||
bool Function(Map<String, Object?>) predicate,
|
||||
) async {
|
||||
final deadline = DateTime.now().add(const Duration(minutes: 3));
|
||||
while (DateTime.now().isBefore(deadline)) {
|
||||
final value = await status();
|
||||
if (predicate(value)) return value;
|
||||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||
}
|
||||
throw StateError(
|
||||
'Timed out waiting for native update state: ${await status()}',
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> record(String name, Object value) async {
|
||||
await File('$smokeRoot/$name.json')
|
||||
.writeAsString(jsonEncode(value), flush: true);
|
||||
}
|
||||
|
||||
Future<void> runSmoke() async {
|
||||
if (smokeRoot.isEmpty) {
|
||||
throw StateError('Set CUTDEX_UPDATE_SMOKE_ROOT for this test app');
|
||||
}
|
||||
try {
|
||||
await channel.invokeMethod<void>('ready');
|
||||
final initial = await waitFor(
|
||||
(value) => value['configured'] == true && value['canCheck'] == true,
|
||||
);
|
||||
await channel.invokeMethod<void>('check');
|
||||
var checked = await waitFor((value) => value['canCheck'] == true);
|
||||
if (initial['build'] == '900002') {
|
||||
if (checked['phase'] != 'current') {
|
||||
throw StateError('Updated version was offered again: $checked');
|
||||
}
|
||||
await record('after', checked);
|
||||
exit(0);
|
||||
}
|
||||
if (checked['phase'] != 'available' ||
|
||||
checked['availableVersion'] != '1.0.0-build.900002') {
|
||||
throw StateError('Expected version 1.0.0-build.900002: $checked');
|
||||
}
|
||||
await channel.invokeMethod<void>('download');
|
||||
final rejected = await waitFor((value) => value['canCheck'] == true);
|
||||
if (rejected['phase'] == 'ready' || rejected['error'] == '') {
|
||||
throw StateError('Corrupted package was not rejected: $rejected');
|
||||
}
|
||||
await record('corrupt-rejected', rejected);
|
||||
await channel.invokeMethod<void>('download');
|
||||
checked = await waitFor((value) => value['canCheck'] == true);
|
||||
if (checked['phase'] != 'ready' || checked['error'] != '') {
|
||||
throw StateError('Could not download valid update: $checked');
|
||||
}
|
||||
await record('before', checked);
|
||||
await channel.invokeMethod<void>('validateInstall');
|
||||
await channel.invokeMethod<void>('install');
|
||||
} catch (error, stack) {
|
||||
await record('failure', {'error': '$error', 'stack': '$stack'});
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
"""CLI contracts: help/invalid arguments must not start builds or publish files."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class CliTests(unittest.TestCase):
|
||||
def test_python_help_and_unknown_option(self):
|
||||
scripts = [
|
||||
'check.py', 'macos/check_macos_release.py', 'macos/macos_updates.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',
|
||||
'diagnostics/frame_budget.py',
|
||||
]
|
||||
for name in scripts:
|
||||
for flag, code in [('--help', 0), ('--invalid-option', 2)]:
|
||||
with self.subTest(script=name, flag=flag):
|
||||
result = subprocess.run([sys.executable, str(ROOT / 'tool' / name), flag],
|
||||
capture_output=True, text=True, timeout=30)
|
||||
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')]
|
||||
for arguments, code in [(['--help'], 0), ([], 2)]:
|
||||
result = subprocess.run(command + arguments, cwd=ROOT, capture_output=True,
|
||||
text=True, timeout=60)
|
||||
self.assertEqual(result.returncode, code, result.stderr)
|
||||
self.assertIn('Usage:', result.stdout + result.stderr)
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / 'history.json'
|
||||
path.write_text('[]')
|
||||
result = subprocess.run(command + [str(path)], cwd=ROOT, capture_output=True,
|
||||
text=True, timeout=60)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(json.loads(result.stdout)['messages'], 0)
|
||||
|
||||
@unittest.skipUnless(shutil.which('bash'), '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'],
|
||||
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'],
|
||||
capture_output=True, text=True, timeout=10)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
|
||||
|
||||
@unittest.skipUnless(sys.platform == 'darwin' and shutil.which('swiftc'), 'macOS Swift required')
|
||||
class NativeCliTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.temp = tempfile.TemporaryDirectory(prefix='cutdex-cli-')
|
||||
cls.addClassCleanup(cls.temp.cleanup)
|
||||
cls.root = Path(cls.temp.name)
|
||||
for name in ['set_macos_file_icon', 'sparkle_test_key']:
|
||||
subprocess.run(['swiftc', str(ROOT / f'tool/macos/{name}.swift'),
|
||||
'-o', str(cls.root / name)], check=True, capture_output=True, timeout=120)
|
||||
|
||||
def test_help_and_missing_arguments(self):
|
||||
for name in ['set_macos_file_icon', 'sparkle_test_key']:
|
||||
for arguments, code in [(['--help'], 0), ([], 2)]:
|
||||
with self.subTest(script=name, arguments=arguments):
|
||||
result = subprocess.run([str(self.root / name), *arguments], capture_output=True)
|
||||
self.assertEqual(result.returncode, code, result.stderr)
|
||||
|
||||
def test_test_key_reuse_and_invalid_file(self):
|
||||
path = self.root / 'keys with spaces'
|
||||
command = [str(self.root / 'sparkle_test_key'), str(path)]
|
||||
subprocess.run(command, check=True, capture_output=True)
|
||||
original = (path / 'private.key').read_bytes()
|
||||
subprocess.run(command, check=True, capture_output=True)
|
||||
self.assertEqual((path / 'private.key').read_bytes(), original)
|
||||
self.assertEqual((path / 'private.key').stat().st_mode & 0o777, 0o600)
|
||||
(path / 'private.key').write_text('invalid key')
|
||||
result = subprocess.run(command, capture_output=True)
|
||||
self.assertEqual(result.returncode, 1)
|
||||
self.assertNotIn(b'invalid key', result.stderr)
|
||||
|
||||
def test_missing_icon_returns_failure(self):
|
||||
result = subprocess.run([str(self.root / 'set_macos_file_icon'),
|
||||
str(self.root / 'missing.png'), str(self.root / 'missing.dmg')],
|
||||
capture_output=True)
|
||||
self.assertEqual(result.returncode, 1)
|
||||
@@ -0,0 +1,97 @@
|
||||
"""Catch dependencies that Dart's shared workspace resolution can hide."""
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
'boundaries', Path(__file__).resolve().parents[1] / 'check_package_boundaries.py')
|
||||
boundaries = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(boundaries)
|
||||
|
||||
|
||||
class PackageBoundaryTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.root = Path(temp.name)
|
||||
for package in boundaries.RUNTIME:
|
||||
self.write(f'packages/{package}/pubspec.yaml', f'''name: {package}
|
||||
resolution: workspace
|
||||
publish_to: none
|
||||
dependencies:
|
||||
flutter:
|
||||
sdk: flutter
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
sdk: flutter
|
||||
''')
|
||||
|
||||
def write(self, path, content):
|
||||
target = self.root / path
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_text(content)
|
||||
|
||||
def test_reverse_dependency_is_rejected_even_when_unused(self):
|
||||
path = self.root / 'packages/cutdex_native/pubspec.yaml'
|
||||
path.write_text(path.read_text().replace('dependencies:\n',
|
||||
'dependencies:\n cutdex: any\n', 1))
|
||||
self.assertTrue(any('forbidden dependency cutdex' in error
|
||||
for error in boundaries.check(self.root)))
|
||||
|
||||
def test_workspace_resolution_does_not_authorize_transitive_imports(self):
|
||||
self.write('packages/cutdex_ui/lib/component.dart', "import 'package:path/path.dart';")
|
||||
self.assertTrue(any('undeclared import package:path/' in error
|
||||
for error in boundaries.check(self.root)))
|
||||
|
||||
def test_application_requires_public_package_entrypoints(self):
|
||||
self.write('lib/app.dart', "import 'package:cutdex_ui/src/widgets/app_item.dart';")
|
||||
self.write('test/app_test.dart', "import '../packages/cutdex_native/lib/cutdex_native.dart';")
|
||||
errors = boundaries.check(self.root)
|
||||
self.assertEqual(len(errors), 2, errors)
|
||||
|
||||
def test_integration_tests_cannot_import_sdk_implementation(self):
|
||||
self.write('integration_test/save_test.dart',
|
||||
"import 'package:cutdex_project/src/persistence/timeline_codec.dart';")
|
||||
self.assertTrue(any('private import' in error
|
||||
for error in boundaries.check(self.root)))
|
||||
|
||||
def test_package_tests_cannot_escape_the_package(self):
|
||||
self.write('packages/cutdex_ui/test/component_test.dart',
|
||||
"import '../../../lib/app.dart';")
|
||||
self.assertTrue(any('escaping import' in error
|
||||
for error in boundaries.check(self.root)))
|
||||
|
||||
def test_application_cannot_import_sibling_repository_sources(self):
|
||||
self.write('lib/bridge.dart', "export '../../cutdex_sdk/lib/editor.dart';")
|
||||
self.write('integration_test/save_test.dart',
|
||||
"import '../../cutdex_sdk/packages/project/lib/cutdex_project.dart';")
|
||||
self.assertEqual(len(boundaries.check(self.root)), 2)
|
||||
|
||||
def test_application_library_cannot_import_test_or_tool_sources(self):
|
||||
self.write('lib/bridge.dart', "import '../test/support/fake.dart';")
|
||||
self.write('lib/tool.dart', "export '../tool/testing/fixture.dart';")
|
||||
self.assertEqual(len(boundaries.check(self.root)), 2)
|
||||
|
||||
def test_public_imports_and_own_implementation_are_allowed(self):
|
||||
self.write('lib/app.dart', "import 'package:cutdex_ui/widgets.dart';")
|
||||
self.write('packages/cutdex_ui/lib/widgets.dart', "export 'src/widget.dart';")
|
||||
self.write('packages/cutdex_ui/test/widget_test.dart',
|
||||
"import 'package:cutdex_ui/widgets.dart';\nimport 'package:flutter_test/flutter_test.dart';")
|
||||
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';")
|
||||
self.assertEqual(len(boundaries.check(self.root)), 2)
|
||||
|
||||
def test_normalized_package_uris_cannot_hide_private_sources(self):
|
||||
self.write('lib/app.dart', "import 'package:cutdex_ui/public/../src/widgets/app_item.dart';")
|
||||
self.assertTrue(any('private import' in error for error in boundaries.check(self.root)))
|
||||
|
||||
def test_fixture_strings_and_comments_are_not_imports(self):
|
||||
self.write('lib/app.dart', '''// import 'package:cutdex_ui/src/fake.dart';
|
||||
/* export 'package:cutdex_ui/src/fake.dart'; */
|
||||
const fixture = "import 'package:cutdex_ui/src/fake.dart';";
|
||||
''')
|
||||
self.assertEqual(boundaries.check(self.root), [])
|
||||
@@ -0,0 +1,58 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
SPEC = importlib.util.spec_from_file_location(
|
||||
'public_repository', Path(__file__).resolve().parents[1] / 'check_public_repository.py')
|
||||
CHECKER = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(CHECKER)
|
||||
|
||||
|
||||
class PublicRepositoryTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temporary = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temporary.cleanup)
|
||||
self.root = Path(self.temporary.name)
|
||||
|
||||
def write(self, name, text='local value'):
|
||||
path = self.root / name
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(text)
|
||||
|
||||
def test_credential_report_does_not_echo_secret(self):
|
||||
secret = 'gh' + 'p_' + 'a' * 40
|
||||
self.write('config.txt', 'token=' + secret)
|
||||
errors = CHECKER.check_files(self.root, ['config.txt'])
|
||||
self.assertEqual(len(errors), 1)
|
||||
self.assertIn('config.txt:1', errors[0])
|
||||
self.assertNotIn(secret, errors[0])
|
||||
|
||||
def test_local_inputs_are_rejected_but_examples_are_allowed(self):
|
||||
names = ['.env', '.env.production', 'android/key.properties',
|
||||
'.local/config.json', 'nested/build/output.txt',
|
||||
'example.cutdex/project.json', 'signing.p12']
|
||||
for name in names + ['.env.example', '.env.production.sample']:
|
||||
self.write(name)
|
||||
self.assertEqual(len(CHECKER.check_files(self.root, names)), len(names))
|
||||
self.assertEqual(CHECKER.check_files(
|
||||
self.root, ['.env.example', '.env.production.sample']), [])
|
||||
|
||||
def test_links_allow_urls_fragments_and_relative_files(self):
|
||||
self.write('docs/guide.md', '[file](../LICENSE) [section](#intro) '
|
||||
'[web](https://example.com) [missing](missing.md)')
|
||||
self.write('LICENSE')
|
||||
errors = CHECKER.check_files(self.root, ['docs/guide.md'])
|
||||
self.assertEqual(errors, ['docs/guide.md: missing or external local link missing.md'])
|
||||
|
||||
def test_symlinks_cannot_publish_external_files(self):
|
||||
(self.root / 'external').symlink_to(self.root.parent)
|
||||
self.assertEqual(CHECKER.check_files(self.root, ['external']),
|
||||
['external: symlink escapes repository'])
|
||||
|
||||
def test_deleted_worktree_file_is_not_published(self):
|
||||
self.assertEqual(CHECKER.check_files(self.root, ['deleted.txt']), [])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Audit Windows x64 PE imports without trusting the build host's System32.
|
||||
|
||||
Build-host dependency: pefile==2024.8.26. The target computer needs no Python.
|
||||
This is a static dependency gate, not a substitute for a clean Windows VM run.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
# Inbox components on supported, fully updated Windows 10/11 (non-N editions).
|
||||
# Never infer this list from files installed on the developer's machine.
|
||||
SYSTEM_DLLS = set('''
|
||||
advapi32 avicap32 avrt bcrypt bcryptprimitives cfgmgr32 combase comctl32 comdlg32
|
||||
crypt32 d2d1 d3d11 d3d12 d3d9 d3dcompiler_47 dbghelp dnsapi dwmapi dwrite dxgi
|
||||
gdi32 imagehlp imm32 iphlpapi kernel32 mf mfplat mfplay mfreadwrite msimg32
|
||||
ncrypt ntdll ole32 oleacc oleaut32 opengl32 propsys psapi rpcrt4 secur32
|
||||
setupapi shell32 shlwapi uiautomationcore user32 userenv usp10 winmm wintrust
|
||||
ws2_32 ucrtbase version
|
||||
'''.split())
|
||||
SYSTEM_DLLS = {name + '.dll' for name in SYSTEM_DLLS}
|
||||
REQUIRED = (
|
||||
'cutdex.exe', 'flutter_windows.dll', 'cutdex_runtime_plugin.dll',
|
||||
'deskup_plugin.dll', 'velopack_libc.dll',
|
||||
'cutdex_windows_ffi.dll', 'sqlite3.dll', 'data/app.so', 'data/icudtl.dat',
|
||||
'processing/bin/cutdex-processing-worker.exe',
|
||||
'processing/bin/cutdex_processing_ffi.dll', 'processing/bin/ffmpeg.exe',
|
||||
'processing/bin/ffprobe.exe', 'processing/bin/onnxruntime.dll',
|
||||
'processing/bin/DirectML.dll',
|
||||
'processing/workers/asr/cutdex-asr-worker.exe',
|
||||
'processing/workers/audio/cutdex-audio-worker.exe',
|
||||
'processing/workers/translation/cutdex-m2m100-worker.exe',
|
||||
)
|
||||
|
||||
|
||||
def system_dependency(name):
|
||||
name = name.lower()
|
||||
return name in SYSTEM_DLLS or name.startswith(('api-ms-win-', 'ext-ms-win-'))
|
||||
|
||||
|
||||
def pe_imports(path):
|
||||
import pefile
|
||||
with pefile.PE(str(path), fast_load=True) as pe:
|
||||
if pe.FILE_HEADER.Machine != 0x8664:
|
||||
raise ValueError(f'Not an x64 PE: {path}')
|
||||
pe.parse_data_directories(directories=[1, 13])
|
||||
return sorted({item.dll.decode('ascii').lower() for attribute in
|
||||
('DIRECTORY_ENTRY_IMPORT', 'DIRECTORY_ENTRY_DELAY_IMPORT')
|
||||
for item in getattr(pe, attribute, [])})
|
||||
|
||||
|
||||
def audit(root, read_imports=pe_imports):
|
||||
root = Path(root).resolve()
|
||||
missing = [name for name in REQUIRED if not (root / name).is_file()]
|
||||
if missing:
|
||||
raise ValueError(f'Missing release files: {missing}')
|
||||
if not (root / 'data/flutter_assets').is_dir():
|
||||
raise ValueError('Missing Flutter assets')
|
||||
report = {}
|
||||
unresolved = []
|
||||
for binary in sorted(root.rglob('*')):
|
||||
if binary.suffix.lower() not in ('.dll', '.exe'):
|
||||
continue
|
||||
if binary.is_symlink():
|
||||
raise ValueError(f'External/symlink binary: {binary}')
|
||||
# Each worker is a separate process. A DLL in another worker directory
|
||||
# (or only in the main app directory) does not satisfy its dependency.
|
||||
local = {p.name.lower() for p in binary.parent.iterdir() if p.is_file()}
|
||||
names = read_imports(binary)
|
||||
report[binary.relative_to(root).as_posix()] = names
|
||||
for name in names:
|
||||
if name.lower() not in local and not system_dependency(name):
|
||||
unresolved.append(f'{binary.relative_to(root)} -> {name}')
|
||||
if unresolved:
|
||||
raise ValueError('Unbundled dependencies: ' + '; '.join(unresolved))
|
||||
return {'architecture': 'x64', 'imports': report, 'unresolved': [],
|
||||
'cleanSystemValidated': False}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--app', type=Path, required=True)
|
||||
parser.add_argument('--report', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
result = audit(args.app)
|
||||
args.report.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.report.write_text(json.dumps(result, indent=2) + '\n', encoding='utf-8')
|
||||
print(f'Windows dependency gate passed: {len(result["imports"])} PE files')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Stage an audited portable Windows x64 app from a normal Flutter Release build.
|
||||
|
||||
Requires pefile on the build host. Models remain separate from the application.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
|
||||
from check_windows_release import audit
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--app', type=Path, required=True)
|
||||
parser.add_argument('--processing', type=Path, required=True)
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
source, runtime, output = [p.resolve() for p in (args.app, args.processing, args.output)]
|
||||
if output.exists() or output.is_relative_to(source) or output.is_relative_to(runtime):
|
||||
raise ValueError('Output must be a new directory outside the source packages')
|
||||
if not (source / 'cutdex.exe').is_file() or not (runtime / 'checksums.json').is_file():
|
||||
raise ValueError('Provide a complete Release directory and processing package')
|
||||
checksums = json.loads((runtime / 'checksums.json').read_text(encoding='utf-8-sig'))
|
||||
for name, expected in checksums.items():
|
||||
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()
|
||||
if actual.lower() != expected.lower():
|
||||
raise ValueError(f'Processing checksum mismatch: {name}')
|
||||
# Older Flutter builds can retain the unused JNI plugin from Android's
|
||||
# path_provider dependency. Windows has its own provider and needs no JVM.
|
||||
shutil.copytree(source, output, ignore=shutil.ignore_patterns('processing', '*.pdb', '*.lib', '*.exp', 'dartjni.dll'))
|
||||
shutil.copytree(runtime, output / 'processing')
|
||||
result = audit(output)
|
||||
(output / 'dependency-audit.json').write_text(json.dumps(result, indent=2) + '\n', encoding='utf-8')
|
||||
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()
|
||||
(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()
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Create a Windows Sandbox launch file; no developer tools are mapped into it.
|
||||
|
||||
Inputs must contain fixture.mp4 (short SDR H.264 + AAC). Model folders are mapped
|
||||
read-only; the vocals folder must contain melband.pt. Only results are writable.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
for name in ('app', 'smoke', 'inputs', 'whisper', 'translation', 'vocals', 'results', 'output'):
|
||||
parser.add_argument('--' + name, type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
paths = {name: getattr(args, name).resolve() for name in
|
||||
('app', 'smoke', 'inputs', 'whisper', 'translation', 'vocals', 'results')}
|
||||
for name in ('app', 'smoke'):
|
||||
if not (paths[name] / 'checksums.json').is_file():
|
||||
raise ValueError(f'Not an audited package: {paths[name]}')
|
||||
for name in ('inputs', 'whisper', 'translation', 'vocals'):
|
||||
if not paths[name].is_dir():
|
||||
raise ValueError(f'Missing directory: {paths[name]}')
|
||||
if not (paths['inputs'] / 'fixture.mp4').is_file() or not (paths['vocals'] / 'melband.pt').is_file():
|
||||
raise ValueError('Missing fixture.mp4 or vocals/melband.pt')
|
||||
paths['results'].mkdir(parents=True, exist_ok=True)
|
||||
config = ET.Element('Configuration')
|
||||
ET.SubElement(config, 'VGpu').text = 'Enable'
|
||||
ET.SubElement(config, 'MemoryInMB').text = '8192'
|
||||
ET.SubElement(config, 'Networking').text = 'Disable'
|
||||
folders = ET.SubElement(config, 'MappedFolders')
|
||||
# Copy just the standalone guest script; never map the source/build tool tree.
|
||||
script = Path(__file__).with_name('test_windows_release.ps1')
|
||||
(paths['inputs'] / script.name).write_bytes(script.read_bytes())
|
||||
mapping = {'app': r'C:\Cutdex', 'smoke': r'C:\Smoke', 'inputs': r'C:\Inputs',
|
||||
'whisper': r'C:\Models\whisper', 'translation': r'C:\Models\translation',
|
||||
'vocals': r'C:\Models\vocals', 'results': r'C:\Results'}
|
||||
for name, guest in mapping.items():
|
||||
folder = ET.SubElement(folders, 'MappedFolder')
|
||||
ET.SubElement(folder, 'HostFolder').text = str(paths[name])
|
||||
ET.SubElement(folder, 'SandboxFolder').text = guest
|
||||
ET.SubElement(folder, 'ReadOnly').text = 'false' if name == 'results' else 'true'
|
||||
(paths['inputs'] / 'models.json').write_text(json.dumps({
|
||||
'whisper': mapping['whisper'],
|
||||
'translation': mapping['translation'],
|
||||
'vocals': mapping['vocals'] + r'\melband.pt',
|
||||
}, indent=2), encoding='utf-8')
|
||||
command = ET.SubElement(config, 'LogonCommand')
|
||||
ET.SubElement(command, 'Command').text = (
|
||||
'powershell.exe -NoProfile -ExecutionPolicy Bypass -File C:\\Inputs\\test_windows_release.ps1 '
|
||||
'-App C:\\Cutdex -SmokeApp C:\\Smoke -Inputs C:\\Inputs -Results C:\\Results')
|
||||
ET.indent(config)
|
||||
args.output.write_text(ET.tostring(config, encoding='unicode') + '\n', encoding='utf-8')
|
||||
print(f'Log into Windows, then open {args.output}. Results: {paths["results"]}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,46 @@
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from check_windows_release import REQUIRED, audit
|
||||
|
||||
|
||||
class DependencyGateTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name)
|
||||
for name in REQUIRED:
|
||||
path = self.root / name
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.touch()
|
||||
(self.root / 'data/flutter_assets').mkdir()
|
||||
|
||||
def test_vc_runtime_in_another_worker_does_not_satisfy_app(self):
|
||||
(self.root / 'processing/workers/asr/vcruntime140.dll').touch()
|
||||
with self.assertRaisesRegex(ValueError, 'cutdex.exe -> vcruntime140.dll'):
|
||||
audit(self.root, lambda p: ['vcruntime140.dll'] if p.name == 'cutdex.exe' else [])
|
||||
|
||||
def test_unknown_dependency_is_not_assumed_to_be_a_system_dll(self):
|
||||
with self.assertRaisesRegex(ValueError, 'vendor.dll'):
|
||||
audit(self.root, lambda p: ['vendor.dll'])
|
||||
|
||||
def test_local_runtime_and_inbox_api_sets_pass(self):
|
||||
(self.root / 'VCRUNTIME140.dll').touch()
|
||||
result = audit(self.root, lambda p: ['vcruntime140.dll', 'KERNEL32.dll',
|
||||
'VERSION.dll', 'COMCTL32.dll', 'api-ms-win-crt-runtime-l1-1-0.dll'] if p.name == 'cutdex.exe' else [])
|
||||
self.assertEqual(result['unresolved'], [])
|
||||
self.assertFalse(result['cleanSystemValidated'])
|
||||
|
||||
def test_missing_flutter_aot_is_rejected(self):
|
||||
(self.root / 'data/app.so').unlink()
|
||||
with self.assertRaisesRegex(ValueError, 'data/app.so'):
|
||||
audit(self.root, lambda p: [])
|
||||
|
||||
def test_jvm_is_not_assumed_to_be_a_system_dependency(self):
|
||||
with self.assertRaisesRegex(ValueError, 'jvm.dll'):
|
||||
audit(self.root, lambda p: ['jvm.dll'] if p.name == 'cutdex.exe' else [])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,100 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Validates a normal and smoke release package on an interactive Windows desktop.
|
||||
.DESCRIPTION
|
||||
Requires App, SmokeApp, Inputs and Results paths. Writes result.json and process
|
||||
logs to Results. Returns a nonzero status on failure; does not publish packages.
|
||||
.EXAMPLE
|
||||
Get-Help ./tool/windows/test_windows_release.ps1 -Full
|
||||
.EXAMPLE
|
||||
./tool/windows/test_windows_release.ps1 -App C:\Cutdex -SmokeApp C:\Smoke -Inputs C:\Inputs -Results C:\Results
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory=$true)][string]$App,
|
||||
[Parameter(Mandatory=$true)][string]$SmokeApp,
|
||||
[Parameter(Mandatory=$true)][string]$Inputs,
|
||||
[Parameter(Mandatory=$true)][string]$Results
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
New-Item -ItemType Directory -Force $Results | Out-Null
|
||||
$report = @{ passed = $false; sandbox = ($env:USERNAME -eq 'WDAGUtilityAccount'); sessionId = (Get-Process -Id $PID).SessionId }
|
||||
$normal = $null
|
||||
try {
|
||||
if ($report.sessionId -eq 0) { throw 'Interactive Windows desktop required; SSH Session 0 is not a display test.' }
|
||||
foreach ($folder in @($App, $SmokeApp)) {
|
||||
$manifest = Get-Content (Join-Path $folder 'checksums.json') -Raw | ConvertFrom-Json
|
||||
foreach ($entry in $manifest.PSObject.Properties) {
|
||||
if ((Get-FileHash -LiteralPath (Join-Path $folder $entry.Name) -Algorithm SHA256).Hash -ne $entry.Value) {
|
||||
throw "Package checksum mismatch: $($entry.Name)"
|
||||
}
|
||||
}
|
||||
}
|
||||
Get-ChildItem Env:CUTDEX_* | Remove-Item
|
||||
$env:PATH = "$env:SystemRoot\System32;$env:SystemRoot"
|
||||
$env:PATHEXT = '.COM;.EXE;.BAT;.CMD'
|
||||
$normal = Start-Process (Join-Path $App 'cutdex.exe') -WorkingDirectory $App -PassThru -RedirectStandardOutput (Join-Path $Results 'app.stdout.log') -RedirectStandardError (Join-Path $Results 'app.stderr.log')
|
||||
Start-Sleep -Seconds 5
|
||||
$normal.Refresh()
|
||||
if ($normal.HasExited -or $normal.MainWindowHandle -eq 0) { throw 'Normal app did not create a window.' }
|
||||
$loaded = @{}
|
||||
foreach ($module in $normal.Modules) {
|
||||
if ($module.ModuleName -match '^(msvcp140|vcruntime140(_1)?)\.dll$') {
|
||||
$loaded[$module.ModuleName] = $module.FileName
|
||||
if ([IO.Path]::GetFullPath([IO.Path]::GetDirectoryName($module.FileName)) -ne [IO.Path]::GetFullPath($App)) {
|
||||
throw "VC runtime loaded outside app: $($module.FileName)"
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach ($name in @('msvcp140.dll','vcruntime140.dll','vcruntime140_1.dll')) {
|
||||
if (!$loaded.ContainsKey($name)) { throw "VC runtime module missing: $name" }
|
||||
}
|
||||
$report.loadedVcRuntime = $loaded
|
||||
Stop-Process -Id $normal.Id
|
||||
$normal = $null
|
||||
& "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy Bypass -File (Join-Path $App 'processing\verify.ps1') -Report (Join-Path $Results 'processing.json')
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Processing package verification failed.' }
|
||||
$config = Get-Content (Join-Path $Inputs 'models.json') -Raw | ConvertFrom-Json
|
||||
foreach ($configured in @($false, $true)) {
|
||||
Get-ChildItem Env:CUTDEX_* | Remove-Item
|
||||
$name = if ($configured) { 'with-models' } else { 'without-models' }
|
||||
$caseDirectory = Join-Path $Results $name
|
||||
New-Item -ItemType Directory -Force $caseDirectory | Out-Null
|
||||
$env:LOCALAPPDATA = $caseDirectory
|
||||
$env:APPDATA = $caseDirectory
|
||||
$env:USERPROFILE = $caseDirectory
|
||||
$env:CUTDEX_SMOKE_REPORT = Join-Path $caseDirectory 'result.json'
|
||||
$env:CUTDEX_SMOKE_MODELS = [int]$configured
|
||||
$env:CUTDEX_SMOKE_VIDEO = '1'
|
||||
$env:CUTDEX_SMOKE_MEDIA = Join-Path $Inputs 'fixture.mp4'
|
||||
if ($configured) {
|
||||
$processing = Join-Path $caseDirectory 'Documents\Cutdex\Resources\Processing'
|
||||
$whisperTarget = Join-Path $processing 'Transcription\whisper-turbo\1'
|
||||
$translationTarget = Join-Path $processing 'Translation\m2m100-418m\1'
|
||||
New-Item -ItemType Directory -Force $whisperTarget, $translationTarget | Out-Null
|
||||
Copy-Item -Recurse -Force (Join-Path $config.whisper '*') $whisperTarget
|
||||
Copy-Item -Recurse -Force (Join-Path $config.translation '*') $translationTarget
|
||||
New-Item -ItemType Directory -Force (Join-Path $processing 'VocalSeparation\melband\1') | Out-Null
|
||||
Copy-Item -Force $config.vocals (Join-Path $processing 'VocalSeparation\melband\1\melband.pt')
|
||||
}
|
||||
$process = Start-Process (Join-Path $SmokeApp 'cutdex.exe') -WorkingDirectory $SmokeApp -PassThru -RedirectStandardOutput (Join-Path $caseDirectory 'stdout.log') -RedirectStandardError (Join-Path $caseDirectory 'stderr.log')
|
||||
# Retain the process handle before it exits so PowerShell 5.1 can read
|
||||
# ExitCode after WaitForExit instead of returning null.
|
||||
$null = $process.Handle
|
||||
try {
|
||||
if (!$process.WaitForExit(600000)) { throw "Smoke timed out: $name" }
|
||||
if ($process.ExitCode -ne 0) { throw "Smoke failed: $name ($($process.ExitCode))" }
|
||||
$result = Get-Content $env:CUTDEX_SMOKE_REPORT -Raw | ConvertFrom-Json
|
||||
if (!$result.passed -or !$result.videoPreviewAndExport) { throw "Incomplete smoke: $name" }
|
||||
$report[$name] = $result
|
||||
} finally {
|
||||
if (!$process.HasExited) { Stop-Process -Id $process.Id }
|
||||
}
|
||||
}
|
||||
$report.passed = $true
|
||||
} catch {
|
||||
$report.error = $_.ToString()
|
||||
throw
|
||||
} finally {
|
||||
if ($normal -and !$normal.HasExited) { Stop-Process -Id $normal.Id }
|
||||
$report | ConvertTo-Json -Depth 12 | Set-Content -Encoding UTF8 (Join-Path $Results 'result.json')
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
"""Build two disposable Flutter apps and verify updates through a Python HTTP server.
|
||||
|
||||
Uses Cutdex.Dev only. Tests checksum rejection, retry, install, relaunch and no-op
|
||||
checks. Requires Flutter, the pinned vpk tool and Windows. Never uploads releases.
|
||||
"""
|
||||
import argparse
|
||||
from functools import partial
|
||||
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
from windows_updates import DESKUP_VERSION, ROOT, check_tool, pack_release, update_version, vpk_command
|
||||
|
||||
|
||||
class TestHandler(SimpleHTTPRequestHandler):
|
||||
corrupt = True
|
||||
|
||||
def do_GET(self):
|
||||
if self.path.endswith('.nupkg') and type(self).corrupt:
|
||||
type(self).corrupt = False
|
||||
file = Path(self.directory) / self.path.lstrip('/')
|
||||
payload = bytearray(file.read_bytes())
|
||||
payload[len(payload) // 2] ^= 1
|
||||
self.send_response(200)
|
||||
self.send_header('Content-Length', str(len(payload)))
|
||||
self.end_headers()
|
||||
self.wfile.write(payload)
|
||||
else:
|
||||
super().do_GET()
|
||||
|
||||
|
||||
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')
|
||||
args = parser.parse_args()
|
||||
if sys.platform != 'win32':
|
||||
parser.error('This test requires Windows')
|
||||
work = args.work.resolve()
|
||||
if work.exists():
|
||||
parser.error('Use a new work directory so previous reports cannot pass this test')
|
||||
work.mkdir(parents=True)
|
||||
command = vpk_command(args.vpk)
|
||||
check_tool(command)
|
||||
definitions = work / 'defines.json'
|
||||
definitions.write_text(json.dumps({'CUTDEX_UPDATE_SMOKE_ROOT': work.as_posix()}), encoding='utf-8')
|
||||
environment = dict(os.environ, CUTDEX_WINDOWS_UPDATE_URL=f'http://127.0.0.1:{args.port}',
|
||||
CUTDEX_UPDATE_TEST_HTTP='1')
|
||||
# Isolate Flutter caches, generated runner files and output from live builds.
|
||||
source = work / 'source'
|
||||
source.mkdir()
|
||||
for name in ['windows']:
|
||||
shutil.copytree(ROOT / name, source / name,
|
||||
ignore=shutil.ignore_patterns('ephemeral', 'build', '__pycache__'))
|
||||
# Exercise the real Runner/update bridge with a small Flutter test entry.
|
||||
# Media processing is covered separately and need not be rebuilt here.
|
||||
(source / 'pubspec.yaml').write_text(
|
||||
'name: cutdex_update_smoke\nversion: 1.0.0+1\n'
|
||||
'environment:\n sdk: ^3.13.2\n'
|
||||
'dependencies:\n flutter:\n sdk: flutter\n'
|
||||
f' deskup: {DESKUP_VERSION}\n'
|
||||
'flutter:\n uses-material-design: true\n', encoding='utf-8')
|
||||
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 []),
|
||||
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',
|
||||
'--target', 'tool/testing/windows_update_smoke.dart', '--build-name', '1.0.0',
|
||||
'--build-number', str(build), '--dart-define-from-file', str(definitions)],
|
||||
cwd=source, env=environment, check=True)
|
||||
app = source / 'build/windows/x64/development/runner/Release'
|
||||
release = work / ('baseline' if build == 900001 else 'public')
|
||||
pack_release(command, app=app, output=release, package_id='Cutdex.Dev',
|
||||
version=update_version('1.0.0', build), title='Cutdex update test')
|
||||
verify_update(work, args.port)
|
||||
|
||||
|
||||
def verify_update(work, port):
|
||||
reports = ['corrupt-rejected', 'before', 'after', 'failure']
|
||||
if any((work / f'{name}.json').exists() for name in reports):
|
||||
raise ValueError('Previous reports must not pass this test; use a fresh work directory')
|
||||
portable = next((work / 'baseline').glob('*Portable.zip'))
|
||||
if not (work / 'installed').exists():
|
||||
shutil.unpack_archive(portable, work / 'installed')
|
||||
TestHandler.corrupt = True
|
||||
server = ThreadingHTTPServer(('127.0.0.1', port),
|
||||
partial(TestHandler, directory=str(work / 'public')))
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
# Hide the helper process console; the test app itself shows its test window.
|
||||
app = work / 'installed/Cutdex update test.exe'
|
||||
process = None
|
||||
try:
|
||||
process = subprocess.Popen([str(app)], cwd=app.parent, creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
deadline = time.monotonic() + 240
|
||||
while time.monotonic() < deadline:
|
||||
if (work / 'failure.json').exists():
|
||||
raise RuntimeError((work / 'failure.json').read_text())
|
||||
if (work / 'after.json').exists():
|
||||
break
|
||||
time.sleep(0.2)
|
||||
else:
|
||||
raise TimeoutError('Update did not relaunch within 240 seconds')
|
||||
for report in ['corrupt-rejected', 'before', 'after']:
|
||||
print(report + ': ' + (work / f'{report}.json').read_text())
|
||||
process.wait(timeout=20)
|
||||
print(f'Velopack end-to-end update passed: {work}')
|
||||
finally:
|
||||
if process is not None and process.poll() is None:
|
||||
process.terminate()
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,121 @@
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from windows_updates import resolved_deskup, numeric_version, pack_release, update_version, validate_previous, verify_manifest
|
||||
|
||||
|
||||
class UpdatePublicationTests(unittest.TestCase):
|
||||
def test_deskup_is_located_from_resolved_package_config(self):
|
||||
with tempfile.TemporaryDirectory(prefix='deskup package ') as directory:
|
||||
root = Path(directory)
|
||||
config = root / '.dart_tool/package_config.json'
|
||||
config.parent.mkdir()
|
||||
package = root / 'cache/deskup-0.1.0'
|
||||
for uri in ['../cache/deskup-0.1.0/', package.as_uri() + '/']:
|
||||
config.write_text(json.dumps({'packages': [
|
||||
{'name': 'deskup', 'rootUri': uri},
|
||||
]}), encoding='utf-8')
|
||||
with patch('windows_updates.ROOT', root):
|
||||
self.assertEqual(resolved_deskup().resolve(), package.resolve())
|
||||
|
||||
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'):
|
||||
resolved_deskup()
|
||||
|
||||
def test_display_version_conversion_is_shared_and_ordered(self):
|
||||
self.assertEqual(update_version('1.2.3', '42'), '1.2.3-build.42')
|
||||
self.assertEqual(update_version('1.2.3', '0042'), '1.2.3-build.42')
|
||||
for version, build in [('1.2', 1), ('1.2.3', -1), ('1.2.3', 'beta')]:
|
||||
with self.assertRaises(ValueError):
|
||||
update_version(version, build)
|
||||
|
||||
def test_invalid_pack_version_never_starts_vpk(self):
|
||||
with patch('windows_updates.subprocess.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')
|
||||
run.assert_not_called()
|
||||
|
||||
def test_build_number_participates_in_version_order(self):
|
||||
self.assertLess(numeric_version('1.0.0-build.1'), numeric_version('1.0.0-build.2'))
|
||||
self.assertLess(numeric_version('1.0.0-build.9'), numeric_version('1.0.0-build.10'))
|
||||
self.assertLess(numeric_version('1.0.0-build.999'), numeric_version('1.0.1-build.1'))
|
||||
self.assertLess(numeric_version('1.0.0-build.999'), numeric_version('1.0.0'))
|
||||
for version in ['1.0', '1.0.0+2', '1.0.0.2', '1.0.0-build.02', '1.0.0-beta', '../1.0.0']:
|
||||
with self.assertRaises(ValueError):
|
||||
numeric_version(version)
|
||||
|
||||
def test_reused_build_and_mixed_identity_are_rejected(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
(root / 'releases.win-x64.json').write_text(json.dumps({
|
||||
'Assets': [{'PackageId': 'Cutdex', 'Version': '1.0.0-build.2'}]}))
|
||||
for candidate in ['1.0.0-build.1', '1.0.0-build.2']:
|
||||
with self.assertRaises(ValueError):
|
||||
validate_previous(root, 'Cutdex', candidate)
|
||||
with self.assertRaises(ValueError):
|
||||
validate_previous(root, 'Cutdex.Dev', '1.0.0-build.3')
|
||||
validate_previous(root, 'Cutdex', '1.0.0-build.3')
|
||||
|
||||
def test_post_audit_tampering_and_added_files_are_rejected(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
(root / 'cutdex.exe').write_bytes(b'app')
|
||||
(root / 'processing').mkdir()
|
||||
(root / 'processing/checksums.json').write_text('{}')
|
||||
manifest = {name: hashlib.sha256((root / name).read_bytes()).hexdigest()
|
||||
for name in ['cutdex.exe', 'processing/checksums.json']}
|
||||
(root / 'checksums.json').write_text(json.dumps(manifest))
|
||||
verify_manifest(root)
|
||||
(root / 'cutdex.exe').write_bytes(b'changed')
|
||||
with self.assertRaises(ValueError):
|
||||
verify_manifest(root)
|
||||
(root / 'cutdex.exe').write_bytes(b'app')
|
||||
(root / 'injected.dll').write_bytes(b'new')
|
||||
with self.assertRaises(ValueError):
|
||||
verify_manifest(root)
|
||||
|
||||
def test_escaping_manifest_path_is_rejected(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
(root / 'checksums.json').write_text(json.dumps({'../outside.exe': '0' * 64}))
|
||||
with self.assertRaises(ValueError):
|
||||
verify_manifest(root)
|
||||
|
||||
def test_relative_staging_directory_is_normalized(self):
|
||||
with tempfile.TemporaryDirectory(dir=Path.cwd()) as directory:
|
||||
root = Path(directory).relative_to(Path.cwd())
|
||||
(root / 'cutdex.exe').write_bytes(b'app')
|
||||
(root / 'checksums.json').write_text(json.dumps({
|
||||
'cutdex.exe': hashlib.sha256(b'app').hexdigest(),
|
||||
}))
|
||||
verify_manifest(root)
|
||||
|
||||
def test_symlink_inside_staging_directory_is_rejected(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
original = root / 'cutdex.exe'
|
||||
original.write_bytes(b'app')
|
||||
try:
|
||||
(root / 'linked.exe').symlink_to(original)
|
||||
except OSError as error:
|
||||
if getattr(error, 'winerror', None) != 1314:
|
||||
raise
|
||||
self.skipTest(f'Symlinks unavailable: {error}')
|
||||
digest = hashlib.sha256(b'app').hexdigest()
|
||||
(root / 'checksums.json').write_text(json.dumps({
|
||||
'cutdex.exe': digest,
|
||||
'linked.exe': digest,
|
||||
}))
|
||||
with self.assertRaisesRegex(ValueError, 'Invalid manifest path'):
|
||||
verify_manifest(root)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,184 @@
|
||||
"""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
|
||||
|
||||
from check_windows_release import audit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
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')
|
||||
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']))
|
||||
if uri.scheme != 'file' or uri.netloc:
|
||||
raise ValueError('Expected a local resolved deskup package')
|
||||
return Path(url2pathname(uri.path))
|
||||
|
||||
|
||||
DESKUP_ROOT = resolved_deskup()
|
||||
DESKUP_VERSION = re.search(r'^version: ([^\s]+)',
|
||||
(DESKUP_ROOT / 'pubspec.yaml').read_text(encoding='utf-8'),
|
||||
re.MULTILINE).group(1)
|
||||
SDK_VERSION = re.search(r'set\(DESKUP_VELOPACK_VERSION "([^"]+)"\)',
|
||||
(DESKUP_ROOT / 'windows/velopack.cmake').read_text(encoding='utf-8')).group(1)
|
||||
|
||||
|
||||
def vpk_command(path):
|
||||
path = Path(path).resolve()
|
||||
if path.suffix.lower() == '.dll':
|
||||
# Useful with a locally extracted official vpk tool package.
|
||||
return ['dotnet', str(path), '--legacyConsole', '--skip-updates']
|
||||
return [str(path), '--legacyConsole', '--skip-updates']
|
||||
|
||||
|
||||
def check_tool(command):
|
||||
result = subprocess.run(command + ['--help'], 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')
|
||||
|
||||
|
||||
def pack_release(command, *, app, output, package_id, version, title):
|
||||
numeric_version(version)
|
||||
subprocess.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)
|
||||
|
||||
|
||||
def update_version(display_version, build):
|
||||
version = display_version + '-build.' + str(int(build))
|
||||
numeric_version(version)
|
||||
return version
|
||||
|
||||
|
||||
def file_version(app):
|
||||
import pefile
|
||||
with pefile.PE(str(app / 'cutdex.exe')) as pe:
|
||||
for group in pe.FileInfo:
|
||||
for block in group:
|
||||
if block.Key == b'StringFileInfo':
|
||||
for table in block.StringTable:
|
||||
value = table.entries.get(b'ProductVersion', b'').decode('utf-8')
|
||||
match = re.fullmatch(r'(\d+\.\d+\.\d+)\+(\d+)', value)
|
||||
if match:
|
||||
return update_version(match[1], match[2])
|
||||
raise ValueError('Missing Flutter display version and build number in PE resources')
|
||||
|
||||
|
||||
def numeric_version(version):
|
||||
number = r'(0|[1-9]\d*)'
|
||||
match = re.fullmatch(rf'{number}\.{number}\.{number}(?:-build\.{number})?', version)
|
||||
if not match:
|
||||
raise ValueError('Windows update versions must use major.minor.patch-build.number')
|
||||
major, minor, patch, build = match.groups()
|
||||
# SemVer build metadata (+number) does not participate in precedence.
|
||||
# A numeric prerelease component does, and stable versions rank above it.
|
||||
return (int(major), int(minor), int(patch), int(build is None), int(build or 0))
|
||||
|
||||
|
||||
def validate_previous(output, package_id, version):
|
||||
candidate = numeric_version(version)
|
||||
for feed in output.glob('releases.*.json'):
|
||||
for asset in json.loads(feed.read_text(encoding='utf-8-sig')).get('Assets', []):
|
||||
if asset.get('PackageId') != package_id:
|
||||
raise ValueError('Do not mix production and development packages in one release directory')
|
||||
if numeric_version(asset['Version']) >= candidate:
|
||||
raise ValueError('Update version must be greater than every previously published version')
|
||||
|
||||
|
||||
def verify_manifest(app):
|
||||
app = app.resolve()
|
||||
manifest = json.loads((app / 'checksums.json').read_text(encoding='utf-8-sig'))
|
||||
actual_files = {file.relative_to(app).as_posix() for file in app.rglob('*')
|
||||
if file.is_file() and file.name != 'checksums.json'}
|
||||
# The processing subtree has its own checksum manifest, which is included
|
||||
# as a file in the outer app manifest.
|
||||
actual_files.update(file.relative_to(app).as_posix() for file in app.rglob('checksums.json')
|
||||
if file != app / 'checksums.json')
|
||||
if set(manifest) != actual_files:
|
||||
raise ValueError('Release files differ from the audited staging manifest')
|
||||
for name, expected in manifest.items():
|
||||
candidate = app / name
|
||||
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}')
|
||||
|
||||
|
||||
def package(args):
|
||||
app, output = args.app.resolve(), args.output.resolve()
|
||||
if output == app or output.is_relative_to(app) or app.is_relative_to(output):
|
||||
raise ValueError('Release output must be outside the staged app')
|
||||
audit(app)
|
||||
verify_manifest(app)
|
||||
sdk_dll = app / 'velopack_libc.dll'
|
||||
if not sdk_dll.is_file():
|
||||
raise ValueError('Rebuild the app with the Velopack integration before packaging')
|
||||
command = vpk_command(args.vpk)
|
||||
check_tool(command)
|
||||
version = file_version(app)
|
||||
package_id = 'Cutdex.Dev' if args.development else 'Cutdex'
|
||||
# The expected identity is compiled into the runner and must match the package.
|
||||
identity = package_id.encode('ascii') + b'\0'
|
||||
if identity not in (app / 'cutdex.exe').read_bytes():
|
||||
raise ValueError('Package identity does not match the Flutter build flavor')
|
||||
validate_previous(output, package_id, version)
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
pack_release(command, app=app, output=output, package_id=package_id, version=version,
|
||||
title='Cutdex Dev' if args.development else 'Cutdex')
|
||||
print(json.dumps({'version': version, 'packageId': package_id, 'output': str(output)}))
|
||||
|
||||
|
||||
def serve(directory, port):
|
||||
directory = directory.resolve()
|
||||
if not directory.is_dir():
|
||||
raise ValueError('Provide an existing Velopack release directory')
|
||||
with ThreadingHTTPServer(('127.0.0.1', port),
|
||||
partial(SimpleHTTPRequestHandler, directory=str(directory))) as server:
|
||||
print(f'Test update source: http://127.0.0.1:{server.server_port}', flush=True)
|
||||
server.serve_forever()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
commands = parser.add_subparsers(dest='command', required=True)
|
||||
pack = commands.add_parser('pack', help='Package a complete audited release; never uploads')
|
||||
pack.add_argument('--app', type=Path, required=True)
|
||||
pack.add_argument('--output', type=Path, required=True)
|
||||
pack.add_argument('--vpk', type=Path, required=True)
|
||||
pack.add_argument('--development', action='store_true')
|
||||
server = commands.add_parser('serve', help='Serve a test feed on 127.0.0.1 only')
|
||||
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':
|
||||
package(args)
|
||||
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 __name__ == '__main__':
|
||||
main()
|
||||
Reference in new issue
Block a user