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); } }