diff --git a/app/lib/features/settings/settings_updates_section.dart b/app/lib/features/settings/settings_updates_section.dart index 08cd8008..aba2b3c4 100644 --- a/app/lib/features/settings/settings_updates_section.dart +++ b/app/lib/features/settings/settings_updates_section.dart @@ -136,7 +136,8 @@ class _SettingsUpdatesSectionState extends State { if (_available != null) button( const Key('settings-install-update'), - _available!.platform == 'linux' + _available!.platform == 'linux' || + _available!.platform == 'macos' ? 'Install and restart' : 'Download update', _busy ? null : _install, diff --git a/app/lib/features/updates/app_updates_io.dart b/app/lib/features/updates/app_updates_io.dart index 0a2f8c97..3ab26b5e 100644 --- a/app/lib/features/updates/app_updates_io.dart +++ b/app/lib/features/updates/app_updates_io.dart @@ -11,6 +11,7 @@ import 'package:path_provider/path_provider.dart'; import '../../core/session/server_session.dart'; import 'app_updates.dart'; import 'linux_self_update.dart'; +import 'macos_self_update.dart'; import 'update_feed_signature.dart'; bool get supported => @@ -206,6 +207,24 @@ Future downloadAndInstall( } await LinuxSelfUpdate.relaunch(executable); } + if (Platform.isMacOS) { + // macOS installs in place too: download, verify, swap the bundle, relaunch. + final installer = MacSelfUpdate.current(); + final problem = await installer.problem(); + if (problem != null) throw FileSystemException(problem); + final file = await downloadUpdate( + update, + await getTemporaryDirectory(), + onProgress: onProgress, + ); + final String app; + try { + app = await installer.install(file, versionCode: update.versionCode); + } finally { + if (await file.exists()) await file.delete(); + } + await MacSelfUpdate.relaunch(app); + } final dir = Platform.isAndroid ? await getTemporaryDirectory() : (await getDownloadsDirectory() ?? await getTemporaryDirectory()); diff --git a/app/lib/features/updates/launch_update_dialog.dart b/app/lib/features/updates/launch_update_dialog.dart index 34acbf64..fbf5bbcd 100644 --- a/app/lib/features/updates/launch_update_dialog.dart +++ b/app/lib/features/updates/launch_update_dialog.dart @@ -20,8 +20,7 @@ Future showLaunchUpdateDialog( : nativePlatform == 'linux' ? 'Linux' : 'Android'} build is available${sourceName.isEmpty ? '' : ' from $sourceName'}.${switch (nativePlatform) { - 'linux' => ' Pipelines installs it and restarts.', - 'macos' => ' Download and extract the archive to update the app.', + 'linux' || 'macos' => ' Pipelines installs it and restarts.', _ => '', }}', ), @@ -35,7 +34,7 @@ Future showLaunchUpdateDialog( child: Text( web ? 'Refresh' - : nativePlatform == 'linux' + : nativePlatform == 'linux' || nativePlatform == 'macos' ? 'Install and restart' : 'Download', ), diff --git a/app/lib/features/updates/macos_self_update.dart b/app/lib/features/updates/macos_self_update.dart new file mode 100644 index 00000000..7b9a5cd4 --- /dev/null +++ b/app/lib/features/updates/macos_self_update.dart @@ -0,0 +1,124 @@ +import 'dart:io'; + +/// Installs a downloaded macOS release archive over the running app. +/// +/// The archive holds one `Pipelines.app` bundle. It is unpacked with `ditto` +/// (which keeps the bundle's code signature and extended attributes) beside +/// the installed bundle, checked, and swapped in with two renames; the +/// previous bundle is kept as `.app.previous` until the next update so a +/// failed swap rolls back. A running app may be renamed, so the old process +/// keeps working until [relaunch] opens the new bundle once it has quit. +class MacSelfUpdate { + MacSelfUpdate({ + required this.bundle, + Future Function(String, List)? run, + }) : _run = run ?? ((exe, args) => Process.run(exe, args)); + + /// The installed `.app` bundle. + final Directory bundle; + final Future Function(String, List) _run; + + /// The bundle this process runs from: `/Contents/MacOS/`. + static MacSelfUpdate current() => MacSelfUpdate( + bundle: File(Platform.resolvedExecutable).parent.parent.parent, + ); + + String get _name => + bundle.uri.pathSegments.where((segment) => segment.isNotEmpty).last; + + /// Why this install cannot update itself, or null when it can. + Future problem() async { + if (!_name.endsWith('.app')) { + return 'Pipelines is not running from an app bundle, so it cannot ' + 'update itself. Install it from the downloaded archive instead.'; + } + final parent = bundle.parent; + try { + final probe = File( + '${parent.path}/.pipelines-update-probe-${DateTime.now().microsecondsSinceEpoch}', + ); + await probe.writeAsString(''); + await probe.delete(); + } on FileSystemException { + return 'Pipelines is installed in ${parent.path}, which this user ' + 'cannot change. Move Pipelines.app to Applications or your home ' + 'folder to update it from the app.'; + } + return null; + } + + /// Unpacks [archive] and swaps it in; returns the new bundle's path. + Future install(File archive, {required int versionCode}) async { + final reason = await problem(); + if (reason != null) throw FileSystemException(reason, bundle.path); + final parent = bundle.parent.path; + final staging = Directory('$parent/.$_name-update-$versionCode'); + if (await staging.exists()) await staging.delete(recursive: true); + await staging.create(); + try { + final result = await _run('/usr/bin/ditto', [ + '-x', + '-k', + archive.path, + staging.path, + ]); + if (result.exitCode != 0) { + throw FileSystemException( + 'The update archive could not be extracted: ${'${result.stderr}'.trim()}', + archive.path, + ); + } + final fresh = await _bundleIn(staging); + // Downloads made by this app carry no quarantine flag, but an archive + // fetched another way might; clear it so the new app opens cleanly. + await _run('/usr/bin/xattr', ['-dr', 'com.apple.quarantine', fresh.path]); + final previous = Directory('$parent/$_name.previous'); + if (await previous.exists()) await previous.delete(recursive: true); + await bundle.rename(previous.path); + try { + await fresh.rename(bundle.path); + } catch (_) { + await previous.rename(bundle.path); + rethrow; + } + return bundle.path; + } finally { + if (await staging.exists()) await staging.delete(recursive: true); + } + } + + /// The unpacked `.app` bundle: the one with an executable and Info.plist. + Future _bundleIn(Directory staging) async { + await for (final entry in staging.list()) { + if (entry is! Directory || !entry.path.endsWith('.app')) continue; + final contents = '${entry.path}/Contents'; + final macos = Directory('$contents/MacOS'); + if (await File('$contents/Info.plist').exists() && + await macos.exists() && + await macos.list().any((file) => file is File)) { + return entry; + } + } + throw FileSystemException( + 'The update archive has no complete app bundle.', + staging.path, + ); + } + + /// Opens [app] once this process has exited, then ends this process. + /// + /// `open` would bring the still-running old instance forward, so a small + /// detached shell waits for this process to quit before opening the bundle. + static Future relaunch(String app) async { + final script = + 'while /bin/kill -0 $pid 2>/dev/null; do /bin/sleep 0.2; done; ' + '/usr/bin/open "\$1"'; + await Process.start('/bin/sh', [ + '-c', + script, + 'pipelines-relaunch', + app, + ], mode: ProcessStartMode.detached); + exit(0); + } +} diff --git a/app/test/features/updates/macos_self_update_test.dart b/app/test/features/updates/macos_self_update_test.dart new file mode 100644 index 00000000..573f02a1 --- /dev/null +++ b/app/test/features/updates/macos_self_update_test.dart @@ -0,0 +1,115 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/updates/macos_self_update.dart'; + +/// Builds a release-shaped archive holding one Pipelines.app bundle. +Future _archive( + Directory root, + String marker, { + bool complete = true, +}) async { + final src = Directory('${root.path}/src-$marker'); + final contents = Directory('${src.path}/Pipelines.app/Contents'); + await Directory('${contents.path}/MacOS').create(recursive: true); + if (complete) { + await File('${contents.path}/Info.plist').writeAsString(''); + } + await File('${contents.path}/MacOS/Pipelines').writeAsString(marker); + final out = File('${root.path}/$marker.zip'); + final result = await Process.run('/usr/bin/ditto', [ + '-c', + '-k', + '--keepParent', + '${src.path}/Pipelines.app', + out.path, + ]); + expect(result.exitCode, 0, reason: '${result.stderr}'); + return out; +} + +void main() { + late Directory root; + late Directory bundle; + + setUp(() async { + root = await Directory.systemTemp.createTemp('macos-self-update'); + bundle = Directory('${root.path}/Applications/Pipelines.app'); + await Directory('${bundle.path}/Contents/MacOS').create(recursive: true); + await File('${bundle.path}/Contents/Info.plist').writeAsString(''); + await File('${bundle.path}/Contents/MacOS/Pipelines').writeAsString('old'); + }); + tearDown(() => root.delete(recursive: true)); + + String installed() => + File('${bundle.path}/Contents/MacOS/Pipelines').readAsStringSync(); + + test('swaps in the new bundle and keeps the previous one', () async { + final updater = MacSelfUpdate(bundle: bundle); + expect(await updater.problem(), isNull); + final app = await updater.install( + await _archive(root, 'new'), + versionCode: 2, + ); + expect(app, bundle.path); + expect(installed(), 'new'); + final previous = File( + '${root.path}/Applications/Pipelines.app.previous/Contents/MacOS/Pipelines', + ); + expect(previous.readAsStringSync(), 'old'); + // No staging folder is left behind. + expect( + Directory('${root.path}/Applications').listSync().map((e) => e.path), + unorderedEquals([bundle.path, '${bundle.path}.previous']), + ); + }); + + test('a second update replaces the kept previous bundle', () async { + final updater = MacSelfUpdate(bundle: bundle); + await updater.install(await _archive(root, 'two'), versionCode: 2); + await updater.install(await _archive(root, 'three'), versionCode: 3); + expect(installed(), 'three'); + expect( + File( + '${bundle.path}.previous/Contents/MacOS/Pipelines', + ).readAsStringSync(), + 'two', + ); + }); + + test('an incomplete archive leaves the installed app untouched', () async { + final updater = MacSelfUpdate(bundle: bundle); + await expectLater( + updater.install( + await _archive(root, 'broken', complete: false), + versionCode: 2, + ), + throwsA(isA()), + ); + expect(installed(), 'old'); + expect(Directory('${bundle.path}.previous').existsSync(), isFalse); + }); + + test('a failed extraction reports why and changes nothing', () async { + final updater = MacSelfUpdate( + bundle: bundle, + run: (exe, args) async => ProcessResult(0, 1, '', 'bad archive'), + ); + await expectLater( + updater.install(File('${root.path}/missing.zip'), versionCode: 2), + throwsA( + isA().having( + (e) => e.message, + 'message', + contains('bad archive'), + ), + ), + ); + expect(installed(), 'old'); + }); + + test('outside an app bundle there is nothing to update', () async { + final updater = MacSelfUpdate(bundle: Directory('${root.path}/plain')); + expect(await updater.problem(), contains('not running from an app')); + }); +} diff --git a/app/test/features/updates/native_update_dialog_test.dart b/app/test/features/updates/native_update_dialog_test.dart index 8ef3d898..58e1c3cb 100644 --- a/app/test/features/updates/native_update_dialog_test.dart +++ b/app/test/features/updates/native_update_dialog_test.dart @@ -8,7 +8,7 @@ import 'package:pipelines_app/features/updates/launch_update_dialog.dart'; void main() { for (final (platform, sentence, action) in [ ('linux', 'installs it and restarts', 'Install and restart'), - ('macos', 'extract the archive', 'Download'), + ('macos', 'installs it and restarts', 'Install and restart'), ]) { testWidgets('$platform prompt identifies source and its action', ( tester,