Move editor UI into the app and release verified Core dependencies (#14)
Gitea CI / Assemble and validate CI artifacts (push) Successful in 1m47s
Gitea CI / Check code and tests (push) Successful in 7m15s
Gitea CI / Build Android APK (push) Successful in 4m6s
Gitea CI / Build Windows x64 app (push) Successful in 3m34s
Gitea CI / Audit and package Windows x64 (push) Successful in 1m29s
Gitea CI / Gitea CI passed (push) Successful in 1s
Gitea Release / Prepare draft Release (push) Failing after 8s
Gitea Release / Upload Android to draft Release (push) Skipped
Gitea Release / Upload Windows to draft Release (push) Skipped
Gitea Release / Verify and publish Release (push) Skipped

This commit was merged in pull request #14.
This commit is contained in:
lingjhf committed 2026-10-11 19:59:40 +00:00
1 parent abc1868550
commit 06f1c26681
452 files changed
+43806 -2329

No files matched your search

+1 -1
View File
@@ -106,7 +106,7 @@ python tool/windows/package_windows_release.py `
## 应用更新产物
Cutdex 的 macOS 更新构建配置为 `CUTDEX_UPDATE_FEED_URL` / `CUTDEX_UPDATE_PUBLIC_KEY`;在构建前设置正式 HTTPS 更新源。Windows production 使用固定的公开 Gitea 仓库与 deskup 0.2.0;开发更新源、Release 附件与迁移说明见 [Windows 更新与发布](../docs/windows-updates.md)。
Cutdex 的 macOS 更新构建配置为 `CUTDEX_UPDATE_FEED_URL` / `CUTDEX_UPDATE_PUBLIC_KEY`;在构建前设置正式 HTTPS 更新源。Windows production 使用固定的公开 Gitea 仓库与 pubspec.lock 锁定的 deskup SDK;开发更新源、Release 附件与迁移说明见 [Windows 更新与发布](../docs/windows-updates.md)。
生成更新产物的应用入口:
+2 -1
View File
@@ -43,7 +43,8 @@ def check_analyze():
def check_flutter():
package_tests = sorted(str(path.relative_to(ROOT)) for path in (ROOT / 'packages').glob('*/test'))
package_tests = sorted(str(path.relative_to(ROOT)) for pattern in ('*/test', '*/example/test')
for path in (ROOT / 'packages').glob(pattern))
run(tool_command('flutter', ['test', '--reporter', 'expanded', 'test', *package_tests]))
+28 -2
View File
@@ -9,10 +9,14 @@ ROOT = Path(__file__).resolve().parent.parent
RUNTIME = {
'cutdex_native': {'flutter', 'path'},
'cutdex_ui': {'flutter', 'cutdex_native', 'freezed_annotation'},
'cutdex_timeline_ui': {'flutter', 'cutdex_core'},
'cutdex_preview': {'flutter', 'cutdex_core', 'cutdex_native_flutter', 'cutdex_timeline_ui'},
}
DEVELOPMENT = {
'cutdex_native': {'flutter_test', 'flutter_lints'},
'cutdex_ui': {'flutter_test', 'flutter_lints', 'build_runner', 'freezed'},
'cutdex_timeline_ui': {'flutter_test', 'flutter_lints'},
'cutdex_preview': {'flutter_test', 'flutter_lints'},
}
TOKENS = re.compile(
r"//[^\n]*|/\*.*?\*/|"
@@ -51,6 +55,18 @@ def package_uri(uri):
return dependency, posixpath.normpath(unquote(path))
def native_channels(source):
"""Recognize reserved wire names, ignoring comments and ordinary text."""
for token in TOKENS.finditer(source):
if token.lastgroup != 'string':
continue
value = token.group().removeprefix('r')
quote = value[0] * (3 if value[:3] == value[0] * 3 else 1)
value = value[len(quote):-len(quote)]
if value == 'cutdex_runtime' or value.startswith('cutdex_runtime/'):
yield value
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,
@@ -66,6 +82,10 @@ def check(root):
def reject(source, message):
errors.append(f'{source.relative_to(root)}: {message}')
def check_transport(source, content):
for channel in native_channels(content):
reject(source, f'native channel {channel} belongs to cutdex_native_flutter transport')
for package, allowed in RUNTIME.items():
directory = root / 'packages' / package
manifest_path = directory / 'pubspec.yaml'
@@ -84,7 +104,10 @@ def check(root):
if area != 'lib':
declared |= dev_dependencies
for source in (directory / area).rglob('*.dart'):
for kind, uri in directives(source.read_text(encoding='utf-8')):
content = source.read_text(encoding='utf-8')
if area == 'lib':
check_transport(source, content)
for kind, uri in directives(content):
if uri.startswith('package:'):
dependency, path = package_uri(uri)
if dependency not in declared:
@@ -99,7 +122,10 @@ def check(root):
for area in ['lib', 'test', 'integration_test', 'test_driver', 'tool']:
for source in (root / area).rglob('*.dart'):
for kind, uri in directives(source.read_text(encoding='utf-8')):
content = source.read_text(encoding='utf-8')
if area == 'lib':
check_transport(source, content)
for kind, uri in directives(content):
if uri.startswith('package:'):
dependency, path = package_uri(uri)
if dependency != 'cutdex' and (path == 'src' or path.startswith('src/')):
@@ -0,0 +1,88 @@
#!/usr/bin/env python3
"""Compare repeated release-mode PropertyPerformanceTests logs; fail on regressions."""
import argparse
import json
import math
import re
import statistics
from pathlib import Path
LINE = re.compile(
r"PROPERTY_BENCH (\w+) median_us=(\S+) p95_us=(\S+) checksum=(\S+)"
)
def read(paths):
runs = {}
for path in paths:
current = {}
for name, median, p95, checksum in LINE.findall(Path(path).read_text()):
values = tuple(float(value) for value in (median, p95, checksum))
if (name in current or not all(math.isfinite(value) for value in values)
or values[0] < 0 or values[1] < values[0]):
raise ValueError(f"Invalid or duplicate measurement in {path}: {name}")
current[name] = values
if not current or (runs and current.keys() != runs.keys()):
raise ValueError(f"Missing benchmark scenarios in {path}")
for name, values in current.items():
runs.setdefault(name, []).append(values)
return runs
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--before", nargs="+", required=True)
parser.add_argument("--after", nargs="+", required=True)
parser.add_argument("--output", type=Path)
parser.add_argument("--tolerance", type=float, default=0.15,
help="Allowed relative timing noise (default: 0.15)")
args = parser.parse_args()
if not 0 <= args.tolerance < 1:
parser.error("--tolerance must be in [0, 1)")
if len(args.before) < 3 or len(args.after) < 3:
parser.error("At least three independent runs are required on each side")
try:
before, after = read(args.before), read(args.after)
expected = {"render_plain", "render_effects", "sampling_empty", "sampling_normal", "sampling_dense"}
if before.keys() != expected or after.keys() != expected:
raise ValueError("Before/after scenarios do not match")
result = {
"method": "Median of independent run medians and run P95 values; times in microseconds",
"scope": "Scalar sampling and 640x360 native frozen-frame compositor, not display FPS",
"checksumScope": "Scalar outputs and rendered-frame work counters; pixel parity is tested separately",
"relativeNoiseTolerance": args.tolerance,
"beforeLogs": args.before,
"afterLogs": args.after,
"scenarios": {},
}
passed = True
for name in before:
checksums = {row[2] for row in before[name] + after[name]}
scenario = {"checksumMatches": len(checksums) == 1,
"beforeRuns": len(before[name]), "afterRuns": len(after[name])}
passed &= scenario["checksumMatches"]
# Timer noise dominates empty, sub-microsecond sampling measurements.
absolute_noise = 0.1 if name.startswith("sampling_") else 100.0
for index, metric in enumerate(["median", "p95"]):
old = statistics.median(row[index] for row in before[name])
new = statistics.median(row[index] for row in after[name])
limit = old * (1 + args.tolerance) + absolute_noise
scenario[metric] = {"beforeUs": old, "afterUs": new,
"changePercent": (new / old - 1) * 100 if old else None,
"limitUs": limit, "passed": new <= limit}
passed &= new <= limit
result["scenarios"][name] = scenario
result["passed"] = bool(passed)
encoded = json.dumps(result, indent=2) + "\n"
if args.output:
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(encoded)
print(encoded, end="")
return 0 if passed else 1
except (OSError, ValueError) as error:
parser.exit(2, f"Invalid benchmark input: {error}\n")
if __name__ == "__main__":
raise SystemExit(main())
+2 -3
View File
@@ -12,11 +12,10 @@ def packaging_change(path):
return (
path.startswith(('.gitea/', '.github/workflows/', '.github/actions/',
'tool/', 'android/', 'windows/',
'packages/cutdex_native/android/',
'packages/cutdex_native/windows/',
'packages/cutdex_native/',
'lib/integrations/app_update',
'lib/features/settings/update'))
or PurePosixPath(path).name in {'pubspec.yaml', 'pubspec.lock', '.metadata', '.fvmrc'}
or PurePosixPath(path).name in {'pubspec.yaml', 'pubspec.lock', '.metadata', '.fvmrc', 'dependencies.json'}
or (path.startswith('test/') and 'update' in path)
)
+141
View File
@@ -0,0 +1,141 @@
"""Resolve the application's verified, self-contained Core source release."""
import argparse
import hashlib
import io
import json
import os
from pathlib import Path, PurePosixPath
import posixpath
import re
import shutil
import sys
import tempfile
import zipfile
from read_dependencies import ROOT, validate_pins
from release_transport import SERVER, attachment_url, request
def verify_archive(data, pins):
validate_pins(pins)
core, native = pins['core'], pins['nativeFlutter']
artifact = core['artifact']
if not re.fullmatch(r'[a-f0-9]{64}', artifact['sha256']):
raise ValueError('Core archive must pin a complete SHA256 digest.')
if hashlib.sha256(data).hexdigest() != artifact['sha256']:
raise ValueError('Core archive SHA256 does not match the application dependency lock.')
prefix = f"cutdex-core-{core['version']}/"
if artifact['file'] != f"cutdex-core-{core['version']}.zip" or core.get('ref') != 'v' + core['version']:
raise ValueError('Core archive must refer to the exact recorded release version.')
with zipfile.ZipFile(io.BytesIO(data)) as archive:
names = archive.namelist()
if len(names) != len(set(names)):
raise ValueError('Duplicate Core archive paths.')
for item in archive.infolist():
path = PurePosixPath(item.filename)
if not item.filename.startswith(prefix) or '..' in path.parts or ':' in item.filename or '\\' in item.filename:
raise ValueError('Unsafe Core archive path.')
if (item.external_attr >> 16) & 0o170000 == 0o120000:
target = archive.read(item).decode()
resolved = posixpath.normpath(posixpath.join(str(path.parent), target))
if target.startswith('/') or '\\' in target or ':' in target or not resolved.startswith(prefix):
raise ValueError('Core symlink escapes its source directory.')
manifest = json.loads(archive.read(prefix + 'RELEASE.json'))
if manifest['version'] != core['version'] or manifest['source_commit'] != core['revision']:
raise ValueError('Core release manifest differs from the recorded commit/version.')
bundled = manifest['native_flutter']
if bundled['version'] != native['version'] or bundled['source_commit'] != native['revision'] or bundled['path'] != 'native_flutter':
raise ValueError('Bundled native Flutter differs from the recorded release commit/version.')
for package, version in (('', core['version']), ('native_flutter/', native['version'])):
text = archive.read(prefix + package + 'pubspec.yaml').decode()
if re.search(r'^version:\s*(\S+)\s*$', text, re.M)[1] != version:
raise ValueError('Bundled package version differs from release metadata.')
platform_pins = json.loads(archive.read(prefix + 'native_flutter/native-dependencies.json'))
if bundled['platform_dependencies'] != platform_pins:
raise ValueError('Bundled platform pins differ from release metadata.')
core_pin = json.loads(archive.read(prefix + 'native-flutter-dependency.json'))
if (core_pin['revision'] != native['revision'] or core_pin['version'] != native['version']
or core_pin['repository'] != native['repository']):
raise ValueError('Core native Flutter pin differs from the application release pin.')
return prefix, manifest
def extract_archive(data, prefix, destination):
"""Materialize internal aliases as copies, including on Windows without symlink privileges."""
links = []
with zipfile.ZipFile(io.BytesIO(data)) as archive:
for item in archive.infolist():
relative = PurePosixPath(item.filename).relative_to(PurePosixPath(prefix))
path = destination.joinpath(*relative.parts)
if item.is_dir():
path.mkdir(parents=True, exist_ok=True)
elif (item.external_attr >> 16) & 0o170000 == 0o120000:
target = posixpath.normpath(posixpath.join(str(relative.parent), archive.read(item).decode()))
links.append((path, destination.joinpath(*PurePosixPath(target).parts)))
else:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(archive.read(item))
path.chmod((item.external_attr >> 16) & 0o777 or 0o644)
for path, target in links:
if not target.exists():
raise ValueError('Core archive alias target is missing.')
path.parent.mkdir(parents=True, exist_ok=True)
if target.is_dir():
shutil.copytree(target, path)
else:
shutil.copy2(target, path)
def release_archive(pins):
core = pins['core']
release = request(f"{SERVER}/api/v1/repos/{core['repository']}/releases/tags/{core['ref']}")
if release.get('draft') or release.get('prerelease') or release['tag_name'] != core['ref']:
raise ValueError('Core dependency must be a published stable release.')
assets = [asset for asset in release['assets'] if asset['name'] == core['artifact']['file']]
if len(assets) != 1:
raise ValueError('Expected exactly one Core release source archive.')
return request(attachment_url(assets[0]))
def prepare(pins, root=ROOT):
validate_pins(pins)
cache_root = Path(os.environ.get('CUTDEX_CORE_ARCHIVE_CACHE', Path.home() / '.cache/cutdex/core'))
cache_root.mkdir(parents=True, exist_ok=True)
digest = pins['core']['artifact']['sha256']
archive_path = cache_root / (digest + '.zip')
data = archive_path.read_bytes() if archive_path.is_file() else release_archive(pins)
prefix, manifest = verify_archive(data, pins)
if not archive_path.is_file():
with tempfile.NamedTemporaryFile(dir=cache_root, delete=False) as stream:
temporary_archive = Path(stream.name)
stream.write(data)
temporary_archive.replace(archive_path)
dependencies = root / '.dependencies'
dependencies.mkdir(exist_ok=True)
destination = dependencies / 'cutdex_core'
if destination.is_symlink() or (destination / '.git').exists():
raise ValueError('Core source checkout is for development; use the local dependency overrides.')
if destination.exists() and not (destination / 'RELEASE.json').is_file():
raise ValueError('Refusing to replace an unmanaged Core directory.')
with tempfile.TemporaryDirectory(prefix='core-release-', dir=dependencies) as directory:
staged = Path(directory) / 'cutdex_core'
staged.mkdir()
extract_archive(data, prefix, staged)
if destination.exists():
shutil.rmtree(destination)
staged.rename(destination)
print(f"Prepared Core {manifest['version']} with native Flutter {manifest['native_flutter']['version']}; archive SHA256 verified.")
def main():
argparse.ArgumentParser(description=__doc__).parse_args()
os.environ['GITEA_TOKEN'] = os.environ.get('CUTDEX_GITEA_TOKEN', os.environ.get('GITEA_TOKEN', ''))
prepare(json.loads((ROOT / 'dependencies.json').read_text()))
if __name__ == '__main__':
try:
main()
except (ValueError, OSError, KeyError, zipfile.BadZipFile) as error:
print(f'Core dependency preparation failed: {error}', file=sys.stderr)
sys.exit(1)
+77
View File
@@ -0,0 +1,77 @@
"""Expose exact application dependencies to CI or update development commit pins."""
import argparse
import json
import os
from pathlib import Path
import re
import subprocess
ROOT = Path(__file__).resolve().parents[2]
DEPENDENCIES = ('core', 'nativeFlutter')
def validate_pins(pins):
if pins.get('schemaVersion') != 1:
raise ValueError('Unsupported application dependency lock schema.')
for name in DEPENDENCIES:
pin = pins[name]
if not re.fullmatch(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+', pin['repository']):
raise ValueError(f'{name}: invalid repository identity.')
if not re.fullmatch(r'[a-f0-9]{40}', pin['revision']):
raise ValueError(f'{name}: dependency must pin a full commit SHA.')
reference = pin.get('ref', pin['revision'])
if reference != pin['revision'] and reference != 'v' + pin.get('version', ''):
raise ValueError(f'{name}: release ref must match the recorded version.')
if reference != pin['revision'] and not re.fullmatch(r'\d+\.\d+\.\d+', pin['version']):
raise ValueError(f'{name}: invalid release version.')
return pins
def write_outputs(pins, output):
validate_pins(pins)
for name in DEPENDENCIES:
pin = pins[name]
for key in ('repository', 'revision'):
output.write(f'{name}-{key}={pin[key]}\n')
output.write(f"{name}-ref={pin.get('ref', pin['revision'])}\n")
def verify_checkouts(pins):
validate_pins(pins)
for name, directory in (('core', 'cutdex_core'), ('nativeFlutter', 'cutdex_native_flutter')):
revision = subprocess.check_output(['git', 'rev-parse', 'HEAD'],
cwd=ROOT / '.dependencies' / directory, text=True).strip()
if revision != pins[name]['revision']:
raise ValueError(f'{name}: checkout does not match the recorded commit.')
print('Both dependency checkouts match their recorded commits.')
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--core', type=Path, help='Update the core pin from this committed checkout')
parser.add_argument('--native-flutter', type=Path, help='Update the native Flutter pin from this committed checkout')
parser.add_argument('--verify', action='store_true', help='Verify CI dependency checkouts match the recorded commits')
args = parser.parse_args()
path = ROOT / 'dependencies.json'
pins = json.loads(path.read_text())
if args.core or args.native_flutter:
for name, checkout in (('core', args.core), ('nativeFlutter', args.native_flutter)):
if checkout:
sha = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=checkout, text=True).strip()
manifest = 'native-dependencies.json' if name == 'nativeFlutter' else 'native-flutter-dependency.json'
subprocess.check_output(['git', 'show', f'{sha}:{manifest}'], cwd=checkout)
pubspec = subprocess.check_output(['git', 'show', f'{sha}:pubspec.yaml'], cwd=checkout, text=True)
pins[name].update(revision=sha, version=re.search(r'^version:\s*(\S+)\s*$', pubspec, re.M)[1])
pins[name].pop('ref', None)
validate_pins(pins)
path.write_text(json.dumps(pins, indent=2) + '\n')
print('Updated committed application dependency pins.')
elif args.verify:
verify_checkouts(pins)
else:
with Path(os.environ['GITHUB_OUTPUT']).open('a', encoding='utf-8') as output:
write_outputs(pins, output)
if __name__ == '__main__':
main()
+12 -1
View File
@@ -33,13 +33,24 @@ class ScopeTests(unittest.TestCase):
'tool/gitea/ci_scope.py', 'tool/windows/windows_updates.py',
'windows/runner/main.cpp.in', 'android/app/build.gradle.kts',
'pubspec.yaml', 'pubspec.lock', '.fvmrc', 'packages/cutdex_ui/pubspec.yaml',
'packages/cutdex_native/windows/CMakeLists.txt',
'packages/cutdex_native/windows/CMakeLists.txt', 'dependencies.json',
'lib/integrations/app_update_bridge.dart',
'lib/features/settings/update_controller.dart', 'test/app_updates_test.dart'):
with self.subTest(path=path):
self.assertEqual(select_scope('pull_request', ['README.md', path]),
{'build-app': True, 'package-app': True})
def test_windows_source_setup_preserves_explicit_compiler_configuration(self):
workflow = (Path(__file__).resolve().parents[2] / '.gitea/workflows/ci.yml').read_text()
branch = workflow.split(' windows-build:', 1)[1].split(' windows:', 1)[0]
cleanup = branch.index('Clear inherited native build overrides')
setup = branch.index('/.gitea/actions/setup-windows')
build = branch.index('Build production Windows app')
self.assertLess(cleanup, setup)
self.assertLess(setup, build)
self.assertIn('"$key=" >> $env:GITHUB_ENV', branch[cleanup:setup])
self.assertNotIn('Remove-Item', branch[setup:])
def test_arbitrary_runtime_markdown_is_not_treated_as_documentation(self):
self.assertTrue(select_scope('pull_request', ['assets/help.md'])['build-app'])
+44
View File
@@ -0,0 +1,44 @@
import copy
import io
import unittest
from unittest.mock import patch
from read_dependencies import validate_pins, verify_checkouts, write_outputs
class DependencyPinsTests(unittest.TestCase):
def setUp(self):
self.pins = {'schemaVersion': 1,
'core': {'repository': 'lingjhf/cutdex_core', 'revision': 'a' * 40},
'nativeFlutter': {'repository': 'cutdex-native/cutdex_native_flutter',
'revision': 'b' * 40, 'version': '0.0.1', 'ref': 'v0.0.1'}}
def test_development_commit_and_release_tag_outputs(self):
output = io.StringIO()
write_outputs(self.pins, output)
self.assertIn('core-ref=' + 'a' * 40 + '\n', output.getvalue())
self.assertIn('nativeFlutter-ref=v0.0.1\n', output.getvalue())
self.assertIn('nativeFlutter-revision=' + 'b' * 40 + '\n', output.getvalue())
def test_unpinned_branch_mismatched_version_and_invalid_identity_are_rejected(self):
for field, value in (('ref', 'main'), ('ref', 'v0.0.2'), ('version', '0.0.1\ninjected=true'),
('revision', 'short'), ('repository', 'owner/repo\ninjected=true')):
pins = copy.deepcopy(self.pins)
pins['nativeFlutter'][field] = value
with self.subTest(field=field, value=value), self.assertRaises(ValueError):
validate_pins(pins)
def test_mutated_release_tag_cannot_change_dependency_commit(self):
with patch('read_dependencies.subprocess.check_output', side_effect=['a' * 40, 'c' * 40]):
with self.assertRaisesRegex(ValueError, 'nativeFlutter: checkout'):
verify_checkouts(self.pins)
def test_both_dependency_commits_are_checked_in_their_own_checkouts(self):
with patch('read_dependencies.subprocess.check_output', side_effect=['a' * 40, 'b' * 40]) as git:
verify_checkouts(self.pins)
self.assertEqual([call.kwargs['cwd'].name for call in git.call_args_list],
['cutdex_core', 'cutdex_native_flutter'])
if __name__ == '__main__':
unittest.main()
+112
View File
@@ -0,0 +1,112 @@
import copy
import hashlib
import io
import json
from pathlib import Path
import tempfile
from unittest.mock import patch
import unittest
import zipfile
from prepare_dependencies import extract_archive, prepare, release_archive, verify_archive
class CoreSourceDependencyTests(unittest.TestCase):
def test_local_gitea_response_links_use_verified_public_origin(self):
_, pins = self.bundle()
asset = {'name': pins['core']['artifact']['file'],
'browser_download_url': 'http://git.orangraph.com/lingjhf/cutdex_core/releases/download/v0.0.1/cutdex-core-0.0.1.zip'}
release = {'tag_name': 'v0.0.1', 'draft': False, 'prerelease': False, 'assets': [asset]}
with patch('prepare_dependencies.request', side_effect=[release, b'archive']) as send:
self.assertEqual(release_archive(pins), b'archive')
self.assertEqual(send.call_args.args[0], asset['browser_download_url'].replace('http:', 'https:'))
asset['browser_download_url'] = 'https://untrusted.example/archive.zip'
with patch('prepare_dependencies.request', return_value=release), self.assertRaises(ValueError):
release_archive(pins)
def bundle(self, extra=None):
prefix = 'cutdex-core-0.0.1/'
native = {'version': '0.0.1', 'source_commit': 'b' * 40, 'path': 'native_flutter',
'platform_dependencies': {'schemaVersion': 1, 'platforms': {}}}
files = {'RELEASE.json': json.dumps({'version': '0.0.1', 'source_commit': 'a' * 40,
'native_flutter': native}),
'pubspec.yaml': 'name: cutdex_core\nversion: 0.0.1\n',
'native_flutter/pubspec.yaml': 'name: cutdex_native_flutter\nversion: 0.0.1\n',
'native_flutter/native-dependencies.json': json.dumps(native['platform_dependencies']),
'native-flutter-dependency.json': json.dumps({'repository': 'cutdex-native/cutdex_native_flutter',
'revision': 'b' * 40, 'version': '0.0.1'}),
'native_flutter/darwin/runtime/source.swift': 'source'}
data = io.BytesIO()
with zipfile.ZipFile(data, 'w') as archive:
for name, body in files.items():
archive.writestr(prefix + name, body)
link = zipfile.ZipInfo(prefix + 'native_flutter/darwin/cutdex_native_flutter')
link.external_attr = 0o120777 << 16
archive.writestr(link, 'runtime')
if extra:
archive.writestr(extra[0], extra[1])
body = data.getvalue()
pins = {'schemaVersion': 1,
'core': {'repository': 'lingjhf/cutdex_core', 'version': '0.0.1', 'ref': 'v0.0.1',
'revision': 'a' * 40, 'artifact': {'file': 'cutdex-core-0.0.1.zip',
'sha256': hashlib.sha256(body).hexdigest()}},
'nativeFlutter': {'repository': 'cutdex-native/cutdex_native_flutter',
'revision': 'b' * 40, 'version': '0.0.1', 'ref': 'v0.0.1'}}
return body, pins
def test_exact_release_bundle_materializes_apple_alias_without_symlink_privileges(self):
data, pins = self.bundle()
prefix, manifest = verify_archive(data, pins)
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
extract_archive(data, prefix, root)
self.assertEqual((root / 'native_flutter/darwin/cutdex_native_flutter/source.swift').read_text(), 'source')
self.assertFalse((root / 'native_flutter/darwin/cutdex_native_flutter').is_symlink())
self.assertEqual(manifest['native_flutter']['source_commit'], pins['nativeFlutter']['revision'])
def test_digest_core_commit_and_native_commit_mismatches_fail_before_extraction(self):
data, pins = self.bundle()
for package, field in [('core', 'revision'), ('nativeFlutter', 'revision'), ('nativeFlutter', 'repository')]:
altered = copy.deepcopy(pins)
altered[package][field] = 'old/native_flutter' if field == 'repository' else 'c' * 40
with self.subTest(package=package), self.assertRaises(ValueError):
verify_archive(data, altered)
with self.assertRaisesRegex(ValueError, 'SHA256'):
verify_archive(data + b'changed', pins)
def test_cached_archive_is_verified_and_extracted_fresh_for_retry(self):
data, pins = self.bundle()
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
cache = root / 'cache'
cache.mkdir()
(cache / (pins['core']['artifact']['sha256'] + '.zip')).write_bytes(data)
with patch.dict('os.environ', {'CUTDEX_CORE_ARCHIVE_CACHE': str(cache)}), patch('prepare_dependencies.release_archive') as fetch:
prepare(pins, root)
source = root / '.dependencies/cutdex_core/native_flutter/darwin/runtime/source.swift'
source.write_text('local stale content')
prepare(pins, root)
self.assertEqual(source.read_text(), 'source')
fetch.assert_not_called()
def test_development_checkout_is_never_removed_by_release_preparation(self):
data, pins = self.bundle()
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
development = root / '.dependencies/cutdex_core'
development.mkdir(parents=True)
(development / '.git').mkdir()
with patch('prepare_dependencies.release_archive', return_value=data), patch.dict('os.environ', {'CUTDEX_CORE_ARCHIVE_CACHE': str(root / 'cache')}):
with self.assertRaisesRegex(ValueError, 'development'):
prepare(pins, root)
self.assertTrue((development / '.git').is_dir())
def test_archive_escape_and_duplicate_paths_are_rejected(self):
for name in ['cutdex-core-0.0.1/../outside', 'cutdex-core-0.0.1/pubspec.yaml']:
data, pins = self.bundle((name, 'unexpected'))
with self.subTest(name=name), self.assertRaises(ValueError):
verify_archive(data, pins)
if __name__ == '__main__':
unittest.main()
+6 -6
View File
@@ -21,12 +21,12 @@ import 'package:cutdex/workspace/timeline_provider.dart';
import 'package:cutdex/workspace/view_settings.dart';
import 'package:cutdex/workspace/workspace_mode.dart';
import 'package:cutdex/workspace/workspace_navigation.dart';
import 'package:cutdex_sdk/editor.dart';
import 'package:cutdex_sdk/preview.dart';
import 'package:cutdex_sdk/project.dart';
import 'package:cutdex_sdk/timeline/layout.dart';
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:cutdex_sdk/timeline_ui.dart';
import 'package:cutdex_core/editor.dart';
import 'package:cutdex_preview/cutdex_preview.dart';
import 'package:cutdex_core/project.dart';
import 'package:cutdex_core/timeline/layout.dart';
import 'package:cutdex_core/timeline/model.dart';
import 'package:cutdex_timeline_ui/cutdex_timeline_ui.dart';
import 'package:drift/native.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
+4 -4
View File
@@ -6,10 +6,10 @@ 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:cutdex_core/editor.dart';
import 'package:cutdex_preview/cutdex_preview.dart';
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
import 'package:cutdex_core/timeline/model.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter/rendering.dart';
+1 -1
View File
@@ -21,7 +21,7 @@ class CommonToolsTests(unittest.TestCase):
result = run([sys.executable, '-c', code, *arguments], cwd=directory,
env={'CUTDEX_TEST': 'child'}, capture_output=True, text=True)
lines = result.stdout.splitlines()
self.assertEqual(Path(lines[0]), Path(directory))
self.assertEqual(Path(lines[0]).resolve(), Path(directory).resolve())
self.assertEqual(lines[1], 'child')
self.assertEqual(lines[2], repr(arguments))
+7 -6
View File
@@ -76,7 +76,7 @@ sys.exit(7 if 'fail' in sys.argv else 0)
def test_cli_injects_environment_before_build_and_preserves_machine_io(self):
(self.root / '.env.local').write_text(
'CUTDEX_ENV_FILE_TEST="C:/My SDK/native"\nCUTDEX_ENV_PARENT_TEST=file\n'
'CUTDEX_ANDROID_PATH="C:/My SDK/cutdex_android"\n',
'CUTDEX_ANDROID_PATH="C:/My SDK/cutdex-android"\n',
encoding='utf-8')
result = self.run_cli('run', '--machine', '--profile', '--dart-define=VALUE=with space')
self.assertEqual(result.returncode, 0, result.stderr)
@@ -84,9 +84,9 @@ sys.exit(7 if 'fail' in sys.argv else 0)
self.assertEqual(data['args'], ['run', '--machine', '--profile', '--dart-define=VALUE=with space'])
self.assertEqual(data['file'], 'C:/My SDK/native')
self.assertEqual(data['parent'], 'parent')
self.assertEqual(data['android'], 'C:/My SDK/cutdex_android')
self.assertEqual(data['android'], 'C:/My SDK/cutdex-android')
self.assertEqual(data['input'], 'daemon-request')
self.assertEqual(Path(data['cwd']), self.root)
self.assertEqual(Path(data['cwd']).resolve(), self.root.resolve())
self.assertEqual(result.stderr.strip(), 'flutter-diagnostic')
def test_ide_shim_uses_the_same_loader_and_preserves_arguments(self):
@@ -168,7 +168,7 @@ sys.exit(7 if 'fail' in sys.argv else 0)
text=True, encoding='utf-8', timeout=40)
self.assertEqual(result.returncode, 0, result.stderr)
data = json.loads(result.stdout)
self.assertEqual(Path(data['cwd']), source)
self.assertEqual(Path(data['cwd']).resolve(), source.resolve())
self.assertEqual(data['file'], 'main-project')
self.assertEqual(data['args'], ['build', 'windows'])
@@ -228,7 +228,8 @@ sys.exit(7 if 'fail' in sys.argv else 0)
capture_output=True, text=True, encoding='utf-8', timeout=40)
self.assertEqual(result.returncode, 0, result.stderr)
data = json.loads(result.stdout)
self.assertEqual(Path(data['cwd']), self.root if cwd is None else cwd)
expected_cwd = self.root if cwd is None else cwd
self.assertEqual(Path(data['cwd']).resolve(), expected_cwd.resolve())
self.assertEqual(data['file'], 'selected-project')
self.assertEqual(data['input'], 'request')
self.assertEqual(data['args'], ['build', 'macos', '--release', '--flavor', 'production',
@@ -262,7 +263,7 @@ sys.exit(7 if 'fail' in sys.argv else 0)
result = subprocess.run([sys.executable, str(self.root / 'tool/project_tools.py'), 'dart', str(probe)],
cwd=package, env=self.environment, capture_output=True, text=True, timeout=40)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(Path(result.stdout.strip()), package)
self.assertEqual(Path(result.stdout.strip()).resolve(), package.resolve())
if __name__ == '__main__':
+22 -2
View File
@@ -63,9 +63,9 @@ dev_dependencies:
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('lib/bridge.dart', "export '../../cutdex_core/lib/editor.dart';")
self.write('integration_test/save_test.dart',
"import '../../cutdex_sdk/packages/project/lib/cutdex_project.dart';")
"import '../../cutdex_core/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):
@@ -101,3 +101,23 @@ dev_dependencies:
const fixture = "import 'package:cutdex_ui/src/fake.dart';";
''')
self.assertEqual(boundaries.check(self.root), [])
def test_application_and_ui_cannot_own_native_media_channels(self):
for path in ('lib/diagnostics.dart', 'packages/cutdex_preview/lib/bridge.dart'):
with self.subTest(path=path):
self.write(path, "const native = MethodChannel('cutdex_runtime');")
self.assertTrue(any('belongs to cutdex_native_flutter transport' in error
for error in boundaries.check(self.root)))
def test_native_event_and_indirect_channel_names_are_rejected(self):
for channel in ('cutdex_runtime', 'cutdex_runtime/sessions/$id'):
with self.subTest(channel=channel):
self.write('lib/bridge.dart', f"const name = '{channel}';")
self.assertEqual(len(boundaries.check(self.root)), 1)
def test_wire_mocks_and_application_channels_remain_host_owned(self):
self.write('test/preview_test.dart', "const native = MethodChannel('cutdex_runtime');")
self.write('lib/window.dart', "const window = MethodChannel('cutdex_native/window');")
self.write('lib/note.dart', "// MethodChannel('cutdex_runtime');\n"
"const message = 'Missing cutdex_runtime plugin';")
self.assertEqual(boundaries.check(self.root), [])
+1 -1
View File
@@ -19,7 +19,7 @@ ws2_32 ucrtbase version
'''.split())
SYSTEM_DLLS = {name + '.dll' for name in SYSTEM_DLLS}
REQUIRED = (
'cutdex.exe', 'flutter_windows.dll', 'cutdex_runtime_plugin.dll',
'cutdex.exe', 'flutter_windows.dll', 'cutdex_native_flutter_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',
+6 -6
View File
@@ -11,12 +11,12 @@ import 'package:cutdex/features/properties/properties_panel.dart';
import 'package:cutdex/features/timeline/timeline_panel.dart';
import 'package:cutdex/l10n/app_localizations.dart';
import 'package:cutdex/workspace/timeline_provider.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:cutdex_sdk/timeline/layout.dart';
import 'package:cutdex_sdk/timeline_ui.dart';
import 'package:cutdex_core/editor.dart';
import 'package:cutdex_preview/cutdex_preview.dart';
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
import 'package:cutdex_core/timeline/model.dart';
import 'package:cutdex_core/timeline/layout.dart';
import 'package:cutdex_timeline_ui/cutdex_timeline_ui.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
@@ -37,6 +37,12 @@ class DependencyGateTest(unittest.TestCase):
with self.assertRaisesRegex(ValueError, 'data/app.so'):
audit(self.root, lambda p: [])
def test_native_flutter_plugin_is_required_after_migration(self):
(self.root / 'cutdex_native_flutter_plugin.dll').unlink()
(self.root / 'cutdex_runtime_plugin.dll').touch()
with self.assertRaisesRegex(ValueError, 'cutdex_native_flutter_plugin.dll'):
audit(self.root, lambda p: [], require_processing=False)
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 [])
+1 -1
View File
@@ -198,7 +198,7 @@ class NativeCacheTests(unittest.TestCase):
with patch.object(cache, 'download_archive', side_effect=self.download):
archive = cache.prepare(environment=environment)
self.assertEqual(output.read_text(), f'EXISTING=value\nDESKUP_VELOPACK_ARCHIVE={archive.as_posix()}\n')
self.assertEqual(archive.parent, self.root / 'Cutdex/ci-tools/native')
self.assertEqual(archive.parent.resolve(), (self.root / 'Cutdex/ci-tools/native').resolve())
def test_failed_verification_cannot_export_an_archive(self):
output = self.root / 'github-env'