1 Commits
Author SHA1 Message Date
ImBenjiandClaude Opus 5.5 d3b232f0ee feat(garage_updates): an auto updater for garage apps
Asks Garage for the newest release of a project, downloads it with resume,
checks the sha256, installs it beside the old one and restarts into it.
Splash on garage_ui, a native stub and a first time installer for windows,
bundle swap on mac, the system installer on android. No-op on web.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KHotisA4hV2xmuZsHTksFX
2026-10-12 06:37:02 +01:00
56 changed files with 9031 additions and 0 deletions
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 IMBENJI.NET LTD
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+6
View File
@@ -0,0 +1,6 @@
include: package:flutter_lints/flutter.yaml
linter:
rules:
# the SDK prints caught errors to console on purpose for debugging
avoid_print: false
+9
View File
@@ -0,0 +1,9 @@
*.iml
.gradle
/local.properties
/.idea/workspace.xml
/.idea/libraries
.DS_Store
/build
/captures
.cxx
+58
View File
@@ -0,0 +1,58 @@
group = "net.imbenji.garage_updates"
version = "1.0-SNAPSHOT"
buildscript {
val kotlinVersion = "2.3.20"
repositories {
google()
mavenCentral()
}
dependencies {
classpath("com.android.tools.build:gradle:9.0.1")
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion")
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
plugins {
id("com.android.library")
}
android {
namespace = "net.imbenji.garage_updates"
compileSdk = 36
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
sourceSets {
getByName("main") {
java.srcDirs("src/main/kotlin")
}
}
defaultConfig {
minSdk = 24
}
}
kotlin {
compilerOptions {
jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17
}
}
dependencies {
// FileProvider, the only way to hand the installer a file since android 7
implementation("androidx.core:core:1.13.1")
}
@@ -0,0 +1 @@
rootProject.name = "garage_updates"
@@ -0,0 +1,19 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- without this the system installer refuses an apk that came from us -->
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<application>
<!-- our own subclass + authority, so it cant collide with a file
provider the app (or another plugin) allready declares -->
<provider
android:name="net.imbenji.garage_updates.GarageUpdatesFileProvider"
android:authorities="${applicationId}.garage_updates.files"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/garage_updates_paths" />
</provider>
</application>
</manifest>
@@ -0,0 +1,6 @@
package net.imbenji.garage_updates
import androidx.core.content.FileProvider
// nothing in it. it exists so the manifest entry has a class name of its own
class GarageUpdatesFileProvider : FileProvider()
@@ -0,0 +1,106 @@
package net.imbenji.garage_updates
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
import androidx.core.content.FileProvider
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import java.io.File
// The android half of garage_updates. Two things dart cant do for itself:
// find out who installed the app, and hand an apk to the system installer.
// The installer always asks the person, theres no silent path and we dont
// want one.
class GarageUpdatesPlugin : FlutterPlugin, MethodCallHandler {
private lateinit var channel: MethodChannel
private lateinit var context: Context
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
context = binding.applicationContext
channel = MethodChannel(binding.binaryMessenger, "net.imbenji.garage_updates")
channel.setMethodCallHandler(this)
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
}
override fun onMethodCall(call: MethodCall, result: Result) {
when (call.method) {
"info" -> result.success(
mapOf(
"installer" to installerPackageName(),
"cacheDir" to context.cacheDir.absolutePath,
)
)
"installerPackageName" -> result.success(installerPackageName())
"install" -> {
val path = call.argument<String>("path")
if (path == null) {
result.error("bad_args", "install needs a path", null)
return
}
install(File(path), result)
}
else -> result.notImplemented()
}
}
// "com.android.vending" for a play store install, null for a sideload
private fun installerPackageName(): String? {
val pm = context.packageManager
return try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
pm.getInstallSourceInfo(context.packageName).installingPackageName
} else {
@Suppress("DEPRECATION")
pm.getInstallerPackageName(context.packageName)
}
} catch (e: Exception) {
Log.e(TAG, "couldnt read the installer package name", e)
null
}
}
private fun install(apk: File, result: Result) {
if (!apk.exists()) {
result.error("missing", "No apk at ${apk.path}", null)
return
}
try {
val uri = FileProvider.getUriForFile(
context,
"${context.packageName}.garage_updates.files",
apk,
)
val intent = Intent(Intent.ACTION_VIEW).apply {
setDataAndType(uri, "application/vnd.android.package-archive")
// the installer is another app, it needs lending the file
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
// we only have the application context, not an activity
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
context.startActivity(intent)
result.success(null)
} catch (e: Exception) {
// an apk outside the shared cache folder lands here too
Log.e(TAG, "couldnt open the installer for ${apk.path}", e)
result.error("install_failed", e.message ?: "The installer could not be opened", null)
}
}
companion object {
private const val TAG = "garage_updates"
}
}
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- only the staging folder in the cache is ever shared, and only with the installer -->
<paths>
<cache-path name="garage_updates" path="garage_updates/" />
</paths>
+117
View File
@@ -0,0 +1,117 @@
import "package:flutter/widgets.dart";
import "package:garage_ui/garage_ui.dart";
import "package:garage_updates/garage_updates.dart";
import "package:go_router/go_router.dart";
// The whole integration is the one call at the top of main. Everything under
// it is just an app with a "restart to update" button, which is the only
// other thing an app has to do for itself.
//
// Run it with `flutter run` and the updater prints that this copy isnt an
// install and stays out of the way - it only ever touches a release build
// that the installer (or a previous update) put in place.
Future<void> main(List<String> args) async {
// an app with helpers of its own (an agent, a tray) stops them here
GarageUpdater.instance.onBeforeRestart = () async {
print("about to restart into the new build");
};
await GarageUpdater.launch(
args: args,
project: "proj_example",
build: 12, // the number after the + in pubspec's version
label: "v2610-1",
branding: const UpdaterBranding(
name: "Example App",
logo: Icon(LucideIcons.package),
),
mode: UpdateMode.prompt,
);
runApp(const ExampleApp());
}
final _theme = ThemeData(
colorScheme: GarageSchemes.carbon,
density: const Density.product(),
);
final _router = GoRouter(
routes: [
GoRoute(path: "/", builder: (context, state) => const HomePage()),
],
);
class ExampleApp extends StatelessWidget {
const ExampleApp({super.key});
@override
Widget build(BuildContext context) {
return GarageApp.router(routerConfig: _router, theme: _theme, title: "Example App");
}
}
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
String? _error;
Future<void> _restart() async {
try {
await GarageUpdater.instance.restartToUpdate();
} on UpdateError catch (e) {
// a UAC prompt turned down, say. the update is still waiting
print("couldnt restart into the update: $e");
if (mounted) setState(() => _error = e.message);
}
}
@override
Widget build(BuildContext context) {
final updater = GarageUpdater.instance;
return Scaffold(
child: Center(
child: ValueListenableBuilder<UpdateInfo?>(
valueListenable: updater.ready,
builder: (context, waiting, _) {
final latest = waiting?.latest;
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Text("Example App ${updater.label}").large().semiBold(),
const Gap.sm(),
if (latest == null)
const Text("Up to date").muted()
else ...[
Text("${latest.label} is ready to install").muted(),
const Gap.sm(),
// the notes are the apps to show, the splash never does
if (latest.notes.isNotEmpty) Text(latest.notes).muted(),
const Gap.lg(),
Button(
style: const ButtonStyle.primary(),
onPressed: _restart,
child: const Text("Restart to update"),
),
],
if (_error != null) ...[
const Gap.md(),
Text(_error!).muted(),
],
],
);
},
),
),
);
}
}
+24
View File
@@ -0,0 +1,24 @@
name: garage_updates_example
description: "Minimal example of an app that updates itself with garage_updates."
publish_to: 'none'
version: 0.1.0+12
environment:
sdk: ^3.10.0
flutter: ">=3.5.0"
dependencies:
flutter:
sdk: flutter
garage_ui:
path: ../../garage_ui
garage_updates:
path: ../
go_router: ^14.6.2
dev_dependencies:
flutter_lints: ^6.0.0
flutter:
+20
View File
@@ -0,0 +1,20 @@
// The updater without flutter: ask Garage for the newest release, download it
// with resume, check the sha256, install it and restart.
//
// A headless dart program (an agent, a cli) imports this one. A flutter app
// wants package:garage_updates/garage_updates.dart instead, which is this
// plus the splash.
//
// final engine = UpdateEngine.detect(project: "<project id>", build: 12);
// final info = await engine.check();
// if (info.hasUpdate) {
// await engine.download(info.latest!);
// await engine.install(info.latest!);
// await engine.restart(args: args);
// }
//
// android isnt in here, installing an apk needs a platform channel.
library;
export "src/core/models.dart";
export "src/core/io.dart" if (dart.library.js_interop) "src/core/web.dart";
+25
View File
@@ -0,0 +1,25 @@
// Auto updates for a flutter app, akin to Discord's. One call at the top of
// main and the rest happens on its own:
//
// Future<void> main(List<String> args) async {
// await GarageUpdater.launch(
// args: args,
// project: "<project id>",
// build: 12,
// label: "v2610-1",
// branding: UpdaterBranding(name: "Garage Stash", logo: "assets/logo.png"),
// );
// runApp(const MyApp());
// }
//
// While the app runs, GarageUpdater.instance.ready says when a newer build has
// been downloaded, and restartToUpdate() moves over to it.
//
// On the web every call is a no-op.
library;
export "src/core/models.dart"
show UpdateInfo, UpdateRelease, UpdateAsset, UpdateStatus, UpdateError, UpdateDriver, DownloadProgress;
export "src/branding.dart" show UpdaterBranding, UpdateMode;
export "src/splash.dart" show UpdateSplash, UpdateSplashApp, SplashController, SplashStage;
export "src/updater.dart" show GarageUpdater;
+39
View File
@@ -0,0 +1,39 @@
import "package:flutter/widgets.dart";
import "package:garage_ui/garage_ui.dart";
/// What happens to an update the app could carry on without.
enum UpdateMode {
/// found at launch = downloaded and installed there and then, behind the
/// splash. The app starts allready up to date
silent,
/// never installed from the splash. Its fetched in the background and
/// `GarageUpdater.instance.ready` tells the app, which asks the person
prompt,
}
/// Whose splash it is.
class UpdaterBranding {
const UpdaterBranding({required this.name, this.logo, this.theme})
: assert(
logo == null || logo is Widget || logo is String || logo is ImageProvider,
"logo is an asset path, an ImageProvider or a Widget",
);
/// the developers name for the app, shown under the logo
final String name;
/// an asset path ("assets/logo.png"), an [ImageProvider], or any widget
final Object? logo;
/// the splash wears carbon at the product tier unless told otherwise
final ThemeData? theme;
Widget? buildLogo() {
final l = logo;
if (l is Widget) return l;
if (l is String) return Image.asset(l);
if (l is ImageProvider) return Image(image: l);
return null;
}
}
+138
View File
@@ -0,0 +1,138 @@
import "dart:async";
import "dart:convert";
import "dart:ffi" show Abi;
import "dart:io";
import "models.dart";
const kDefaultApiBase = "https://pay.imbenji.net/api";
/// Asks Garage what the newest release is. No sign in, one GET.
class UpdateClient {
UpdateClient({
required this.project,
String apiBase = kDefaultApiBase,
HttpClient? httpClient,
this.timeout = const Duration(seconds: 20),
}) : apiBase = apiBase.endsWith("/") ? apiBase.substring(0, apiBase.length - 1) : apiBase,
_http = httpClient ?? HttpClient();
final String project;
final String apiBase;
final Duration timeout;
final HttpClient _http;
Uri checkUri({required String platform, required String arch, required int build}) {
return Uri.parse("$apiBase/v1/updates/${Uri.encodeComponent(project)}").replace(
queryParameters: {"platform": platform, "arch": arch, "build": "$build"},
);
}
/// `GET /v1/updates/:pid`. Throws [UpdateError] when the server cant be
/// reached or says no, a 200 with an odd body comes back as unknown.
Future<UpdateInfo> check({
required String platform,
required String arch,
required int build,
}) async {
final uri = checkUri(platform: platform, arch: arch, build: build);
final HttpClientResponse res;
final String body;
try {
final req = await _http.getUrl(uri).timeout(timeout);
req.headers.set(HttpHeaders.acceptHeader, "application/json");
res = await req.close().timeout(timeout);
body = await res.transform(utf8.decoder).join().timeout(timeout);
} on TimeoutException catch (e) {
print("[garage_updates] the update check timed out: $e");
throw UpdateError("timeout", "The update check timed out");
} catch (e, st) {
print("[garage_updates] the update check didnt get through: $e\n$st");
throw UpdateError("network", "Couldn't reach the update server");
}
if (res.statusCode != 200) {
// the store api's errors are {"error": code, "message": ...}
var code = "http_${res.statusCode}";
var message = "The update server answered ${res.statusCode}";
try {
final j = jsonDecode(body);
if (j is Map) {
if (j["error"] is String) code = j["error"] as String;
if (j["message"] is String) message = j["message"] as String;
}
} catch (e) {
print("[garage_updates] update check ${res.statusCode} with a body that isnt json: $e");
}
throw UpdateError(code, message);
}
Object? json;
try {
json = jsonDecode(body);
} catch (e) {
print("[garage_updates] the update check answered something that isnt json: $e");
return const UpdateInfo(status: UpdateStatus.unknown);
}
final info = UpdateInfo.fromJson(json);
final latest = info.latest;
if (latest == null) return info;
// hosted assets come back absolute, but dont fall over on a relative one
final resolved = _resolve(latest.asset.url);
if (resolved == latest.asset.url) return info;
return UpdateInfo(
status: info.status,
minimumBuild: info.minimumBuild,
latest: UpdateRelease(
label: latest.label,
build: latest.build,
notes: latest.notes,
publishedAt: latest.publishedAt,
asset: UpdateAsset(
url: resolved,
filename: latest.asset.filename,
format: latest.asset.format,
size: latest.asset.size,
sha256: latest.asset.sha256,
),
),
);
}
String _resolve(String url) {
final u = Uri.tryParse(url);
if (u == null || u.hasScheme) return url;
return Uri.parse("$apiBase/").resolve(url.startsWith("/") ? url.substring(1) : url).toString();
}
void close() => _http.close(force: true);
}
/// "windows" | "macos" | "android", or null where theres nothing to update
String? currentUpdatePlatform() {
if (Platform.isWindows) return "windows";
if (Platform.isMacOS) return "macos";
if (Platform.isAndroid) return "android";
return null;
}
/// The arch to ask for. The server falls back to `universal` by itself, so
/// this only has to be honest about the machine.
String currentUpdateArch() {
final abi = Abi.current();
if (abi == Abi.windowsX64 || abi == Abi.macosX64 || abi == Abi.androidX64 || abi == Abi.linuxX64) {
return "x64";
}
if (abi == Abi.windowsArm64 ||
abi == Abi.macosArm64 ||
abi == Abi.androidArm64 ||
abi == Abi.linuxArm64) {
return "arm64";
}
// 32 bit android and the like. only a universal asset can suit it
return "universal";
}
+276
View File
@@ -0,0 +1,276 @@
import "dart:async";
import "dart:convert";
import "dart:io";
import "package:crypto/crypto.dart";
import "models.dart";
// Fetches one release asset into the staging folder.
//
// The bytes land in `update.part`, with a little json beside it saying which
// build + sha they belong to. A cut connection leaves both where they are and
// the next go asks for `Range: bytes=N-`. Only once the whole file hashes to
// what Garage recorded does it get its real name.
const _partName = "update.part";
const _metaName = "update.part.json";
class Downloader {
Downloader({
HttpClient? httpClient,
this.quietTimeout = const Duration(seconds: 30),
this.retries = 3,
this.retryPause = const Duration(seconds: 2),
}) : _http = httpClient ?? HttpClient();
final HttpClient _http;
/// how long the line may say nothing before we call it dead
final Duration quietTimeout;
/// extra goes after the first, each one resuming
final int retries;
final Duration retryPause;
static File partFile(Directory staging) => File(_join(staging.path, _partName));
static File metaFile(Directory staging) => File(_join(staging.path, _metaName));
/// where a finished, verified download of [release] sits
static File finishedFile(Directory staging, UpdateRelease release) {
final ext = release.asset.format.isEmpty ? "bin" : release.asset.format;
return File(_join(staging.path, "update-${release.build}.$ext"));
}
Future<File> fetch({
required UpdateRelease release,
required Directory staging,
DownloadProgress? onProgress,
}) async {
final asset = release.asset;
if (asset.sha256.isEmpty) {
// never install something we cant check
throw UpdateError("no_checksum", "The release has no checksum to verify against");
}
await staging.create(recursive: true);
final done = finishedFile(staging, release);
final part = partFile(staging);
final meta = metaFile(staging);
if (await done.exists()) {
if (await sha256Of(done) == asset.sha256) {
onProgress?.call(await done.length(), await done.length());
return done;
}
print("[garage_updates] ${done.path} doesnt match its checksum any more, fetching it again");
await _remove(done);
}
await _sweep(staging, keep: done);
if (!await _partIsOurs(meta, release)) {
if (await part.exists()) {
print("[garage_updates] throwing away a stale part file, it was for another build");
}
await _remove(part);
await _writeMeta(meta, release);
}
var attempt = 0;
while (true) {
try {
await _pull(asset, part, onProgress);
break;
} on UpdateError catch (e) {
if (!_worthRetrying(e) || attempt >= retries) rethrow;
print("[garage_updates] download stopped (${e.message}), going again");
} catch (e, st) {
// a cut connection, a quiet line. the part file stays for the resume
print("[garage_updates] download stopped: $e\n$st");
if (attempt >= retries) {
throw UpdateError("download", "The download kept failing: $e");
}
}
attempt++;
await Future<void>.delayed(retryPause);
}
final got = await sha256Of(part);
if (got != asset.sha256) {
print("[garage_updates] checksum mismatch, wanted ${asset.sha256} got $got");
await _remove(part);
await _remove(meta);
throw UpdateError("checksum_mismatch", "The download didn't match its checksum");
}
await part.rename(done.path);
await _remove(meta);
return done;
}
bool _worthRetrying(UpdateError e) => e.code == "restart" || e.code == "server";
Future<void> _pull(UpdateAsset asset, File part, DownloadProgress? onProgress) async {
var have = await part.exists() ? await part.length() : 0;
if (asset.size > 0 && have > asset.size) {
print("[garage_updates] the part file is bigger than the release, starting over");
await _remove(part);
have = 0;
}
// all there allready, only the checksum left to do
if (asset.size > 0 && have == asset.size) {
onProgress?.call(have, asset.size);
return;
}
final res = await _open(Uri.parse(asset.url), have);
var append = false;
if (res.statusCode == HttpStatus.partialContent) {
final start = _rangeStart(res.headers.value(HttpHeaders.contentRangeHeader));
if (start == have) {
append = true;
} else if (start == 0) {
have = 0;
} else {
await _drain(res);
await _remove(part);
throw UpdateError("restart", "The server resumed from the wrong place");
}
} else if (res.statusCode == HttpStatus.ok) {
// it ignored the range and sent the lot. fine, start the file again
if (have > 0) print("[garage_updates] the server ignored the range, downloading from the top");
have = 0;
} else if (res.statusCode == HttpStatus.requestedRangeNotSatisfiable) {
await _drain(res);
await _remove(part);
throw UpdateError("restart", "The server wouldn't resume the download");
} else {
await _drain(res);
if (res.statusCode >= 500) {
throw UpdateError("server", "The download server answered ${res.statusCode}");
}
throw UpdateError("http_${res.statusCode}", "The download was refused (${res.statusCode})");
}
int? total;
if (res.contentLength >= 0) {
total = have + res.contentLength;
} else if (asset.size > 0) {
total = asset.size;
}
final out = await part.open(mode: append ? FileMode.writeOnlyAppend : FileMode.writeOnly);
var received = have;
try {
onProgress?.call(received, total);
await for (final chunk in res.timeout(quietTimeout)) {
await out.writeFrom(chunk);
received += chunk.length;
onProgress?.call(received, total);
}
} finally {
await out.close();
}
if (total != null && received < total) {
throw HttpException("the download ended early, $received of $total bytes");
}
}
// Walks the redirects by hand. A hosted download is a 302 to a presigned url
// that only lives a few minutes, so a resume has to start from the original
// link every time - which is why nothing here remembers where it ended up.
Future<HttpClientResponse> _open(Uri uri, int have) async {
for (var hop = 0; hop < 6; hop++) {
final req = await _http.getUrl(uri).timeout(quietTimeout);
req.followRedirects = false;
// dart asks for gzip by itself and unpacks it, which makes a nonsense
// of byte ranges
req.headers.removeAll(HttpHeaders.acceptEncodingHeader);
if (have > 0) req.headers.set(HttpHeaders.rangeHeader, "bytes=$have-");
final res = await req.close().timeout(quietTimeout);
final location = res.headers.value(HttpHeaders.locationHeader);
if (res.isRedirect || (_redirects.contains(res.statusCode) && location != null)) {
await _drain(res);
if (location == null) {
throw UpdateError("redirect", "The download redirected to nowhere");
}
uri = uri.resolve(location);
continue;
}
return res;
}
throw UpdateError("redirect", "The download redirected too many times");
}
static const _redirects = {301, 302, 303, 307, 308};
int? _rangeStart(String? contentRange) {
// "bytes 100-999/1000"
if (contentRange == null) return null;
final m = RegExp(r"bytes\s+(\d+)-").firstMatch(contentRange);
return m == null ? null : int.tryParse(m.group(1)!);
}
Future<void> _drain(HttpClientResponse res) async {
try {
await res.drain<void>().timeout(quietTimeout);
} catch (e) {
print("[garage_updates] couldnt drain a response we didnt want: $e");
}
}
Future<bool> _partIsOurs(File meta, UpdateRelease release) async {
if (!await meta.exists()) return false;
try {
final j = jsonDecode(await meta.readAsString());
return j is Map && j["build"] == release.build && j["sha256"] == release.asset.sha256;
} catch (e) {
print("[garage_updates] unreadable part note, treating the part as stale: $e");
return false;
}
}
Future<void> _writeMeta(File meta, UpdateRelease release) async {
await meta.writeAsString(
jsonEncode({"build": release.build, "sha256": release.asset.sha256}),
flush: true,
);
}
// finished downloads of other builds, nobody is going to install those now
Future<void> _sweep(Directory staging, {required File keep}) async {
try {
await for (final e in staging.list()) {
if (e is! File || e.path == keep.path) continue;
final name = e.uri.pathSegments.last;
if (name.startsWith("update-")) await _remove(e);
}
} catch (e) {
print("[garage_updates] couldnt tidy the staging folder: $e");
}
}
void close() => _http.close(force: true);
}
/// sha256 of a file as lower case hex, read as a stream so a big download
/// never sits in memory
Future<String> sha256Of(File f) async {
final digest = await sha256.bind(f.openRead()).first;
return digest.toString();
}
Future<void> _remove(File f) async {
try {
if (await f.exists()) await f.delete();
} catch (e) {
print("[garage_updates] couldnt delete ${f.path}: $e");
}
}
String _join(String a, String b) => a.endsWith(Platform.pathSeparator) ? "$a$b" : "$a${Platform.pathSeparator}$b";
+184
View File
@@ -0,0 +1,184 @@
import "dart:async";
import "dart:io";
import "client.dart";
import "downloader.dart";
import "installer.dart";
import "models.dart";
/// The whole updater with no flutter in it: check, download, install,
/// restart. The splash drives one of these, and so can a headless program.
///
/// final engine = UpdateEngine.detect(project: "...", build: 12);
/// final info = await engine.check();
/// if (info.hasUpdate) {
/// await engine.download(info.latest!);
/// await engine.install(info.latest!);
/// await engine.restart(args: args);
/// }
class UpdateEngine implements UpdateDriver {
UpdateEngine({
required this.project,
required this.build,
String apiBase = kDefaultApiBase,
Installer? installer,
String? notInstalledReason,
UpdateClient? client,
Downloader? downloader,
String? arch,
void Function(int code)? exitProcess,
}) : _installer = installer,
notInstalledReason = installer != null ? null : (notInstalledReason ?? "no installer"),
client = client ?? UpdateClient(project: project, apiBase: apiBase),
downloader = downloader ?? Downloader(),
arch = arch ?? currentUpdateArch(),
_exit = exitProcess ?? exit;
/// Looks at where this process is running from and builds the engine for
/// it. Somewhere the updater didnt put it = an engine that does nothing.
factory UpdateEngine.detect({
required String project,
required int build,
String apiBase = kDefaultApiBase,
}) {
final found = detectInstall();
return UpdateEngine(
project: project,
build: build,
apiBase: apiBase,
installer: found.installer,
notInstalledReason: found.reason,
);
}
final String project;
/// the build this process is
final int build;
final String arch;
final UpdateClient client;
final Downloader downloader;
final Installer? _installer;
final void Function(int code) _exit;
@override
final String? notInstalledReason;
@override
FutureOr<void> Function()? onBeforeRestart;
@override
bool get installed => _installer != null;
Installer? get installer => _installer;
bool _saidNotInstalled = false;
final Set<int> _saidBlocked = {};
/// Says once why this copy wont be updated. Returns [installed].
bool reportIfNotInstalled() {
if (installed) return true;
if (!_saidNotInstalled) {
_saidNotInstalled = true;
print("[garage_updates] not updating this copy: $notInstalledReason");
}
return false;
}
@override
Future<bool> noteStart() async {
final inst = _installer;
if (inst == null) return false;
return inst.noteStart(build);
}
@override
Future<UpdateInfo> check() async {
final inst = _installer;
if (inst == null) {
reportIfNotInstalled();
return const UpdateInfo(status: UpdateStatus.unknown);
}
final info = await client.check(platform: inst.platform, arch: arch, build: build);
final latest = info.latest;
if (latest == null) return info;
if (latest.build <= build) {
// the server only offers newer ones, but never go backwards on its say so
return UpdateInfo(status: UpdateStatus.current, minimumBuild: info.minimumBuild);
}
if (inst.blockedBuilds().contains(latest.build)) {
if (_saidBlocked.add(latest.build)) {
print("[garage_updates] build ${latest.build} failed to start on this machine before, not taking it again");
}
// still required if it was, theres just nothing here that can be installed
return UpdateInfo(
status: info.isRequired ? UpdateStatus.required : UpdateStatus.current,
minimumBuild: info.minimumBuild,
);
}
return info;
}
@override
Future<void> download(UpdateRelease release, {DownloadProgress? onProgress}) async {
final inst = _need();
await downloader.fetch(release: release, staging: inst.staging, onProgress: onProgress);
}
/// true when [release] is allready downloaded and verified
Future<bool> isDownloaded(UpdateRelease release) async {
final inst = _installer;
if (inst == null) return false;
return Downloader.finishedFile(inst.staging, release).exists();
}
@override
Future<void> install(UpdateRelease release) async {
final inst = _need();
final file = Downloader.finishedFile(inst.staging, release);
if (!await file.exists()) {
throw UpdateError("not_downloaded", "Build ${release.build} hasn't been downloaded");
}
await inst.apply(file, release, runningBuild: build);
}
@override
Future<void> restart({List<String> args = const []}) async {
final inst = _need();
final before = onBeforeRestart;
if (before != null) {
try {
await before();
} catch (e, st) {
// the apps own tidy up going wrong shouldnt strand it on the old build
print("[garage_updates] onBeforeRestart threw, restarting anyway: $e\n$st");
}
}
await inst.relaunch(args);
if (inst.exitsOnRestart) _exit(0);
}
@override
Future<void> markHealthy() async {
await _installer?.markHealthy();
}
Installer _need() {
final inst = _installer;
if (inst == null) {
throw UpdateError("not_installed", "This copy of the app can't be updated: $notInstalledReason");
}
return inst;
}
void close() {
client.close();
downloader.close();
}
}
@@ -0,0 +1,99 @@
import "dart:io";
import "mac_installer.dart";
import "models.dart";
import "windows_installer.dart";
/// The part that differs per platform: where downloads go, how a verified
/// archive becomes the installed app, and how the app is started again.
abstract class Installer {
/// "windows" | "macos" | "android", what the check is asked for
String get platform;
/// where the `.part` file and the finished download live
Directory get staging;
/// builds that failed to start here and must not be offered again
List<int> blockedBuilds();
/// Turns the verified [archive] into the installed app. Does not restart.
Future<void> apply(File archive, UpdateRelease release, {required int runningBuild});
/// Starts the app again. The caller ends this process afterwards when
/// [exitsOnRestart] says so.
Future<void> relaunch(List<String> args);
/// false on android, where the system installer does the restarting
bool get exitsOnRestart;
/// Counts a start of [build]. true = the previous build was just put back
/// because this one kept dying, relaunch.
Future<bool> noteStart(int build);
Future<void> markHealthy();
}
typedef ProcessRunner = Future<ProcessResult> Function(String exe, List<String> args);
typedef ProcessStarter = Future<void> Function(String exe, List<String> args);
Future<ProcessResult> defaultRunner(String exe, List<String> args) => Process.run(exe, args);
Future<void> defaultStarter(String exe, List<String> args) async {
// detached, it has to outlive us
await Process.start(exe, args, mode: ProcessStartMode.detached);
}
/// What [detectInstall] found. Exactly one of the two is set.
class InstallDetection {
const InstallDetection.found(Installer this.installer) : reason = null;
const InstallDetection.none(String this.reason) : installer = null;
final Installer? installer;
/// why this copy of the app isnt one we can update
final String? reason;
}
/// Works out whether this process is running from somewhere the updater put
/// it. A dev build, `flutter run`, `dart run`, a folder that isnt
/// `app-<build>`, a translocated or read only mac bundle: all "none", and the
/// updater then leaves the app completly alone.
InstallDetection detectInstall({
String? executable,
Map<String, String>? environment,
String? platform,
bool? product,
}) {
// debug + profile builds and anything run off the jit. a release build is
// the only thing that should ever get swapped
product ??= const bool.fromEnvironment("dart.vm.product");
if (!product) return const InstallDetection.none("this isn't a release build");
final exe = executable ?? Platform.resolvedExecutable;
final env = environment ?? Platform.environment;
switch (platform ?? Platform.operatingSystem) {
case "windows":
return WindowsInstaller.locate(exe, environment: env);
case "macos":
return MacInstaller.locate(exe, environment: env);
default:
return InstallDetection.none("no installer for ${platform ?? Platform.operatingSystem} here");
}
}
/// last bit of a path, whichever way the slashes lean
String baseName(String path) {
var p = path;
while (p.length > 1 && (p.endsWith("/") || p.endsWith("\\"))) {
p = p.substring(0, p.length - 1);
}
final cut = p.lastIndexOf(RegExp(r"[/\\]"));
return cut < 0 ? p : p.substring(cut + 1);
}
String joinPath(String a, String b, [String? c]) {
final sep = Platform.pathSeparator;
final ab = a.endsWith(sep) ? "$a$b" : "$a$sep$b";
return c == null ? ab : "$ab$sep$c";
}
+12
View File
@@ -0,0 +1,12 @@
// everything in core that needs dart:io. see core.dart
export "client.dart";
export "downloader.dart";
export "engine.dart";
export "installer.dart";
export "mac_installer.dart";
export "state.dart";
export "windows_installer.dart";
/// false on the web, where theres nothing to update
const bool kUpdatesSupported = true;
@@ -0,0 +1,343 @@
import "dart:convert";
import "dart:io";
import "installer.dart";
import "models.dart";
import "state.dart";
// macOS. No stub here, the bundle is swapped where it stands:
//
// unpack the zip with ditto, move the running .app out to
// ~/Library/Application Support/<bundle id>/garage_updates/previous.app,
// move the new one into its place, `open -n` it.
//
// A running app carries on fine after its bundle is moved, the files are
// still open. The fallback the windows stub does (3 starts that never get to
// markHealthy = go back) is done in here too, by noteStart().
const _maxFailedStarts = 3;
class MacInstaller implements Installer {
MacInstaller({
required this.bundle,
required this.bundleId,
required this.support,
ProcessRunner? run,
}) : _run = run ?? defaultRunner;
/// the .app we are running out of
final Directory bundle;
final String bundleId;
/// `~/Library/Application Support/<bundle id>/garage_updates`
final Directory support;
final ProcessRunner _run;
late final StateFile state = StateFile(File(joinPath(support.path, "state.json")));
Directory get previousApp => Directory(joinPath(support.path, "previous.app"));
static InstallDetection locate(String executable, {Map<String, String>? environment}) {
final env = environment ?? Platform.environment;
final bundle = _bundleOf(executable);
if (bundle == null) {
return InstallDetection.none("${baseName(executable)} isn't running from an app bundle");
}
final path = bundle.path;
if (path.contains("/AppTranslocation/")) {
// gatekeeper runs a quarantined app from a random read only mount untill
// its been moved by hand. nothing to swap there
return const InstallDetection.none("the app is translocated, move it to Applications first");
}
if (path.contains("/Build/Products/") || path.contains("/DerivedData/")) {
return const InstallDetection.none("the app is running out of a build folder");
}
if (!_writable(bundle.parent.path) || !_writable(path)) {
return InstallDetection.none("$path can't be replaced by this user");
}
final id = readBundleId(bundle);
if (id == null) {
return const InstallDetection.none("the bundle has no CFBundleIdentifier");
}
final home = env["HOME"];
if (home == null || home.isEmpty) {
return const InstallDetection.none("no HOME to keep the update state in");
}
return InstallDetection.found(MacInstaller(
bundle: bundle,
bundleId: id,
support: Directory("$home/Library/Application Support/$id/garage_updates"),
));
}
// the OUTERMOST .app in the path. a helper in Contents/MacOS, or in a login
// item bundle nested inside, still belongs to the app around it
static Directory? _bundleOf(String executable) {
final parts = executable.split("/");
for (var i = 0; i < parts.length - 1; i++) {
if (parts[i].endsWith(".app") && parts[i].length > 4) {
return Directory(parts.sublist(0, i + 1).join("/"));
}
}
return null;
}
static bool _writable(String path) {
try {
return Process.runSync("/bin/test", ["-w", path]).exitCode == 0;
} catch (e) {
print("[garage_updates] couldnt check whether $path is writable: $e");
return false;
}
}
@override
String get platform => "macos";
@override
bool get exitsOnRestart => true;
@override
Directory get staging => Directory(joinPath(support.path, "staging"));
@override
List<int> blockedBuilds() => state.read()?.blocked ?? const [];
@override
Future<void> apply(File archive, UpdateRelease release, {required int runningBuild}) async {
final unpack = Directory(joinPath(support.path, "unpack"));
await _wipe(unpack);
await unpack.create(recursive: true);
try {
switch (release.asset.format) {
case "zip":
await _must("/usr/bin/ditto", ["-x", "-k", archive.path, unpack.path], "unpack the update");
case "dmg":
await _fromDmg(archive, unpack);
default:
throw UpdateError("format", "A mac release has to be a zip or a dmg, not ${release.asset.format}");
}
final fresh = _findApp(unpack);
if (fresh == null) {
throw UpdateError("no_app", "There's no .app inside the update");
}
// dont let a mislabelled asset replace us with some other app
final freshId = readBundleId(fresh);
if (freshId != null && freshId != bundleId) {
throw UpdateError("wrong_app", "The update is for $freshId, this is $bundleId");
}
await _swap(fresh);
} finally {
await _wipe(unpack);
}
state.update((s) {
// what we are running is the truth, whatever the file last thought
s.previous = runningBuild;
s.current = release.build;
s.failedStarts = 0;
}, createIfMissing: true);
try {
if (archive.existsSync()) archive.deleteSync();
} catch (e) {
print("[garage_updates] couldnt remove ${archive.path} after installing it: $e");
}
}
Future<void> _swap(Directory fresh) async {
await _wipe(previousApp);
await support.create(recursive: true);
await _move(bundle.path, previousApp.path);
try {
await _move(fresh.path, bundle.path);
} catch (e, st) {
print("[garage_updates] couldnt move the new bundle in, putting the old one back: $e\n$st");
await _move(previousApp.path, bundle.path);
rethrow;
}
}
Future<void> _fromDmg(File dmg, Directory unpack) async {
final mount = Directory(joinPath(support.path, "mount"));
await _wipe(mount);
await mount.create(recursive: true);
await _must(
"/usr/bin/hdiutil",
["attach", "-nobrowse", "-readonly", "-noautoopen", "-mountpoint", mount.path, dmg.path],
"open the disk image",
);
try {
final app = _findApp(mount);
if (app == null) throw UpdateError("no_app", "There's no .app inside the disk image");
await _must(
"/usr/bin/ditto",
[app.path, joinPath(unpack.path, baseName(app.path))],
"copy the app off the disk image",
);
} finally {
final res = await _run("/usr/bin/hdiutil", ["detach", mount.path, "-force"]);
if (res.exitCode != 0) {
print("[garage_updates] couldnt detach ${mount.path}: ${res.stderr}");
}
await _wipe(mount);
}
}
// top level, or one folder down (a zip of a folder holding the app)
Directory? _findApp(Directory dir) {
final found = <Directory>[];
void look(Directory d, int depth) {
for (final e in d.listSync(followLinks: false)) {
if (e is! Directory) continue;
final name = baseName(e.path);
if (name == "__MACOSX") continue;
if (name.endsWith(".app")) {
found.add(e);
} else if (depth == 0) {
look(e, 1);
}
}
}
look(dir, 0);
if (found.isEmpty) return null;
final ours = baseName(bundle.path);
for (final f in found) {
if (baseName(f.path) == ours) return f;
}
return found.first;
}
@override
Future<void> relaunch(List<String> args) async {
await _must(
"/usr/bin/open",
["-n", bundle.path, if (args.isNotEmpty) ...["--args", ...args]],
"start the app again",
);
}
@override
Future<bool> noteStart(int build) async {
final s = state.read() ?? UpdateState();
if (s.current != build) {
// a build this file has never seen start. put there by hand, most likely
if (!previousApp.existsSync()) s.previous = null;
s.current = build;
s.failedStarts = 0;
}
if (s.failedStarts >= _maxFailedStarts && s.previous != null && previousApp.existsSync()) {
print("[garage_updates] build $build failed to start ${s.failedStarts} times, going back to ${s.previous}");
try {
await _swapBack();
} catch (e, st) {
print("[garage_updates] couldnt put the previous build back: $e\n$st");
return false;
}
if (!s.blocked.contains(build)) s.blocked.add(build);
s.current = s.previous;
s.previous = null;
s.failedStarts = 0;
state.write(s);
return true;
}
s.failedStarts++;
state.write(s);
return false;
}
Future<void> _swapBack() async {
final failed = Directory(joinPath(support.path, "failed.app"));
await _wipe(failed);
await _move(bundle.path, failed.path);
try {
await _move(previousApp.path, bundle.path);
} catch (e) {
print("[garage_updates] the previous bundle wouldnt move back, restoring: $e");
await _move(failed.path, bundle.path);
rethrow;
}
await _wipe(failed);
}
@override
Future<void> markHealthy() async {
final s = state.read();
if (s != null && s.failedStarts == 0) return;
state.update((s) => s.failedStarts = 0, createIfMissing: true);
}
Future<void> _move(String from, String to) async {
try {
await Directory(from).rename(to);
return;
} on FileSystemException catch (e) {
// another volume, rename cant cross those. mv copies when it has to
print("[garage_updates] rename $from -> $to failed (${e.osError?.message}), trying mv");
}
await _must("/bin/mv", [from, to], "move ${baseName(from)}");
}
Future<void> _must(String exe, List<String> args, String what) async {
final res = await _run(exe, args);
if (res.exitCode != 0) {
print("[garage_updates] ${baseName(exe)} ${args.join(" ")} exited ${res.exitCode}\n${res.stdout}\n${res.stderr}");
throw UpdateError("install_failed", "Couldn't $what");
}
}
Future<void> _wipe(Directory d) async {
try {
if (await d.exists()) await d.delete(recursive: true);
} catch (e) {
print("[garage_updates] couldnt remove ${d.path}: $e");
}
}
}
/// CFBundleIdentifier out of a bundles Info.plist, null when there isnt one
String? readBundleId(Directory app) {
final plist = File("${app.path}/Contents/Info.plist");
if (!plist.existsSync()) return null;
try {
final text = utf8.decode(plist.readAsBytesSync(), allowMalformed: true);
if (!text.startsWith("bplist")) {
final m = RegExp(r"<key>\s*CFBundleIdentifier\s*</key>\s*<string>([^<]+)</string>").firstMatch(text);
if (m != null) return m.group(1)!.trim();
}
// a binary plist, or xml laid out some way the regex didnt expect
final res = Process.runSync(
"/usr/libexec/PlistBuddy",
["-c", "Print :CFBundleIdentifier", plist.path],
);
if (res.exitCode == 0) {
final id = (res.stdout as String).trim();
if (id.isNotEmpty) return id;
}
} catch (e) {
print("[garage_updates] couldnt read ${plist.path}: $e");
}
return null;
}
+208
View File
@@ -0,0 +1,208 @@
import "dart:async";
// The shapes the update check hands back, and the one interface the flutter
// half drives. Nothing in here touches dart:io, so it compiles for the web
// where the whole package is a no-op.
enum UpdateStatus {
/// nothing newer for this platform
current,
/// theres a newer build, the app may carry on without it
available,
/// this build is below the projects minimum. the app must not start
required,
/// the server couldnt tell (no build sent), or we couldnt read its answer
unknown,
}
class UpdateAsset {
const UpdateAsset({
required this.url,
required this.filename,
required this.format,
required this.size,
required this.sha256,
});
final String url;
final String filename;
/// "zip" | "dmg" | "apk"
final String format;
final int size;
final String sha256;
static UpdateAsset? fromJson(Object? raw) {
if (raw is! Map) return null;
final url = _str(raw["url"]);
if (url == null || url.isEmpty) return null;
final filename = _str(raw["filename"]) ?? "";
var format = (_str(raw["format"]) ?? "").toLowerCase();
if (format.isEmpty) {
// older answers might not carry it, the filename says the same thing
final dot = filename.lastIndexOf(".");
if (dot >= 0) format = filename.substring(dot + 1).toLowerCase();
}
return UpdateAsset(
url: url,
filename: filename,
format: format,
size: _int(raw["size"]) ?? 0,
sha256: (_str(raw["sha256"]) ?? "").toLowerCase(),
);
}
Map<String, dynamic> toJson() => {
"url": url,
"filename": filename,
"format": format,
"size": size,
"sha256": sha256,
};
}
class UpdateRelease {
const UpdateRelease({
required this.label,
required this.build,
required this.asset,
this.notes = "",
this.publishedAt,
});
final String label;
final int build;
final String notes;
final DateTime? publishedAt;
final UpdateAsset asset;
static UpdateRelease? fromJson(Object? raw) {
if (raw is! Map) return null;
final build = _int(raw["build"]);
final asset = UpdateAsset.fromJson(raw["asset"]);
// a release we cant order or cant download is no use to anyone
if (build == null || asset == null) return null;
final published = _str(raw["published_at"]);
return UpdateRelease(
label: _str(raw["label"]) ?? "",
build: build,
notes: _str(raw["notes"]) ?? "",
publishedAt: published == null ? null : DateTime.tryParse(published),
asset: asset,
);
}
Map<String, dynamic> toJson() => {
"label": label,
"build": build,
"notes": notes,
"published_at": publishedAt?.toUtc().toIso8601String(),
"asset": asset.toJson(),
};
}
class UpdateInfo {
const UpdateInfo({required this.status, this.minimumBuild, this.latest});
final UpdateStatus status;
final int? minimumBuild;
final UpdateRelease? latest;
/// true when theres something to download
bool get hasUpdate =>
latest != null && (status == UpdateStatus.available || status == UpdateStatus.required);
bool get isRequired => status == UpdateStatus.required;
/// Reads the body of `GET /v1/updates/:pid`. Never throws on a strange
/// shape, it just comes back as unknown.
factory UpdateInfo.fromJson(Object? raw) {
if (raw is! Map) return const UpdateInfo(status: UpdateStatus.unknown);
final latest = UpdateRelease.fromJson(raw["latest"]);
var status = switch (_str(raw["status"])) {
"current" => UpdateStatus.current,
"available" => UpdateStatus.available,
"required" => UpdateStatus.required,
_ => UpdateStatus.unknown,
};
// says theres an update but didnt send one we can use
if (latest == null && (status == UpdateStatus.available || status == UpdateStatus.required)) {
print("[garage_updates] the check said ${status.name} but sent no usable release");
status = UpdateStatus.unknown;
}
return UpdateInfo(
status: status,
minimumBuild: _int(raw["minimum_build"]),
latest: latest,
);
}
UpdateInfo withStatus(UpdateStatus s) =>
UpdateInfo(status: s, minimumBuild: minimumBuild, latest: latest);
}
/// Anything the updater gives up on. `code` is stable, `message` is for a log.
class UpdateError implements Exception {
UpdateError(this.code, this.message);
final String code;
final String message;
@override
String toString() => "UpdateError($code): $message";
}
/// bytes so far, and the total when we know it
typedef DownloadProgress = void Function(int received, int? total);
/// What the splash and the background check drive. The real one is
/// `UpdateEngine` in core, the web gets none at all.
abstract class UpdateDriver {
/// false for a dev build, `flutter run`, a translocated mac bundle and so
/// on. When its false nothing else here does anything
bool get installed;
/// why not, for the one line that gets printed
String? get notInstalledReason;
/// Run right before the app is restarted into the new build, so an app can
/// stop its own helper processes first.
FutureOr<void> Function()? onBeforeRestart;
/// Counts this start. Comes back true when the last update kept failing to
/// start and the old build was put back - the caller should [restart].
Future<bool> noteStart();
Future<UpdateInfo> check();
/// Downloads + verifies. Safe to call again, it picks up where it stopped.
Future<void> download(UpdateRelease release, {DownloadProgress? onProgress});
/// Installs what [download] fetched. Does not restart.
Future<void> install(UpdateRelease release);
/// Starts the app again and ends this process. On android the system
/// installer does the restarting, so this returns.
Future<void> restart({List<String> args = const []});
Future<void> markHealthy();
}
String? _str(Object? v) => v is String ? v : null;
int? _int(Object? v) {
if (v is int) return v;
if (v is double && v.isFinite) return v.toInt();
if (v is String) return int.tryParse(v.trim());
return null;
}
+228
View File
@@ -0,0 +1,228 @@
import "dart:convert";
import "dart:io";
// `garage_updates.json` on windows (shared with the stub) and `state.json` on
// the mac. Same fields on both.
class UpdateState {
UpdateState({
this.exe,
this.current,
this.previous,
this.failedStarts = 0,
List<int>? blocked,
Map<String, dynamic>? extra,
}) : blocked = blocked ?? [],
extra = extra ?? {};
/// the real exe inside a version folder. windows only
String? exe;
int? current;
int? previous;
/// starts of `current` that never reached markHealthy
int failedStarts;
/// builds that failed 3 starts on this machine, never offered here again
List<int> blocked;
/// keys we dont know about. the stub may write more than we read, and
/// writing the file back must not lose them
Map<String, dynamic> extra;
factory UpdateState.fromJson(Map<dynamic, dynamic> j) {
final known = {"exe", "current", "previous", "failed_starts", "blocked"};
final blocked = <int>[];
final raw = j["blocked"];
if (raw is List) {
for (final b in raw) {
final n = _int(b);
if (n != null && !blocked.contains(n)) blocked.add(n);
}
}
return UpdateState(
exe: j["exe"] is String ? j["exe"] as String : null,
current: _int(j["current"]),
previous: _int(j["previous"]),
failedStarts: _int(j["failed_starts"]) ?? 0,
blocked: blocked,
extra: {
for (final e in j.entries)
if (e.key is String && !known.contains(e.key)) e.key as String: e.value,
},
);
}
Map<String, dynamic> toJson() => {
...extra,
if (exe != null) "exe": exe,
"current": current,
"previous": previous,
"failed_starts": failedStarts,
"blocked": blocked,
};
}
class StateFile {
StateFile(this.file);
final File file;
/// null when its missing, half written or not ours. Says which on the
/// console, never throws.
UpdateState? read() {
final j = _readObject(file);
return j == null ? null : UpdateState.fromJson(j);
}
/// Write to a temp file beside it, then rename over the top, so a reader
/// never sees half a file.
bool write(UpdateState state) => _writeObject(file, state.toJson());
/// Read, change, write. Without [createIfMissing] it does nothing when the
/// file cant be read, rather than writing an empty state over whatever the
/// stub had in there. The mac owns its file so it passes true, a damaged
/// one just gets started again.
bool update(void Function(UpdateState s) change, {bool createIfMissing = false}) {
var state = read();
if (state == null) {
if (!createIfMissing) return false;
state = UpdateState();
}
change(state);
return write(state);
}
}
/// What one person on the machine knows about the install, for when the
/// install itself is somewhere they cant write (Program Files). The stub
/// keeps it in `%LOCALAPPDATA%\<app id>\garage_updates.json` and it only
/// ever exists for an install like that.
class UserState {
UserState({
this.failedStarts = 0,
List<int>? blocked,
this.forCurrent,
this.runInstead,
}) : blocked = blocked ?? [];
int failedStarts;
/// builds that failed 3 starts for this user
List<int> blocked;
/// the `current` of the install the count was made against
int? forCurrent;
/// the build the stub starts for this user instead of `current`
int? runInstead;
factory UserState.fromJson(Map<dynamic, dynamic> j) {
final blocked = <int>[];
final raw = j["blocked"];
if (raw is List) {
for (final b in raw) {
final n = _int(b);
if (n != null && !blocked.contains(n)) blocked.add(n);
}
}
final count = _int(j["failed_starts"]) ?? 0;
return UserState(
failedStarts: count < 0 ? 0 : count,
blocked: blocked,
forCurrent: _int(j["for_current"]),
runInstead: _int(j["run_instead"]),
);
}
Map<String, dynamic> toJson() => {
"failed_starts": failedStarts,
"blocked": blocked,
"for_current": forCurrent,
"run_instead": runInstead,
};
/// The count and the build to run instead only mean anything for the
/// `current` they were made against. Once an update has gone in they start
/// again, what got blocked stays blocked. Same rule as the stub.
void settleFor(int? current) {
if (forCurrent == current) return;
forCurrent = current;
failedStarts = 0;
runInstead = null;
}
}
class UserStateFile {
UserStateFile(this.file);
final File file;
UserState? read() {
final j = _readObject(file);
return j == null ? null : UserState.fromJson(j);
}
bool write(UserState state) => _writeObject(file, state.toJson());
/// Same deal as [StateFile.update]. The app never passes
/// [createIfMissing], starting this file is the stubs job.
bool update(void Function(UserState s) change, {bool createIfMissing = false}) {
var state = read();
if (state == null) {
if (!createIfMissing) return false;
state = UserState();
}
change(state);
return write(state);
}
}
Map<dynamic, dynamic>? _readObject(File file) {
try {
if (!file.existsSync()) return null;
final text = file.readAsStringSync();
if (text.trim().isEmpty) {
print("[garage_updates] ${file.path} is empty");
return null;
}
final j = jsonDecode(text);
if (j is! Map) {
print("[garage_updates] ${file.path} isnt an object");
return null;
}
return j;
} catch (e) {
// most likely caught mid write by the other side
print("[garage_updates] couldnt read ${file.path}: $e");
return null;
}
}
bool _writeObject(File file, Map<String, dynamic> json) {
final tmp = File("${file.path}.tmp");
try {
file.parent.createSync(recursive: true);
tmp.writeAsStringSync(const JsonEncoder.withIndent(" ").convert(json), flush: true);
tmp.renameSync(file.path);
return true;
} catch (e, st) {
print("[garage_updates] couldnt write ${file.path}: $e\n$st");
try {
if (tmp.existsSync()) tmp.deleteSync();
} catch (e2) {
print("[garage_updates] and couldnt clear up ${tmp.path}: $e2");
}
return false;
}
}
int? _int(Object? v) {
if (v is int) return v;
if (v is double && v.isFinite) return v.toInt();
if (v is String) return int.tryParse(v.trim());
return null;
}
+4
View File
@@ -0,0 +1,4 @@
// the web's half of core: nothing. a site is updated by deploying it
/// false on the web, where theres nothing to update
const bool kUpdatesSupported = false;
@@ -0,0 +1,294 @@
import "dart:io";
import "installer.dart";
import "models.dart";
import "state.dart";
// Windows. The app never unpacks anything itself, the stub in <root> does:
//
// <root>\<AppExe>.exe the stub
// <root>\app-<build>\... a version folder, we are running out of one
// <root>\garage_updates.json state, the stubs and ours
//
// An install in Program Files cant be written by whoever is running the app,
// so there the stub keeps the count of starts in a file of the users own
// (see [UserState]). Everything read here is the two put together.
//
// All this side does is hand the stub a verified zip (`--garage-apply`), with
// a UAC prompt in front of it when <root> is in Program Files, and then start
// the stub again so it launches the new folder.
class WindowsInstaller implements Installer {
WindowsInstaller({
required this.root,
required this.stub,
required this.runningFolderBuild,
Map<String, String>? environment,
ProcessRunner? run,
ProcessStarter? start,
bool Function()? rootWritable,
}) : _env = environment ?? Platform.environment,
_run = run ?? defaultRunner,
_start = start ?? defaultStarter,
_rootWritableOverride = rootWritable;
final Directory root;
final File stub;
/// the number off the `app-<build>` folder this process lives in
final int runningFolderBuild;
final Map<String, String> _env;
final ProcessRunner _run;
final ProcessStarter _start;
final bool Function()? _rootWritableOverride;
late final StateFile state = StateFile(File(joinPath(root.path, "garage_updates.json")));
static final _versionFolder = RegExp(r"^app-(\d+)$");
static InstallDetection locate(String executable, {Map<String, String>? environment}) {
final folder = File(executable).parent;
final m = _versionFolder.firstMatch(baseName(folder.path));
if (m == null) {
return InstallDetection.none("${baseName(executable)} isn't running out of an app-<build> folder");
}
final root = folder.parent;
final stateFile = File(joinPath(root.path, "garage_updates.json"));
if (!stateFile.existsSync()) {
return const InstallDetection.none("there's no garage_updates.json beside the version folder");
}
final stub = _findStub(root, StateFile(stateFile).read(), executable);
if (stub == null) {
return const InstallDetection.none("there's no stub exe beside the version folder");
}
return InstallDetection.found(WindowsInstaller(
root: root,
stub: stub,
runningFolderBuild: int.parse(m.group(1)!),
environment: environment,
));
}
// the stub carries the apps exe name. a helper (stash-agent.exe) isnt named
// after it, so the state file is asked first and our own name second
static File? _findStub(Directory root, UpdateState? state, String executable) {
final names = <String>[
if (state?.exe != null) baseName(state!.exe!),
baseName(executable),
];
for (final n in names) {
final f = File(joinPath(root.path, n));
if (f.existsSync()) return f;
}
try {
final exes = root
.listSync()
.whereType<File>()
.where((f) => f.path.toLowerCase().endsWith(".exe"))
.toList();
if (exes.length == 1) return exes.single;
} catch (e) {
print("[garage_updates] couldnt look for the stub in ${root.path}: $e");
}
return null;
}
@override
String get platform => "windows";
@override
bool get exitsOnRestart => true;
/// "just me" installs are, Program Files isnt
bool get rootWritable {
final over = _rootWritableOverride;
if (over != null) return over();
final probe = File(joinPath(root.path, ".garage_updates_probe"));
try {
probe.writeAsStringSync("");
probe.deleteSync();
return true;
} on FileSystemException {
// the expected answer for Program Files, not worth a line in the log
return false;
}
}
/// The installer may leave `app_id` in the state file, otherwise the
/// folders name does.
String get appId {
final id = state.read()?.extra["app_id"];
// the stub wont make a folder out of one with these in, so neither do we
if (id is String && id.trim().isNotEmpty && !id.contains(RegExp("[\\\\/:*?\"<>|]"))) return id.trim();
return baseName(root.path);
}
/// `%LOCALAPPDATA%\<app id>\garage_updates.json`, the stubs count of starts
/// for this user when it couldnt write the one in root. The file is only
/// there for an install like that, we never make it.
UserStateFile? get userState {
final local = _env["LOCALAPPDATA"];
if (local == null || local.isEmpty) return null;
return UserStateFile(File(joinPath(local, appId, "garage_updates.json")));
}
UserState? _mine(UpdateState? rootState) {
final mine = userState?.read();
mine?.settleFor(rootState?.current);
return mine;
}
/// The build the stub starts for this user. `current`, unless that one
/// kept dying on them and the stub went back a build without being able to
/// say so in root.
int? get startsBuild {
final s = state.read();
final other = _mine(s)?.runInstead;
if (other != null && other != s?.current && Directory(joinPath(root.path, "app-$other")).existsSync()) {
return other;
}
return s?.current;
}
@override
Directory get staging {
if (rootWritable) return Directory(joinPath(root.path, "staging"));
final local = _env["LOCALAPPDATA"];
if (local == null || local.isEmpty) {
print("[garage_updates] no LOCALAPPDATA, staging in the temp folder");
return Directory(joinPath(Directory.systemTemp.path, appId, "staging"));
}
return Directory(joinPath(local, appId, "staging"));
}
@override
List<int> blockedBuilds() {
final s = state.read();
final out = <int>[...?s?.blocked];
// what failed for this user, on an install they cant write to
for (final b in _mine(s)?.blocked ?? const <int>[]) {
if (!out.contains(b)) out.add(b);
}
return out;
}
@override
Future<void> apply(File archive, UpdateRelease release, {required int runningBuild}) async {
if (release.asset.format != "zip") {
throw UpdateError("format", "A windows release has to be a zip, not ${release.asset.format}");
}
final args = ["--garage-apply", archive.path, "${release.build}"];
final ProcessResult res;
if (rootWritable) {
res = await _run(stub.path, args);
} else {
// one UAC prompt. powershell is only the thing that can ask for it
res = await _run(powershellPath(_env), elevationArgs(stub.path, args));
}
if (res.exitCode != 0) {
print("[garage_updates] the stub exited ${res.exitCode}\n${res.stdout}\n${res.stderr}");
if (res.exitCode == kElevationRefused) {
throw UpdateError("elevation_refused", "Administrator permission was not given");
}
throw UpdateError("install_failed", "The update could not be installed (${res.exitCode})");
}
// belt and braces. a stub that said 0 but didnt move `current` would have
// us restart straight back into the old build, forever
final now = state.read();
if (now != null && now.current != release.build) {
throw UpdateError("install_failed", "The update did not take, still on build ${now.current}");
}
try {
if (archive.existsSync()) archive.deleteSync();
} catch (e) {
print("[garage_updates] couldnt remove ${archive.path} after installing it: $e");
}
}
@override
Future<void> relaunch(List<String> args) => _start(stub.path, args);
/// the stub counts starts on windows, before it launches us
@override
Future<bool> noteStart(int build) async => false;
@override
Future<void> markHealthy() async {
final s = state.read();
if (s != null && s.failedStarts != 0) state.update((s) => s.failedStarts = 0);
// the stub counted in here instead if it couldnt write to root
final mine = userState;
final u = mine?.read();
if (mine != null && u != null && u.failedStarts != 0) mine.update((u) => u.failedStarts = 0);
}
}
/// ERROR_CANCELLED, what windows gives when the UAC prompt is turned down
const kElevationRefused = 1223;
String powershellPath(Map<String, String> env) {
final sys = env["SystemRoot"] ?? env["SYSTEMROOT"] ?? env["windir"];
if (sys != null && sys.isNotEmpty) {
final full = "$sys\\System32\\WindowsPowerShell\\v1.0\\powershell.exe";
if (File(full).existsSync()) return full;
}
return "powershell";
}
/// The powershell command line that runs [exe] elevated and passes its exit
/// code back out. Start-Process -Verb RunAs is ShellExecute "runas".
List<String> elevationArgs(String exe, List<String> args) {
final line = args.map(windowsQuoteArg).join(" ");
// without the try a refused prompt leaves $p null and powershell exits 0
final script = "\$ErrorActionPreference = 'Stop'; "
"try { "
"\$p = Start-Process -FilePath ${powershellQuote(exe)} -ArgumentList ${powershellQuote(line)} "
"-Verb RunAs -Wait -PassThru -WindowStyle Hidden; "
"exit \$p.ExitCode "
"} catch { [Console]::Error.WriteLine(\$_); exit $kElevationRefused }";
return ["-NoProfile", "-ExecutionPolicy", "Bypass", "-WindowStyle", "Hidden", "-Command", script];
}
/// a single quoted powershell string, nothing inside it is expanded
String powershellQuote(String s) => "'${s.replaceAll("'", "''")}'";
/// One argument the way CommandLineToArgvW wants it. Backslashes only matter
/// in front of a quote, which is the bit everyone gets wrong with a path that
/// ends in one.
String windowsQuoteArg(String arg) {
if (arg.isNotEmpty && !arg.contains(RegExp("[ \t\n\"]"))) return arg;
final out = StringBuffer("\"");
var slashes = 0;
for (final ch in arg.split("")) {
if (ch == "\\") {
slashes++;
continue;
}
if (ch == "\"") {
out.write("\\" * (slashes * 2 + 1));
out.write("\"");
} else {
out.write("\\" * slashes);
out.write(ch);
}
slashes = 0;
}
out.write("\\" * (slashes * 2));
out.write("\"");
return out.toString();
}
@@ -0,0 +1,83 @@
import "dart:io";
import "package:flutter/foundation.dart";
import "package:flutter/services.dart";
import "../core/installer.dart";
import "../core/models.dart";
// Android. The apk is downloaded into the apps cache and handed to the system
// installer, which always asks. It also does the restarting, so theres no
// relaunch and no fallback here - a build that wont start is androids problem.
const _channel = MethodChannel("net.imbenji.garage_updates");
const _playStore = "com.android.vending";
class AndroidInstaller implements Installer {
AndroidInstaller(this.cacheDir);
final Directory cacheDir;
static Future<InstallDetection> locate() async {
if (!kReleaseMode) {
// a debug apk is signed with the debug key, a release wouldnt install
// over it anyway
return const InstallDetection.none("this isn't a release build");
}
final Map<String, dynamic>? info;
try {
info = await _channel.invokeMapMethod<String, dynamic>("info");
} catch (e, st) {
print("[garage_updates] couldnt ask android about the install: $e\n$st");
return const InstallDetection.none("the garage_updates plugin didn't answer");
}
if (info?["installer"] == _playStore) {
return const InstallDetection.none("installed from the Play Store, which does the updating");
}
final cache = info?["cacheDir"];
if (cache is! String || cache.isEmpty) {
return const InstallDetection.none("android gave no cache folder to download into");
}
return InstallDetection.found(AndroidInstaller(Directory(cache)));
}
@override
String get platform => "android";
@override
bool get exitsOnRestart => false;
// has to match the cache-path in the plugins file provider xml
@override
Directory get staging => Directory("${cacheDir.path}/garage_updates");
@override
List<int> blockedBuilds() => const [];
@override
Future<void> apply(File archive, UpdateRelease release, {required int runningBuild}) async {
if (release.asset.format != "apk") {
throw UpdateError("format", "An android release has to be an apk, not ${release.asset.format}");
}
try {
await _channel.invokeMethod<void>("install", {"path": archive.path});
} on PlatformException catch (e, st) {
print("[garage_updates] the system installer wouldnt open: $e\n$st");
throw UpdateError("install_failed", e.message ?? "The installer could not be opened");
}
}
@override
Future<void> relaunch(List<String> args) async {}
@override
Future<bool> noteStart(int build) async => false;
@override
Future<void> markHealthy() async {}
}
@@ -0,0 +1 @@
export "driver_io.dart" if (dart.library.js_interop) "driver_stub.dart";
@@ -0,0 +1,31 @@
import "dart:io";
import "../core/engine.dart";
import "../core/models.dart";
import "android_installer.dart";
/// The engine for whatever this is running on. null where the package has
/// nothing to do at all (linux, ios).
Future<UpdateDriver?> openDriver({
required String project,
required int build,
required String apiBase,
}) async {
if (Platform.isWindows || Platform.isMacOS) {
return UpdateEngine.detect(project: project, build: build, apiBase: apiBase);
}
if (Platform.isAndroid) {
// core cant do android, installing an apk goes through the plugin
final found = await AndroidInstaller.locate();
return UpdateEngine(
project: project,
build: build,
apiBase: apiBase,
installer: found.installer,
notInstalledReason: found.reason,
);
}
return null;
}
@@ -0,0 +1,10 @@
import "../core/models.dart";
// the web's half. nothing to update, so no driver
Future<UpdateDriver?> openDriver({
required String project,
required int build,
required String apiBase,
}) async =>
null;
+186
View File
@@ -0,0 +1,186 @@
import "dart:async";
import "package:flutter/foundation.dart";
import "package:flutter/widgets.dart";
import "package:garage_ui/garage_ui.dart";
import "branding.dart";
// What's on screen before the app's own runApp. A fixed layout and nothing to
// configure but the logo and the name: logo, name, one status line, a bar,
// and when a required update wont go in, why and a Retry.
enum SplashStage { checking, downloading, installing, starting }
class SplashController extends ChangeNotifier {
SplashStage _stage = SplashStage.checking;
double? _progress;
String? _error;
Completer<void>? _retry;
SplashStage get stage => _stage;
/// 0 to 1 while theres a number to show, null = busy
double? get progress => _progress;
/// set when a required update failed. the Retry button shows with it
String? get error => _error;
String get statusLine => switch (_stage) {
SplashStage.checking => "Checking for updates",
SplashStage.downloading => "Downloading update",
SplashStage.installing => "Installing",
SplashStage.starting => "Starting",
};
void show(SplashStage stage, {double? progress}) {
_stage = stage;
_progress = progress;
_error = null;
notifyListeners();
}
set progress(double? v) {
if (v == _progress) return;
_progress = v;
notifyListeners();
}
/// Puts the error up and waits for Retry to be pressed.
Future<void> fail(String message) {
_error = message;
// a bar sweeping away under an error reads as still trying
_progress ??= 0;
final c = _retry = Completer<void>();
notifyListeners();
return c.future;
}
void retry() {
final c = _retry;
_retry = null;
_error = null;
notifyListeners();
if (c != null && !c.isCompleted) c.complete();
}
}
class UpdateSplash extends StatelessWidget {
const UpdateSplash({required this.branding, required this.controller, super.key});
final UpdaterBranding branding;
final SplashController controller;
@override
Widget build(BuildContext context) {
final density = GarageTheme.of(context).density;
final logo = branding.buildLogo();
return Scaffold(
child: Center(
child: SizedBox(
width: density.fontSize * 22,
child: ListenableBuilder(
listenable: controller,
builder: (context, _) {
final error = controller.error;
return Column(
mainAxisSize: MainAxisSize.min,
children: [
if (logo != null) ...[
SizedBox.square(dimension: density.controlHeight * 2, child: logo),
const Gap.lg(),
],
Text(branding.name).large().semiBold(),
const Gap.sm(),
Text(controller.statusLine).muted(),
const Gap.lg(),
// the bar has no width of its own, it takes the columns
SizedBox(
width: double.infinity,
child: LinearProgressIndicator(value: controller.progress),
),
if (error != null) ...[
const Gap.xl(),
Text(error).muted(),
const Gap.md(),
Button(
style: const ButtonStyle.outline(),
onPressed: controller.retry,
child: const Text("Retry"),
),
],
],
);
},
),
),
),
);
}
}
/// The tiny app `launch` runs to get the splash on screen. The host app's own
/// runApp replaces it, and [onGone] is how the updater finds out it has.
class UpdateSplashApp extends StatefulWidget {
const UpdateSplashApp({
required this.branding,
required this.controller,
this.onGone,
super.key,
});
final UpdaterBranding branding;
final SplashController controller;
final VoidCallback? onGone;
static final defaultTheme = ThemeData(
colorScheme: GarageSchemes.carbon,
density: const Density.product(),
);
@override
State<UpdateSplashApp> createState() => _UpdateSplashAppState();
}
class _UpdateSplashAppState extends State<UpdateSplashApp> {
late final _delegate = _SplashDelegate(
(context) => UpdateSplash(branding: widget.branding, controller: widget.controller),
);
late final _router = RouterConfig<Object>(routerDelegate: _delegate);
@override
void dispose() {
_delegate.dispose();
widget.onGone?.call();
super.dispose();
}
@override
Widget build(BuildContext context) {
return GarageApp.router(
routerConfig: _router,
theme: widget.branding.theme ?? UpdateSplashApp.defaultTheme,
title: widget.branding.name,
);
}
}
// one page and nowhere to go. GarageApp only comes as a router, and pulling
// go_router into every app that wants updates for this would be daft
class _SplashDelegate extends RouterDelegate<Object> with ChangeNotifier {
_SplashDelegate(this.builder);
final WidgetBuilder builder;
@override
Widget build(BuildContext context) => builder(context);
@override
Future<bool> popRoute() => SynchronousFuture(false);
@override
Future<void> setNewRoutePath(Object configuration) => SynchronousFuture(null);
}
+322
View File
@@ -0,0 +1,322 @@
import "dart:async";
import "package:flutter/foundation.dart";
import "package:flutter/widgets.dart";
import "branding.dart";
import "core/models.dart";
import "platform/driver.dart";
import "splash.dart";
const _defaultApiBase = "https://pay.imbenji.net/api";
/// how long the splash waits on the check before letting the app start
const _checkWait = Duration(seconds: 2);
const _recheckEvery = Duration(hours: 6);
/// after the apps first frame. long enough that a build which dies on the way
/// up doesnt get called healthy
const _healthyAfter = Duration(seconds: 3);
class GarageUpdater {
GarageUpdater._();
/// There before [launch] is called, so an app can set [onBeforeRestart]
/// ahead of a restart that happens inside the splash.
static GarageUpdater get instance => _instance;
static GarageUpdater _instance = GarageUpdater._();
/// The one call, at the top of `main(List<String> args)`. Completes when
/// the app should carry on to its own runApp. For a required update that
/// is never: it restarts into the new build instead.
static Future<void> launch({
required List<String> args,
required String project,
required int build,
required String label,
required UpdaterBranding branding,
String apiBase = _defaultApiBase,
UpdateMode mode = UpdateMode.silent,
}) {
return instance.start(
args: args,
project: project,
build: build,
label: label,
branding: branding,
apiBase: apiBase,
mode: mode,
);
}
final ValueNotifier<UpdateInfo?> _ready = ValueNotifier<UpdateInfo?>(null);
/// null untill a newer build has been downloaded and verified. Then
/// [restartToUpdate] moves over to it.
ValueListenable<UpdateInfo?> get ready => _ready;
/// the same thing as a stream, for anyone who would rather await it
Stream<UpdateInfo> get readyStream => _readyStream.stream;
final _readyStream = StreamController<UpdateInfo>.broadcast();
/// The release notes of the newest build we know about. The splash never
/// shows these, they are for the app.
String? get notes => (_ready.value ?? _lastCheck)?.latest?.notes;
/// what the last check that got an answer said
UpdateInfo? get lastCheck => _lastCheck;
/// the label this build was launched with ("v2610-1")
String? get label => _label;
/// Run right before the app is restarted into a new build. Stop helper
/// processes here.
FutureOr<void> Function()? onBeforeRestart;
UpdateDriver? _driver;
UpdateInfo? _lastCheck;
UpdateMode _mode = UpdateMode.silent;
List<String> _args = const [];
String? _label;
bool _started = false;
bool _fetching = false;
Timer? _recheck;
Timer? _healthy;
/// [launch] with the seams showing. [driver] and [show] are for tests.
@visibleForTesting
Future<void> start({
required List<String> args,
required String project,
required int build,
required String label,
required UpdaterBranding branding,
String apiBase = _defaultApiBase,
UpdateMode mode = UpdateMode.silent,
UpdateDriver? driver,
void Function(Widget app)? show,
Duration checkWait = _checkWait,
}) async {
if (_started) {
print("[garage_updates] launch was called twice, ignoring the second");
return;
}
_started = true;
_args = List.of(args);
_mode = mode;
_label = label;
// a site is updated by deploying it
if (kIsWeb) return;
var d = driver;
if (d == null) {
try {
d = await openDriver(project: project, build: build, apiBase: apiBase);
} catch (e, st) {
print("[garage_updates] couldnt set the updater up, starting without it: $e\n$st");
return;
}
}
if (d == null) return;
if (!d.installed) {
// a dev build, flutter run, a copy that isnt in the layout. hands off
print("[garage_updates] not updating this copy: ${d.notInstalledReason}");
return;
}
_driver = d;
d.onBeforeRestart = () => onBeforeRestart?.call();
try {
// the mac counts its own starts. true = the last update kept dying and
// the old build has just been put back
if (await d.noteStart()) {
await d.restart(args: _args);
}
} catch (e, st) {
print("[garage_updates] couldnt count this start: $e\n$st");
}
WidgetsFlutterBinding.ensureInitialized();
final splash = SplashController();
(show ?? runApp)(UpdateSplashApp(
branding: branding,
controller: splash,
onGone: _hostAppIsUp,
));
await _behindTheSplash(d, splash, checkWait);
splash.show(SplashStage.starting);
_recheck = Timer.periodic(_recheckEvery, (_) => checkNow());
}
Future<void> _behindTheSplash(UpdateDriver d, SplashController splash, Duration wait) async {
while (true) {
splash.show(SplashStage.checking);
final UpdateInfo info;
final asking = d.check();
try {
info = await asking.timeout(wait);
} on TimeoutException {
// no answer in time. the app starts, the answer is dealt with whenever
// it turns up
print("[garage_updates] no answer from the update check yet, starting the app");
unawaited(asking.then(_gotLateAnswer, onError: (Object e, StackTrace st) {
print("[garage_updates] the update check failed: $e\n$st");
}));
return;
} catch (e, st) {
print("[garage_updates] the update check failed, starting the app: $e\n$st");
return;
}
_lastCheck = info;
final latest = info.latest;
if (info.isRequired) {
if (latest == null) {
// below the minimum, and the only newer build is blocked here
await splash.fail("This version can no longer be used, and the update can't be installed here.");
continue;
}
try {
await _fetchAndInstall(d, latest, splash);
await d.restart(args: _args);
} catch (e, st) {
print("[garage_updates] the required update failed: $e\n$st");
await splash.fail(_sayWhy(e));
continue;
}
// only android gets here, its installer is a prompt over the top of us
await splash.fail("Install the update to continue.");
continue;
}
if (latest == null || !info.hasUpdate) return;
if (_mode == UpdateMode.prompt || defaultTargetPlatform == TargetPlatform.android) {
// android always asks, so its never sprung on someone at launch
unawaited(_fetchQuietly(info));
return;
}
try {
await _fetchAndInstall(d, latest, splash);
await d.restart(args: _args);
} catch (e, st) {
// not required, so its not worth keeping anyone out of the app over
print("[garage_updates] couldnt update at launch, starting the old build: $e\n$st");
}
return;
}
}
Future<void> _fetchAndInstall(UpdateDriver d, UpdateRelease latest, SplashController splash) async {
splash.show(SplashStage.downloading, progress: 0);
await d.download(latest, onProgress: (got, total) {
splash.progress = (total == null || total <= 0) ? null : (got / total).clamp(0.0, 1.0);
});
splash.show(SplashStage.installing);
await d.install(latest);
splash.show(SplashStage.starting);
}
String _sayWhy(Object e) {
if (e is UpdateError) return e.message;
return "The update could not be installed.";
}
void _gotLateAnswer(UpdateInfo info) {
_lastCheck = info;
if (info.hasUpdate) unawaited(_fetchQuietly(info));
}
/// Asks again now, and fetches whatever is newer. Runs by itself every 6
/// hours, an app can call it from a "check for updates" button.
Future<UpdateInfo?> checkNow() async {
final d = _driver;
if (d == null) return null;
try {
final info = await d.check();
_lastCheck = info;
if (info.hasUpdate) await _fetchQuietly(info);
return info;
} catch (e, st) {
print("[garage_updates] the background update check failed: $e\n$st");
return null;
}
}
Future<void> _fetchQuietly(UpdateInfo info) async {
final d = _driver;
final latest = info.latest;
if (d == null || latest == null || _fetching) return;
if (_ready.value?.latest?.build == latest.build) return;
_fetching = true;
try {
await d.download(latest);
_ready.value = info;
_readyStream.add(info);
} catch (e, st) {
// the part file is kept, the next check carries on from it
print("[garage_updates] the background download failed: $e\n$st");
} finally {
_fetching = false;
}
}
/// Installs the update that [ready] announced and restarts into it. Throws
/// an [UpdateError] when it wont go in (a UAC prompt turned down, say).
Future<void> restartToUpdate() async {
final d = _driver;
final latest = _ready.value?.latest;
if (d == null || latest == null) {
print("[garage_updates] restartToUpdate with no update waiting, nothing to do");
return;
}
try {
await d.install(latest);
await d.restart(args: _args);
} catch (e, st) {
print("[garage_updates] couldnt restart into build ${latest.build}: $e\n$st");
rethrow;
}
}
/// Tells the updater this build starts fine, which stops it being rolled
/// back. Called for you a few seconds after the first frame.
Future<void> markHealthy() async {
try {
await _driver?.markHealthy();
} catch (e, st) {
print("[garage_updates] couldnt mark this build healthy: $e\n$st");
}
}
// the splash was just torn down, which is the host app's runApp taking over.
// its first frame is the next one
void _hostAppIsUp() {
WidgetsBinding.instance.addPostFrameCallback((_) {
_healthy?.cancel();
_healthy = Timer(_healthyAfter, markHealthy);
});
}
/// Puts a fresh updater in [instance]. Tests only.
@visibleForTesting
static void reset() {
_instance._recheck?.cancel();
_instance._healthy?.cancel();
_instance = GarageUpdater._();
}
}
+37
View File
@@ -0,0 +1,37 @@
name: garage_updates
description: "Auto updates for Garage apps — asks Garage for the newest release, downloads it with resume, checks the sha256, installs it beside the old one and restarts into it."
version: 0.1.0
publish_to: 'none'
environment:
sdk: ^3.10.0
flutter: ">=3.5.0"
dependencies:
flutter:
sdk: flutter
# the splash is drawn with the design system, nothing of its own
garage_ui:
path: ../garage_ui
# sha256 of the download, streamed off disk
crypto: ^3.0.6
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^6.0.0
flutter:
plugin:
platforms:
android:
package: net.imbenji.garage_updates
pluginClass: GarageUpdatesPlugin
# no channel on windows. ffiPlugin only so the host app's build pulls in
# windows/CMakeLists.txt, which is where the stub exe gets built
windows:
ffiPlugin: true
+167
View File
@@ -0,0 +1,167 @@
import "dart:io";
import "package:flutter_test/flutter_test.dart";
import "package:garage_updates/core.dart";
import "support/fake_server.dart";
void main() {
late FakeServer server;
late UpdateClient client;
setUp(() async {
server = await FakeServer.start(const []);
client = UpdateClient(project: "proj_1", apiBase: "${server.base}/", httpClient: HttpClient());
});
tearDown(() async {
client.close();
await server.close();
});
Future<UpdateInfo> check() => client.check(platform: "windows", arch: "x64", build: 12);
Map<String, dynamic> latest({Object? build = 13}) => {
"label": "v2610-1",
"build": build,
"notes": "Fixed the thing",
"published_at": "2026-10-01T10:00:00Z",
"asset": {
"url": "https://cdn.example.com/app.zip",
"filename": "app.zip",
"format": "zip",
"size": 1234,
"sha256": "ABCDEF",
},
};
test("asks the right url", () async {
server.updateBody = {"status": "current", "minimum_build": null, "latest": null};
await check();
expect(server.log.single, "GET /v1/updates/proj_1");
final uri = client.checkUri(platform: "macos", arch: "arm64", build: 7);
expect(uri.queryParameters, {"platform": "macos", "arch": "arm64", "build": "7"});
// the trailing slash on apiBase didnt double up
expect(uri.path, "/v1/updates/proj_1");
});
test("current", () async {
server.updateBody = {"status": "current", "minimum_build": 4, "latest": null};
final info = await check();
expect(info.status, UpdateStatus.current);
expect(info.minimumBuild, 4);
expect(info.latest, isNull);
expect(info.hasUpdate, isFalse);
});
test("available", () async {
server.updateBody = {"status": "available", "minimum_build": null, "latest": latest()};
final info = await check();
expect(info.status, UpdateStatus.available);
expect(info.hasUpdate, isTrue);
expect(info.isRequired, isFalse);
final l = info.latest!;
expect(l.label, "v2610-1");
expect(l.build, 13);
expect(l.notes, "Fixed the thing");
expect(l.publishedAt, DateTime.utc(2026, 10, 1, 10));
expect(l.asset.url, "https://cdn.example.com/app.zip");
expect(l.asset.filename, "app.zip");
expect(l.asset.format, "zip");
expect(l.asset.size, 1234);
// lower cased, its compared against our own hex
expect(l.asset.sha256, "abcdef");
});
test("required", () async {
server.updateBody = {"status": "required", "minimum_build": 13, "latest": latest()};
final info = await check();
expect(info.status, UpdateStatus.required);
expect(info.isRequired, isTrue);
expect(info.minimumBuild, 13);
});
test("unknown", () async {
server.updateBody = {"status": "unknown", "minimum_build": null, "latest": null};
expect((await check()).status, UpdateStatus.unknown);
});
test("a status we've never heard of is unknown", () async {
server.updateBody = {"status": "sideways", "latest": latest()};
expect((await check()).status, UpdateStatus.unknown);
});
test("numbers as strings, missing keys and the wrong types are put up with", () async {
final l = latest(build: "13");
(l["asset"] as Map)["size"] = "1234";
(l["asset"] as Map).remove("format");
l["notes"] = 42;
l.remove("published_at");
server.updateBody = {"status": "available", "minimum_build": "9", "latest": l};
final info = await check();
expect(info.minimumBuild, 9);
expect(info.latest!.build, 13);
expect(info.latest!.notes, "");
expect(info.latest!.publishedAt, isNull);
expect(info.latest!.asset.size, 1234);
// worked out from the filename
expect(info.latest!.asset.format, "zip");
});
test("available with nothing usable to download is unknown", () async {
final l = latest();
l.remove("asset");
server.updateBody = {"status": "available", "latest": l};
final info = await check();
expect(info.status, UpdateStatus.unknown);
expect(info.hasUpdate, isFalse);
});
test("a body that isnt json, or isnt an object, is unknown", () async {
server.updateBody = "<html>bad gateway</html>";
expect((await check()).status, UpdateStatus.unknown);
server.updateBody = [1, 2, 3];
expect((await check()).status, UpdateStatus.unknown);
});
test("a relative asset url is resolved against the api", () async {
final l = latest();
(l["asset"] as Map)["url"] = "/v1/updates/proj_1/download/a1";
server.updateBody = {"status": "available", "latest": l};
final info = await check();
expect(info.latest!.asset.url, "${server.base}/v1/updates/proj_1/download/a1");
});
test("an error status throws the store api's code", () async {
server.updateStatus = 404;
server.updateBody = {"error": "not_found", "message": "No such project"};
await expectLater(
check(),
throwsA(isA<UpdateError>()
.having((e) => e.code, "code", "not_found")
.having((e) => e.message, "message", "No such project")),
);
});
test("an error status with no json body still throws", () async {
server.updateStatus = 502;
server.updateBody = "bad gateway";
await expectLater(check(), throwsA(isA<UpdateError>().having((e) => e.code, "code", "http_502")));
});
test("a server that isnt there throws network", () async {
await server.close();
await expectLater(check(), throwsA(isA<UpdateError>().having((e) => e.code, "code", "network")));
});
}
+36
View File
@@ -0,0 +1,36 @@
// Not a flutter test, a plain dart program:
//
// dart run test/core_headless.dart
//
// It imports core and nothing else and runs on the standalone vm, which has
// no dart:ui. If core ever picked up a flutter import this wouldnt compile.
import "dart:io";
import "package:garage_updates/core.dart";
Future<void> main() async {
final engine = UpdateEngine.detect(project: "proj_headless", build: 1);
// `dart run` is the jit, so this is a dev copy and the engine must sit still
if (engine.installed) {
stderr.writeln("FAIL: a dart run was taken for an install");
exit(1);
}
engine.reportIfNotInstalled();
final info = await engine.check();
if (info.status != UpdateStatus.unknown) {
stderr.writeln("FAIL: an engine with no install asked the server");
exit(1);
}
final state = StateFile(File("${Directory.systemTemp.path}/garage_updates_headless_missing.json"));
if (state.read() != null) {
stderr.writeln("FAIL: a missing state file read as something");
exit(1);
}
engine.close();
print("core runs headless: supported=$kUpdatesSupported arch=${currentUpdateArch()} platform=${currentUpdatePlatform()}");
}
@@ -0,0 +1,85 @@
import "dart:io";
import "package:flutter_test/flutter_test.dart";
// core.dart is for headless dart programs, so nothing it reaches may import
// flutter. This walks the imports from lib/core.dart (both sides of every
// conditional one) and checks. test/core_headless.dart is the other half: it
// actually runs core on the plain dart vm, which has no dart:ui to give.
final _directive = RegExp(r'''^\s*(?:import|export)\s+([^;]+);''', multiLine: true);
final _uri = RegExp(r'''["']([^"']+)["']''');
Set<String> _walk(File start) {
final seen = <String>{};
final uris = <String>{};
final queue = [start];
while (queue.isNotEmpty) {
final f = queue.removeLast();
if (!seen.add(f.absolute.path)) continue;
for (final d in _directive.allMatches(f.readAsStringSync())) {
for (final m in _uri.allMatches(d.group(1)!)) {
final uri = m.group(1)!;
if (uri.startsWith("dart:") || uri.startsWith("package:")) {
uris.add(uri);
} else {
queue.add(File.fromUri(f.absolute.uri.resolve(uri)));
}
}
}
}
return uris;
}
void main() {
test("core.dart reaches no flutter", () {
final uris = _walk(File("lib/core.dart"));
expect(uris, isNotEmpty);
expect(uris.where((u) => u.startsWith("package:flutter")), isEmpty);
expect(uris.where((u) => u.startsWith("package:garage_ui")), isEmpty);
expect(uris, isNot(contains("dart:ui")));
// and the only package it leans on at all
expect(uris.where((u) => u.startsWith("package:")).toSet(), {"package:crypto/crypto.dart"});
});
test("core's web side reaches no dart:io", () {
final uris = {
..._walk(File("lib/src/core/models.dart")),
..._walk(File("lib/src/core/web.dart")),
};
expect(uris, isNot(contains("dart:io")));
expect(uris, isNot(contains("dart:ffi")));
});
test("the flutter entry point reaches dart:io only behind a conditional import", () {
// everything garage_updates.dart can reach on the web: the stub side of
// each conditional import, never the io side
final seen = <String>{};
final uris = <String>{};
final queue = [File("lib/garage_updates.dart")];
while (queue.isNotEmpty) {
final f = queue.removeLast();
if (!seen.add(f.absolute.path)) continue;
for (final d in _directive.allMatches(f.readAsStringSync())) {
// of a conditional pair the last uri is the one the web gets
final uri = _uri.allMatches(d.group(1)!).last.group(1)!;
if (uri.startsWith("dart:") || uri.startsWith("package:")) {
uris.add(uri);
} else {
queue.add(File.fromUri(f.absolute.uri.resolve(uri)));
}
}
}
expect(seen.where((p) => p.endsWith("driver_stub.dart")), isNotEmpty);
expect(seen.where((p) => p.endsWith("driver_io.dart")), isEmpty);
expect(uris, isNot(contains("dart:io")));
expect(uris, isNot(contains("dart:ffi")));
});
}
+260
View File
@@ -0,0 +1,260 @@
import "dart:convert";
import "dart:io";
import "package:flutter_test/flutter_test.dart";
import "package:garage_updates/core.dart";
import "support/fake_server.dart";
void main() {
late FakeServer server;
late Directory staging;
final data = noise(200 * 1024);
Downloader make({int retries = 0}) => Downloader(
httpClient: HttpClient(),
retries: retries,
retryPause: const Duration(milliseconds: 10),
quietTimeout: const Duration(seconds: 5),
);
setUp(() async {
server = await FakeServer.start(data);
staging = Directory("${Directory.systemTemp.createTempSync("gu_dl_").path}/staging");
});
tearDown(() async {
await server.close();
if (staging.parent.existsSync()) staging.parent.deleteSync(recursive: true);
});
test("downloads, verifies and renames", () async {
final release = server.release();
final seen = <int>[];
int? total;
final file = await make().fetch(
release: release,
staging: staging,
onProgress: (got, t) {
seen.add(got);
total = t;
},
);
expect(file.path, Downloader.finishedFile(staging, release).path);
expect(file.path.endsWith("update-13.zip"), isTrue);
expect(file.readAsBytesSync(), data);
expect(seen.last, data.length);
expect(total, data.length);
// nothing left lying about
expect(Downloader.partFile(staging).existsSync(), isFalse);
expect(Downloader.metaFile(staging).existsSync(), isFalse);
});
test("a cut connection keeps the part, and the next go resumes with Range", () async {
final release = server.release();
server.cutsLeft = 1;
server.cutAfter = 50 * 1024;
await expectLater(
make().fetch(release: release, staging: staging),
throwsA(isA<UpdateError>().having((e) => e.code, "code", "download")),
);
final part = Downloader.partFile(staging);
expect(part.existsSync(), isTrue);
final had = part.lengthSync();
expect(had, greaterThan(0));
expect(had, lessThan(data.length));
expect(Downloader.metaFile(staging).existsSync(), isTrue);
int? firstProgress;
final file = await make().fetch(
release: release,
staging: staging,
onProgress: (got, _) => firstProgress ??= got,
);
expect(server.log, ["GET /blob", "GET /blob bytes=$had-"]);
expect(file.readAsBytesSync(), data);
// progress carried on from where it was, not from nought
expect(firstProgress, had);
});
test("retries by itself, resuming each time", () async {
final release = server.release();
server.cutsLeft = 2;
server.cutAfter = 30 * 1024;
final file = await make(retries: 3).fetch(release: release, staging: staging);
expect(file.readAsBytesSync(), data);
expect(server.log.length, 3);
expect(server.log[0], "GET /blob");
expect(server.log[1], startsWith("GET /blob bytes="));
expect(server.log[2], startsWith("GET /blob bytes="));
});
test("a 200 that ignored the range starts the file again", () async {
final release = server.release();
server.cutsLeft = 1;
server.cutAfter = 50 * 1024;
await expectLater(make().fetch(release: release, staging: staging), throwsA(isA<UpdateError>()));
server.ignoreRange = true;
final file = await make().fetch(release: release, staging: staging);
expect(server.log.last, startsWith("GET /blob bytes="));
// not the old half with the whole file stuck on the end
expect(file.lengthSync(), data.length);
expect(file.readAsBytesSync(), data);
});
test("a hosted download follows the 302, and asks the original url again on resume", () async {
final release = server.release(path: "/hosted");
server.cutsLeft = 1;
server.cutAfter = 40 * 1024;
await expectLater(make().fetch(release: release, staging: staging), throwsA(isA<UpdateError>()));
final had = Downloader.partFile(staging).lengthSync();
// the first presigned url is dead by now. going straight back to it would 403
final file = await make().fetch(release: release, staging: staging);
expect(server.log, [
"GET /hosted",
"GET /blob",
"GET /hosted bytes=$had-",
"GET /blob bytes=$had-",
]);
expect(file.readAsBytesSync(), data);
});
test("a checksum mismatch deletes the download and fails", () async {
final release = server.release(sha256: "0" * 64);
await expectLater(
make(retries: 3).fetch(release: release, staging: staging),
throwsA(isA<UpdateError>().having((e) => e.code, "code", "checksum_mismatch")),
);
expect(Downloader.partFile(staging).existsSync(), isFalse);
expect(Downloader.metaFile(staging).existsSync(), isFalse);
expect(Downloader.finishedFile(staging, release).existsSync(), isFalse);
// and it wasnt retried, the same bytes would come back
expect(server.log.length, 1);
});
test("a stale part for another build is thrown away", () async {
staging.createSync(recursive: true);
Downloader.partFile(staging).writeAsBytesSync(noise(10 * 1024, seed: 99));
Downloader.metaFile(staging).writeAsStringSync(jsonEncode({"build": 12, "sha256": "f" * 64}));
final file = await make().fetch(release: server.release(), staging: staging);
// no Range, it didnt try to carry on from someone elses bytes
expect(server.log, ["GET /blob"]);
expect(file.readAsBytesSync(), data);
});
test("a part for the same build but another sha is stale too", () async {
staging.createSync(recursive: true);
Downloader.partFile(staging).writeAsBytesSync(noise(10 * 1024, seed: 99));
Downloader.metaFile(staging).writeAsStringSync(jsonEncode({"build": 13, "sha256": "f" * 64}));
await make().fetch(release: server.release(), staging: staging);
expect(server.log, ["GET /blob"]);
});
test("a part with no note beside it is stale", () async {
staging.createSync(recursive: true);
Downloader.partFile(staging).writeAsBytesSync(noise(10 * 1024, seed: 99));
final file = await make().fetch(release: server.release(), staging: staging);
expect(server.log, ["GET /blob"]);
expect(file.readAsBytesSync(), data);
});
test("a part that is allready whole only gets verified", () async {
final release = server.release();
staging.createSync(recursive: true);
Downloader.partFile(staging).writeAsBytesSync(data);
Downloader.metaFile(staging)
.writeAsStringSync(jsonEncode({"build": release.build, "sha256": release.asset.sha256}));
final file = await make().fetch(release: release, staging: staging);
expect(server.log, isEmpty);
expect(file.readAsBytesSync(), data);
});
test("a finished download is reused, and other builds' are swept", () async {
final release = server.release();
await make().fetch(release: release, staging: staging);
File("${staging.path}/update-9.zip").writeAsStringSync("old");
server.log.clear();
await make().fetch(release: release, staging: staging);
expect(server.log, isEmpty);
// asking for a newer one clears the old finished files out
server.data = server.data.sublist(0, 1000);
final next = server.release(build: 14);
await make().fetch(release: next, staging: staging);
expect(File("${staging.path}/update-9.zip").existsSync(), isFalse);
expect(Downloader.finishedFile(staging, release).existsSync(), isFalse);
expect(Downloader.finishedFile(staging, next).existsSync(), isTrue);
});
test("a 404 fails without retrying", () async {
await expectLater(
make(retries: 3).fetch(release: server.release(path: "/gone"), staging: staging),
throwsA(isA<UpdateError>().having((e) => e.code, "code", "http_404")),
);
expect(server.log.length, 1);
});
test("a release with no checksum is refused", () async {
await expectLater(
make().fetch(release: server.release(sha256: ""), staging: staging),
throwsA(isA<UpdateError>().having((e) => e.code, "code", "no_checksum")),
);
expect(server.log, isEmpty);
});
test("a line that goes quiet times out", () async {
// accepts the connection and then says nothing at all
final silent = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
final held = <Socket>[];
silent.listen(held.add);
final release = UpdateRelease(
label: "v13",
build: 13,
asset: UpdateAsset(
url: "http://127.0.0.1:${silent.port}/blob",
filename: "app.zip",
format: "zip",
size: data.length,
sha256: server.sha,
),
);
final d = Downloader(
httpClient: HttpClient(),
retries: 0,
quietTimeout: const Duration(milliseconds: 300),
);
await expectLater(
d.fetch(release: release, staging: staging),
throwsA(isA<UpdateError>().having((e) => e.code, "code", "download")),
);
d.close();
for (final s in held) {
s.destroy();
}
await silent.close();
});
}
+180
View File
@@ -0,0 +1,180 @@
import "dart:convert";
import "dart:io";
import "package:flutter_test/flutter_test.dart";
import "package:garage_updates/core.dart";
import "support/fake_install.dart";
import "support/fake_server.dart";
// the engine end to end against the pretend windows install: a real check, a
// real download off the fake server, the fake stub doing the installing
void main() {
late FakeServer server;
late FakeWindowsInstall fake;
late UpdateEngine engine;
final exits = <int>[];
Map<String, dynamic> answer(String status, {int build = 13, int? minimum}) => {
"status": status,
"minimum_build": minimum,
"latest": server.release(build: build).toJson(),
};
setUp(() async {
exits.clear();
server = await FakeServer.start(noise(64 * 1024));
fake = FakeWindowsInstall.create();
final found = WindowsInstaller.locate(fake.exe.path, environment: const {});
engine = UpdateEngine(
project: "proj_1",
build: 12,
installer: found.installer,
client: UpdateClient(project: "proj_1", apiBase: server.base, httpClient: HttpClient()),
downloader: Downloader(httpClient: HttpClient(), retries: 0),
arch: "x64",
exitProcess: exits.add,
);
});
tearDown(() async {
engine.close();
await server.close();
fake.dispose();
});
test("check, download, install, restart", () async {
server.updateBody = answer("available");
final order = <String>[];
engine.onBeforeRestart = () async {
// the stub has allready been run by the time the app is asked to tidy up
order.add("before restart, stub runs so far: ${fake.runs.length}");
};
final info = await engine.check();
expect(info.status, UpdateStatus.available);
expect(server.log.single, "GET /v1/updates/proj_1");
final latest = info.latest!;
expect(await engine.isDownloaded(latest), isFalse);
await engine.download(latest);
expect(await engine.isDownloaded(latest), isTrue);
final zip = "${fake.root.path}/staging/update-13.zip";
expect(File(zip).existsSync(), isTrue);
await engine.install(latest);
expect(exits, isEmpty, reason: "installing must not restart by itself");
await engine.restart(args: ["--route=/x"]);
expect(exits, [0]);
expect(order, ["before restart, stub runs so far: 1"]);
for (var i = 0; i < 100 && fake.runs.length < 2; i++) {
await Future<void>.delayed(const Duration(milliseconds: 50));
}
expect(fake.runs, [
["--garage-apply", zip, "13"],
["--route=/x"],
]);
// the stub was handed the bytes the server sent
expect(File("${fake.root.path}/app-13/unpacked-from.zip").readAsBytesSync(), server.data);
});
test("an onBeforeRestart that throws doesnt stop the restart", () async {
engine.onBeforeRestart = () => throw StateError("the agent wouldnt stop");
await engine.restart();
expect(exits, [0]);
});
test("a build that failed to start here is never offered again", () async {
// 11 is in the fake installs blocked list
server.updateBody = answer("available", build: 11);
engine = UpdateEngine(
project: "proj_1",
build: 9,
installer: engine.installer,
client: engine.client,
downloader: engine.downloader,
arch: "x64",
exitProcess: exits.add,
);
final lines = await printsOf(() async {
final first = await engine.check();
expect(first.status, UpdateStatus.current);
expect(first.latest, isNull);
expect(first.hasUpdate, isFalse);
await engine.check();
});
// said once, not every six hours for ever
expect(lines.where((l) => l.contains("failed to start on this machine")).length, 1);
});
test("a build that failed for this user on a read only install isnt offered to them again", () async {
// the stub went back to 12 for them. root still says 13 and blocks nothing
Directory("${fake.root.path}/app-13").createSync();
fake.stateFile.writeAsStringSync('{ "exe": "garage_stash.exe", "current": 13, "previous": 12, "failed_starts": 0, "blocked": [] }');
for (var i = 0; i < 4; i++) {
fake.plainLaunch(readOnly: true);
}
server.updateBody = answer("available", build: 13);
engine = UpdateEngine(
project: "proj_1",
build: 12,
installer: fake.installer(readOnly: true),
client: engine.client,
downloader: engine.downloader,
arch: "x64",
exitProcess: exits.add,
);
final info = await engine.check();
expect(info.status, UpdateStatus.current);
expect(info.hasUpdate, isFalse);
// the one after it is
server.updateBody = answer("available", build: 14);
expect((await engine.check()).latest!.build, 14);
});
test("a blocked build that is also required stays required, with nothing to install", () async {
server.updateBody = answer("required", build: 11, minimum: 11);
engine = UpdateEngine(
project: "proj_1",
build: 9,
installer: engine.installer,
client: engine.client,
downloader: engine.downloader,
arch: "x64",
);
final info = await engine.check();
expect(info.status, UpdateStatus.required);
expect(info.latest, isNull);
});
test("an answer offering our own build, or an older one, is current", () async {
server.updateBody = answer("available", build: 12);
expect((await engine.check()).status, UpdateStatus.current);
server.updateBody = answer("available", build: 5);
expect((await engine.check()).hasUpdate, isFalse);
});
test("install before download says so", () async {
await expectLater(
engine.install(server.release()),
throwsA(isA<UpdateError>().having((e) => e.code, "code", "not_downloaded")),
);
expect(fake.runs, isEmpty);
});
test("markHealthy reaches the state file", () async {
await engine.markHealthy();
expect((jsonDecode(fake.stateFile.readAsStringSync()) as Map)["failed_starts"], 0);
});
}
+296
View File
@@ -0,0 +1,296 @@
@TestOn("mac-os")
library;
import "dart:io";
import "package:flutter_test/flutter_test.dart";
import "package:garage_updates/core.dart";
import "support/fake_install.dart";
UpdateRelease _release(int build, {String format = "zip"}) => UpdateRelease(
label: "v$build",
build: build,
asset: UpdateAsset(url: "http://x/app.$format", filename: "app.$format", format: format, size: 3, sha256: "aa"),
);
void main() {
late Directory tmp;
late Directory apps;
late Directory bundle;
late MacInstaller mac;
setUp(() {
// resolved, /var is a symlink to /private/var and the paths get compared
tmp = Directory(Directory.systemTemp.createTempSync("gu_mac_").resolveSymbolicLinksSync());
apps = Directory("${tmp.path}/Applications")..createSync();
bundle = makeApp(apps, marker: "build 12");
mac = MacInstaller(
bundle: bundle,
bundleId: "net.imbenji.foo",
support: Directory("${tmp.path}/Library/Application Support/net.imbenji.foo/garage_updates"),
);
});
tearDown(() {
Process.runSync("/bin/chmod", ["-R", "u+w", tmp.path]);
tmp.deleteSync(recursive: true);
});
// a zip of build [build], sitting in staging the way the downloader leaves it
File stagedZip(int build, {String id = "net.imbenji.foo", String name = "Foo.app"}) {
final src = Directory("${tmp.path}/src-$build")..createSync();
final app = makeApp(src, marker: "build $build", id: id, name: name);
mac.staging.createSync(recursive: true);
return zipApp(app, File("${mac.staging.path}/update-$build.zip"));
}
group("finding the install", () {
test("an exe inside a bundle finds it, its id and where the state goes", () {
final found = MacInstaller.locate("${bundle.path}/Contents/MacOS/Foo", environment: {"HOME": tmp.path});
expect(found.reason, isNull);
final m = found.installer as MacInstaller;
expect(m.bundle.path, bundle.path);
expect(m.bundleId, "net.imbenji.foo");
expect(m.support.path, "${tmp.path}/Library/Application Support/net.imbenji.foo/garage_updates");
expect(m.state.file.path, endsWith("garage_updates/state.json"));
expect(m.previousApp.path, endsWith("garage_updates/previous.app"));
});
test("a helper nested in the bundle belongs to the outer app", () {
final helper = "${bundle.path}/Contents/Library/LoginItems/Helper.app/Contents/MacOS/Helper";
final found = MacInstaller.locate(helper, environment: {"HOME": tmp.path});
expect((found.installer as MacInstaller).bundle.path, bundle.path);
});
test("a bare executable is not an install", () {
final found = MacInstaller.locate("${tmp.path}/bin/dart", environment: {"HOME": tmp.path});
expect(found.installer, isNull);
expect(found.reason, contains("app bundle"));
});
test("a translocated bundle is not an install", () {
final found = MacInstaller.locate(
"/private/var/folders/xx/T/AppTranslocation/ABCD-1234/d/Foo.app/Contents/MacOS/Foo",
environment: {"HOME": tmp.path},
);
expect(found.installer, isNull);
expect(found.reason, contains("translocated"));
});
test("a build folder is not an install", () {
final found = MacInstaller.locate(
"${tmp.path}/proj/build/macos/Build/Products/Release/Foo.app/Contents/MacOS/Foo",
environment: {"HOME": tmp.path},
);
expect(found.installer, isNull);
expect(found.reason, contains("build folder"));
});
test("a bundle in a folder we cant write to is not an install", () {
Process.runSync("/bin/chmod", ["555", apps.path]);
final found = MacInstaller.locate("${bundle.path}/Contents/MacOS/Foo", environment: {"HOME": tmp.path});
expect(found.installer, isNull);
expect(found.reason, contains("can't be replaced"));
});
test("reads the bundle id out of a binary plist too", () {
final plist = "${bundle.path}/Contents/Info.plist";
final res = Process.runSync("/usr/bin/plutil", ["-convert", "binary1", plist]);
expect(res.exitCode, 0, reason: "${res.stderr}");
expect(readBundleId(bundle), "net.imbenji.foo");
});
});
group("the swap", () {
test("unpacks with ditto, keeps the old bundle as previous.app, puts the new one in place", () async {
final zip = stagedZip(13);
await mac.noteStart(12);
await mac.apply(zip, _release(13), runningBuild: 12);
expect(markerOf(bundle), "build 13");
expect(markerOf(mac.previousApp), "build 12");
// still a bundle someone could run
expect(File("${bundle.path}/Contents/MacOS/Foo").existsSync(), isTrue);
expect(readBundleId(bundle), "net.imbenji.foo");
final s = mac.state.read()!;
expect(s.current, 13);
expect(s.previous, 12);
expect(s.failedStarts, 0);
expect(zip.existsSync(), isFalse);
expect(Directory("${mac.support.path}/unpack").existsSync(), isFalse);
// and nothing else turned up beside the app
expect(apps.listSync().map((e) => e.uri.pathSegments.where((s) => s.isNotEmpty).last), ["Foo.app"]);
});
test("a second update replaces previous.app", () async {
await mac.apply(stagedZip(13), _release(13), runningBuild: 12);
await mac.apply(stagedZip(14), _release(14), runningBuild: 13);
expect(markerOf(bundle), "build 14");
expect(markerOf(mac.previousApp), "build 13");
expect(mac.state.read()!.previous, 13);
});
test("an update for some other app is refused and nothing moves", () async {
final zip = stagedZip(13, id: "com.someone.else");
await expectLater(
mac.apply(zip, _release(13), runningBuild: 12),
throwsA(isA<UpdateError>().having((e) => e.code, "code", "wrong_app")),
);
expect(markerOf(bundle), "build 12");
expect(mac.previousApp.existsSync(), isFalse);
});
test("a zip with no app in it is refused and nothing moves", () async {
final junk = Directory("${tmp.path}/junk")..createSync();
File("${junk.path}/readme.txt").writeAsStringSync("hello");
mac.staging.createSync(recursive: true);
final zip = File("${mac.staging.path}/update-13.zip");
Process.runSync("/usr/bin/ditto", ["-c", "-k", junk.path, zip.path]);
await expectLater(
mac.apply(zip, _release(13), runningBuild: 12),
throwsA(isA<UpdateError>().having((e) => e.code, "code", "no_app")),
);
expect(markerOf(bundle), "build 12");
});
test("a file that isnt a zip at all fails cleanly", () async {
mac.staging.createSync(recursive: true);
final zip = File("${mac.staging.path}/update-13.zip")..writeAsStringSync("not a zip");
await expectLater(
mac.apply(zip, _release(13), runningBuild: 12),
throwsA(isA<UpdateError>()),
);
expect(markerOf(bundle), "build 12");
});
test("the app inside can be one folder down, and named differently", () async {
final src = Directory("${tmp.path}/src/Foo 13")..createSync(recursive: true);
makeApp(src, marker: "build 13", name: "Foo Renamed.app");
mac.staging.createSync(recursive: true);
final zip = File("${mac.staging.path}/update-13.zip");
Process.runSync("/usr/bin/ditto", ["-c", "-k", "--keepParent", src.path, zip.path]);
await mac.apply(zip, _release(13), runningBuild: 12);
// it goes where the running bundle was, under the running bundles name
expect(markerOf(bundle), "build 13");
});
test("a dmg is mounted, copied out of and detached", () async {
final src = Directory("${tmp.path}/dmgsrc")..createSync();
makeApp(src, marker: "build 13");
mac.staging.createSync(recursive: true);
final dmg = File("${mac.staging.path}/update-13.dmg");
final made = Process.runSync(
"/usr/bin/hdiutil",
["create", "-srcfolder", src.path, "-volname", "Foo", "-format", "UDZO", "-ov", dmg.path],
);
expect(made.exitCode, 0, reason: "${made.stderr}");
await mac.apply(dmg, _release(13, format: "dmg"), runningBuild: 12);
expect(markerOf(bundle), "build 13");
expect(markerOf(mac.previousApp), "build 12");
expect(Directory("${mac.support.path}/mount").existsSync(), isFalse);
});
});
group("the fallback", () {
test("three starts with no markHealthy and the fourth goes back", () async {
await mac.noteStart(12);
await mac.markHealthy();
await mac.apply(stagedZip(13), _release(13), runningBuild: 12);
expect(await mac.noteStart(13), isFalse);
expect(await mac.noteStart(13), isFalse);
expect(await mac.noteStart(13), isFalse);
expect(mac.state.read()!.failedStarts, 3);
expect(markerOf(bundle), "build 13");
expect(await mac.noteStart(13), isTrue);
expect(markerOf(bundle), "build 12");
expect(mac.previousApp.existsSync(), isFalse);
expect(Directory("${mac.support.path}/failed.app").existsSync(), isFalse);
final s = mac.state.read()!;
expect(s.current, 12);
expect(s.previous, isNull);
expect(s.failedStarts, 0);
expect(s.blocked, [13]);
expect(mac.blockedBuilds(), [13]);
});
test("markHealthy stops the count", () async {
await mac.apply(stagedZip(13), _release(13), runningBuild: 12);
for (var i = 0; i < 6; i++) {
expect(await mac.noteStart(13), isFalse);
await mac.markHealthy();
}
expect(markerOf(bundle), "build 13");
expect(mac.state.read()!.failedStarts, 0);
expect(mac.state.read()!.blocked, isEmpty);
});
test("with no previous.app theres nowhere to go back to", () async {
for (var i = 0; i < 6; i++) {
expect(await mac.noteStart(12), isFalse);
}
expect(markerOf(bundle), "build 12");
expect(mac.state.read()!.blocked, isEmpty);
});
test("a build put there by hand starts its count from nought", () async {
mac.state.write(UpdateState(current: 12, previous: 9, failedStarts: 3));
// 13 was dragged into Applications, the file knows nothing about it
expect(await mac.noteStart(13), isFalse);
final s = mac.state.read()!;
expect(s.current, 13);
expect(s.failedStarts, 1);
// no previous.app on disk, so no previous
expect(s.previous, isNull);
});
test("a damaged state file is started again rather than trusted", () async {
mac.support.createSync(recursive: true);
mac.state.file.writeAsStringSync('{ "current": 1');
expect(await mac.noteStart(12), isFalse);
expect(mac.state.read()!.current, 12);
expect(mac.state.read()!.failedStarts, 1);
});
});
test("relaunch is open -n on the bundle, arguments after --args", () async {
final calls = <List<String>>[];
final m = MacInstaller(
bundle: bundle,
bundleId: "net.imbenji.foo",
support: mac.support,
run: (exe, args) async {
calls.add([exe, ...args]);
return ProcessResult(1, 0, "", "");
},
);
await m.relaunch(const []);
await m.relaunch(["--route=/settings"]);
expect(calls, [
["/usr/bin/open", "-n", bundle.path],
["/usr/bin/open", "-n", bundle.path, "--args", "--route=/settings"],
]);
});
}
+145
View File
@@ -0,0 +1,145 @@
import "dart:io";
import "package:flutter_test/flutter_test.dart";
import "package:garage_updates/core.dart";
import "support/fake_install.dart";
import "support/fake_server.dart";
// the rule: a copy the updater didnt put there is left completly alone. no
// check, no download, nothing swapped, one line on the console.
void main() {
group("detecting", () {
test("this very test run is not an install", () {
// flutter_tester off the jit, exactly the dev case
final found = detectInstall();
expect(found.installer, isNull);
expect(found.reason, isNotNull);
});
test("a debug build is never an install, wherever it sits", () {
final fake = FakeWindowsInstall.create();
addTearDown(fake.dispose);
final found = detectInstall(executable: fake.exe.path, platform: "windows", product: false);
expect(found.installer, isNull);
expect(found.reason, contains("release build"));
// the same place as a release build is one
expect(detectInstall(executable: fake.exe.path, platform: "windows", product: true).installer, isNotNull);
});
test("flutter run on windows", () {
final found = detectInstall(
executable: r"C:\src\app\build\windows\x64\runner\Debug\app.exe",
platform: "windows",
product: true,
);
expect(found.installer, isNull);
expect(found.reason, contains("app-<build>"));
});
test("a release exe run out of the build folder on windows", () {
final tmp = Directory.systemTemp.createTempSync("gu_dev_");
addTearDown(() => tmp.deleteSync(recursive: true));
final release = Directory("${tmp.path}/build/windows/x64/runner/Release")..createSync(recursive: true);
final found = detectInstall(executable: "${release.path}/app.exe", platform: "windows", product: true);
expect(found.installer, isNull);
});
test("dart run / a bare binary on the mac", () {
final found = detectInstall(
executable: "/opt/homebrew/Cellar/dart/3.8.1/libexec/bin/dart",
platform: "macos",
product: true,
environment: const {"HOME": "/Users/someone"},
);
expect(found.installer, isNull);
expect(found.reason, contains("app bundle"));
});
test("flutter run on the mac", () {
final found = detectInstall(
executable: "/Users/someone/app/build/macos/Build/Products/Debug/App.app/Contents/MacOS/App",
platform: "macos",
product: true,
environment: const {"HOME": "/Users/someone"},
);
expect(found.installer, isNull);
expect(found.reason, contains("build folder"));
});
test("a platform core has no installer for", () {
final found = detectInstall(executable: "/usr/bin/app", platform: "linux", product: true);
expect(found.installer, isNull);
expect(found.reason, contains("linux"));
});
});
group("an engine with no install", () {
late FakeServer server;
late UpdateEngine engine;
final exits = <int>[];
setUp(() async {
exits.clear();
server = await FakeServer.start(noise(1024));
server.updateBody = {"status": "required", "minimum_build": 99, "latest": server.release().toJson()};
engine = UpdateEngine(
project: "proj_1",
build: 12,
notInstalledReason: "this isn't a release build",
client: UpdateClient(project: "proj_1", apiBase: server.base, httpClient: HttpClient()),
downloader: Downloader(httpClient: HttpClient(), retries: 0),
arch: "arm64",
exitProcess: exits.add,
);
});
tearDown(() async {
engine.close();
await server.close();
});
test("says why once, and never asks the server", () async {
expect(engine.installed, isFalse);
expect(engine.notInstalledReason, "this isn't a release build");
final lines = await printsOf(() async {
expect((await engine.check()).status, UpdateStatus.unknown);
expect((await engine.check()).hasUpdate, isFalse);
expect(engine.reportIfNotInstalled(), isFalse);
});
expect(lines, ["[garage_updates] not updating this copy: this isn't a release build"]);
expect(server.log, isEmpty);
});
test("wont download, install or restart", () async {
final release = server.release();
final notInstalled = throwsA(isA<UpdateError>().having((e) => e.code, "code", "not_installed"));
await expectLater(engine.download(release), notInstalled);
await expectLater(engine.install(release), notInstalled);
await expectLater(engine.restart(), notInstalled);
expect(server.log, isEmpty);
expect(exits, isEmpty);
});
test("counting starts and markHealthy are quiet no-ops", () async {
expect(await engine.noteStart(), isFalse);
await engine.markHealthy();
expect(await engine.isDownloaded(server.release()), isFalse);
});
test("detect() off a test run gives exactly this engine", () {
final e = UpdateEngine.detect(project: "proj_1", build: 12);
addTearDown(e.close);
expect(e.installed, isFalse);
expect(e.installer, isNull);
});
});
}
+117
View File
@@ -0,0 +1,117 @@
import "package:flutter/widgets.dart";
import "package:flutter_test/flutter_test.dart";
import "package:garage_ui/garage_ui.dart";
import "package:garage_updates/garage_updates.dart";
void main() {
const branding = UpdaterBranding(
name: "Garage Stash",
logo: SizedBox(key: Key("logo")),
);
Future<SplashController> pumpSplash(WidgetTester t, {UpdaterBranding b = branding, VoidCallback? onGone}) async {
final c = SplashController();
await t.pumpWidget(UpdateSplashApp(branding: b, controller: c, onGone: onGone));
return c;
}
double? bar(WidgetTester t) => t.widget<LinearProgressIndicator>(find.byType(LinearProgressIndicator)).value;
testWidgets("the logo, the name, one status line and a bar", (t) async {
await pumpSplash(t);
expect(find.byKey(const Key("logo")), findsOneWidget);
expect(find.text("Garage Stash"), findsOneWidget);
expect(find.text("Checking for updates"), findsOneWidget);
expect(find.byType(LinearProgressIndicator), findsOneWidget);
// nothing known yet, so the bar just sweeps
expect(bar(t), isNull);
expect(find.text("Retry"), findsNothing);
expect(find.byType(Button), findsNothing);
});
testWidgets("each stage has its line", (t) async {
final c = await pumpSplash(t);
c.show(SplashStage.downloading, progress: 0);
await t.pump();
expect(find.text("Downloading update"), findsOneWidget);
expect(find.text("Checking for updates"), findsNothing);
expect(bar(t), 0);
c.progress = 0.4;
await t.pump();
expect(bar(t), 0.4);
c.show(SplashStage.installing);
await t.pump();
expect(find.text("Installing"), findsOneWidget);
expect(bar(t), isNull);
c.show(SplashStage.starting);
await t.pump();
expect(find.text("Starting"), findsOneWidget);
expect(find.text("Installing"), findsNothing);
});
testWidgets("a failure shows why and a Retry, and Retry clears it", (t) async {
final c = await pumpSplash(t);
c.show(SplashStage.downloading, progress: 0.3);
var retried = false;
c.fail("The download didn't match its checksum").then((_) => retried = true);
await t.pump();
expect(find.text("The download didn't match its checksum"), findsOneWidget);
expect(find.text("Retry"), findsOneWidget);
// the stage it failed at is still what the status line says
expect(find.text("Downloading update"), findsOneWidget);
expect(bar(t), 0.3);
expect(retried, isFalse);
await t.tap(find.text("Retry"));
await t.pump();
expect(retried, isTrue);
expect(find.text("Retry"), findsNothing);
expect(find.text("The download didn't match its checksum"), findsNothing);
});
testWidgets("a failure with nothing measured stops the bar sweeping", (t) async {
final c = await pumpSplash(t);
c.show(SplashStage.installing);
c.fail("The update could not be installed.");
await t.pump();
expect(bar(t), 0);
});
testWidgets("no logo is fine", (t) async {
await pumpSplash(t, b: const UpdaterBranding(name: "Plain"));
expect(find.text("Plain"), findsOneWidget);
expect(find.byType(LinearProgressIndicator), findsOneWidget);
});
testWidgets("its drawn with the garage theme, carbon unless the developer says otherwise", (t) async {
await pumpSplash(t);
var theme = GarageTheme.of(t.element(find.byType(UpdateSplash)));
expect(theme.colorScheme, GarageSchemes.carbon);
final light = ThemeData(colorScheme: GarageSchemes.light);
await t.pumpWidget(const SizedBox());
await pumpSplash(t, b: UpdaterBranding(name: "Light", theme: light));
theme = GarageTheme.of(t.element(find.byType(UpdateSplash)));
expect(theme.colorScheme, GarageSchemes.light);
});
testWidgets("the host app taking over is noticed", (t) async {
var gone = 0;
await pumpSplash(t, onGone: () => gone++);
expect(gone, 0);
// what the apps own runApp does to us
await t.pumpWidget(const SizedBox());
expect(gone, 1);
});
}
+159
View File
@@ -0,0 +1,159 @@
import "dart:convert";
import "dart:io";
import "package:flutter_test/flutter_test.dart";
import "package:garage_updates/core.dart";
void main() {
late Directory dir;
late StateFile state;
setUp(() {
dir = Directory.systemTemp.createTempSync("gu_state_");
state = StateFile(File("${dir.path}/garage_updates.json"));
});
tearDown(() => dir.deleteSync(recursive: true));
test("a missing file reads as null", () {
expect(state.read(), isNull);
});
test("reads what the stub writes", () {
state.file.writeAsStringSync(
'{ "exe": "garage_stash.exe", "current": 12, "previous": 9, "failed_starts": 2, "blocked": [11] }',
);
final s = state.read()!;
expect(s.exe, "garage_stash.exe");
expect(s.current, 12);
expect(s.previous, 9);
expect(s.failedStarts, 2);
expect(s.blocked, [11]);
});
test("a half written file reads as null rather than throwing", () {
state.file.writeAsStringSync('{ "exe": "garage_stash.exe", "curr');
expect(state.read(), isNull);
state.file.writeAsStringSync("");
expect(state.read(), isNull);
state.file.writeAsStringSync("[1, 2]");
expect(state.read(), isNull);
});
test("missing and mistyped fields get sane defaults", () {
state.file.writeAsStringSync('{ "current": "12", "blocked": [11, "x", 11, 10.0], "failed_starts": null }');
final s = state.read()!;
expect(s.exe, isNull);
expect(s.current, 12);
expect(s.previous, isNull);
expect(s.failedStarts, 0);
expect(s.blocked, [11, 10]);
});
test("writing keeps the keys we dont know about", () {
state.file.writeAsStringSync('{ "exe": "a.exe", "current": 12, "app_id": "net.imbenji.stash", "later": {"x": 1} }');
expect(state.update((s) => s.failedStarts = 0), isTrue);
final j = jsonDecode(state.file.readAsStringSync()) as Map;
expect(j["app_id"], "net.imbenji.stash");
expect(j["later"], {"x": 1});
expect(j["exe"], "a.exe");
expect(j["current"], 12);
expect(j["previous"], isNull);
expect(j["failed_starts"], 0);
expect(j["blocked"], isEmpty);
});
test("the write is a replace, no temp file is left", () {
state.write(UpdateState(exe: "a.exe", current: 1));
state.write(UpdateState(exe: "a.exe", current: 2, previous: 1, blocked: [3]));
expect(dir.listSync().map((e) => e.uri.pathSegments.last), ["garage_updates.json"]);
final s = state.read()!;
expect(s.current, 2);
expect(s.previous, 1);
expect(s.blocked, [3]);
});
test("update wont write over a file it couldnt read", () {
state.file.writeAsStringSync('{ "exe": "garage_stash.exe", "curr');
expect(state.update((s) => s.failedStarts = 0), isFalse);
expect(state.file.readAsStringSync(), '{ "exe": "garage_stash.exe", "curr');
});
test("update can start a file that isnt there", () {
state = StateFile(File("${dir.path}/deeper/still/state.json"));
expect(state.update((s) => s.current = 5, createIfMissing: true), isTrue);
expect(state.read()!.current, 5);
});
group("the users file", () {
late UserStateFile mine;
setUp(() => mine = UserStateFile(File("${dir.path}/local/garage_updates.json")));
test("reads what the stub writes", () {
mine.file.parent.createSync();
mine.file.writeAsStringSync('{\n "failed_starts": 2,\n "blocked": [13, 13],\n "for_current": 14,\n "run_instead": null\n}\n');
final u = mine.read()!;
expect(u.failedStarts, 2);
expect(u.blocked, [13]);
expect(u.forCurrent, 14);
expect(u.runInstead, isNull);
});
test("missing, empty and half written all read as null", () {
expect(mine.read(), isNull);
mine.file.parent.createSync();
mine.file.writeAsStringSync("");
expect(mine.read(), isNull);
mine.file.writeAsStringSync('{ "failed_starts": 2, "bl');
expect(mine.read(), isNull);
// and isnt written over
expect(mine.update((u) => u.failedStarts = 0), isFalse);
expect(mine.file.readAsStringSync(), '{ "failed_starts": 2, "bl');
});
test("update doesnt start a file unless its told to", () {
expect(mine.update((u) => u.failedStarts = 0), isFalse);
expect(mine.file.existsSync(), isFalse);
expect(mine.update((u) => u.failedStarts = 1, createIfMissing: true), isTrue);
expect(mine.file.parent.listSync().map((e) => e.uri.pathSegments.last), ["garage_updates.json"]);
expect(jsonDecode(mine.file.readAsStringSync()), {
"failed_starts": 1,
"blocked": [],
"for_current": null,
"run_instead": null,
});
});
test("the count is only good for the current it was made against", () {
final u = UserState(failedStarts: 2, blocked: [13], forCurrent: 13, runInstead: 12);
u.settleFor(13);
expect(u.failedStarts, 2);
expect(u.runInstead, 12);
u.settleFor(14);
expect(u.failedStarts, 0);
expect(u.runInstead, isNull);
expect(u.forCurrent, 14);
expect(u.blocked, [13]);
});
});
test("a write that cant happen says false", () {
// a folder where the file should be
Directory(state.file.path).createSync();
expect(state.write(UpdateState(current: 1)), isFalse);
});
}
@@ -0,0 +1,164 @@
import "dart:io";
import "package:garage_updates/core.dart";
// A pretend windows install in a temp folder. The "stub" is a shell script
// with the stubs name: it writes down the arguments it was given, and for
// --garage-apply does the bookkeeping the real one would.
const _stubScript = r'''#!/bin/sh
dir="$(cd "$(dirname "$0")" && pwd)"
printf '%s\n' "$@" >> "$dir/stub-args.txt"
echo "--" >> "$dir/stub-args.txt"
if [ "$1" = "--garage-apply" ]; then
if [ -f "$dir/stub-exit" ]; then
exit "$(cat "$dir/stub-exit")"
fi
if [ ! -f "$dir/stub-lazy" ]; then
mkdir -p "$dir/app-$3"
cp "$2" "$dir/app-$3/unpacked-from.zip"
printf '{ "exe": "garage_stash.exe", "current": %s, "previous": 12, "failed_starts": 0, "blocked": [] }' "$3" > "$dir/garage_updates.json"
fi
fi
exit 0
''';
class FakeWindowsInstall {
FakeWindowsInstall._(this.tmp);
final Directory tmp;
Directory get root => Directory("${tmp.path}/Garage Stash");
Directory get versionFolder => Directory("${root.path}/app-12");
File get stub => File("${root.path}/garage_stash.exe");
File get exe => File("${versionFolder.path}/garage_stash.exe");
File get stateFile => File("${root.path}/garage_updates.json");
File get argsFile => File("${root.path}/stub-args.txt");
static FakeWindowsInstall create({String? state}) {
final f = FakeWindowsInstall._(Directory.systemTemp.createTempSync("gu_win_"));
f.versionFolder.createSync(recursive: true);
f.exe.writeAsStringSync("the real app, build 12");
File("${f.versionFolder.path}/stash-agent.exe").writeAsStringSync("the agent");
f.stub.writeAsStringSync(_stubScript);
Process.runSync("/bin/chmod", ["+x", f.stub.path]);
f.stateFile.writeAsStringSync(
state ?? '{ "exe": "garage_stash.exe", "current": 12, "previous": 9, "failed_starts": 1, "blocked": [11] }',
);
return f;
}
/// what LOCALAPPDATA is for an installer made by [installer]
Directory get local => Directory("${tmp.path}/Local");
File get userStateFile => File("${local.path}/Garage Stash/garage_updates.json");
/// `readOnly` is an install in Program Files. Nothing is chmodded, the
/// installer is just told it cant write, and [plainLaunch] behaves the same
WindowsInstaller installer({bool readOnly = false}) => WindowsInstaller(
root: root,
stub: stub,
runningFolderBuild: 12,
environment: {"LOCALAPPDATA": local.path},
rootWritable: () => !readOnly,
);
/// The stub being started with no flags, as far as the counting goes: the
/// same sums garage_stub.cpp does, in root when it can write there and in
/// the users own file when it cant. Returns the build it would start.
int plainLaunch({bool readOnly = false}) {
final state = StateFile(stateFile);
final s = state.read()!;
bool there(int? build) => build != null && Directory("${root.path}/app-$build").existsSync();
if (!readOnly) {
if (s.failedStarts >= 3 && there(s.previous)) {
if (!s.blocked.contains(s.current)) s.blocked.add(s.current!);
s.current = s.previous;
s.previous = null;
s.failedStarts = 0;
}
s.failedStarts++;
state.write(s);
return s.current!;
}
final mine = UserStateFile(userStateFile);
final u = mine.read() ?? UserState();
u.settleFor(s.current);
if (u.runInstead != null) {
if (u.runInstead != s.current && there(u.runInstead)) return u.runInstead!;
u.runInstead = null;
u.failedStarts = 0;
}
var run = s.current!;
if (u.failedStarts >= 3 && there(s.previous) && s.previous != s.current && !u.blocked.contains(s.previous)) {
if (!u.blocked.contains(s.current)) u.blocked.add(s.current!);
u.runInstead = s.previous;
u.failedStarts = 0;
run = s.previous!;
}
if (run == s.current) u.failedStarts++;
mine.write(u);
return run;
}
/// every run of the stub, as the list of arguments it got
List<List<String>> get runs {
if (!argsFile.existsSync()) return [];
final out = <List<String>>[];
var cur = <String>[];
for (final line in argsFile.readAsLinesSync()) {
if (line == "--") {
out.add(cur);
cur = <String>[];
} else {
cur.add(line);
}
}
return out;
}
void dispose() {
// a test may have made the root read only
Process.runSync("/bin/chmod", ["-R", "u+w", tmp.path]);
tmp.deleteSync(recursive: true);
}
}
/// A pretend mac app. `Foo.app/Contents/{Info.plist, MacOS/Foo}` with a
/// marker file so a test can tell which build is sitting where.
Directory makeApp(Directory parent, {String name = "Foo.app", String id = "net.imbenji.foo", required String marker}) {
final app = Directory("${parent.path}/$name");
Directory("${app.path}/Contents/MacOS").createSync(recursive: true);
Directory("${app.path}/Contents/Resources").createSync(recursive: true);
File("${app.path}/Contents/Info.plist").writeAsStringSync('''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleExecutable</key>
<string>Foo</string>
<key>CFBundleIdentifier</key>
<string>$id</string>
</dict>
</plist>
''');
File("${app.path}/Contents/MacOS/Foo").writeAsStringSync("#!/bin/sh\necho $marker\n");
File("${app.path}/Contents/Resources/marker.txt").writeAsStringSync(marker);
return app;
}
String markerOf(Directory app) => File("${app.path}/Contents/Resources/marker.txt").readAsStringSync();
/// zips [app] the way a release would be, with the .app at the top
File zipApp(Directory app, File to) {
final res = Process.runSync("/usr/bin/ditto", ["-c", "-k", "--keepParent", app.path, to.path]);
if (res.exitCode != 0) throw StateError("ditto couldnt zip ${app.path}: ${res.stderr}");
return to;
}
@@ -0,0 +1,154 @@
import "dart:async";
import "dart:convert";
import "dart:io";
import "dart:typed_data";
import "package:crypto/crypto.dart";
import "package:garage_updates/core.dart";
/// A file server on loopback that can be told to misbehave.
class FakeServer {
FakeServer._(this._server, this.data);
final HttpServer _server;
Uint8List data;
/// "GET /blob bytes=100-" for every request, in order
final List<String> log = [];
/// send a plain 200 with the whole file whatever Range says
bool ignoreRange = false;
/// how many of the next downloads to cut dead, and after how many bytes
int cutsLeft = 0;
int cutAfter = 0;
/// the json `/v1/updates/<pid>` answers with, and the status it uses
Object? updateBody;
int updateStatus = 200;
/// a /blob request without this sig gets a 403, like an expired presign
String? wantSig;
int _sig = 0;
String get base => "http://127.0.0.1:${_server.port}";
static Future<FakeServer> start(List<int> data) async {
final s = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
final fake = FakeServer._(s, Uint8List.fromList(data));
s.listen(fake._handle);
return fake;
}
Future<void> close() => _server.close(force: true);
String get sha => sha256.convert(data).toString();
UpdateRelease release({int build = 13, String path = "/blob", String format = "zip", String? sha256}) {
return UpdateRelease(
label: "v$build",
build: build,
notes: "notes for $build",
asset: UpdateAsset(
url: "$base$path",
filename: "app.$format",
format: format,
size: data.length,
sha256: sha256 ?? sha,
),
);
}
Future<void> _handle(HttpRequest req) async {
final range = req.headers.value(HttpHeaders.rangeHeader);
log.add("${req.method} ${req.uri.path}${range == null ? "" : " $range"}");
if (req.uri.path.startsWith("/v1/updates/")) {
req.response.statusCode = updateStatus;
req.response.headers.contentType = ContentType.json;
final body = updateBody;
req.response.write(body is String ? body : jsonEncode(body));
await req.response.close();
return;
}
if (req.uri.path == "/hosted") {
// a fresh "presigned" url every time, the old ones stop working
wantSig = "s${++_sig}";
req.response.statusCode = HttpStatus.found;
req.response.headers.set(HttpHeaders.locationHeader, "/blob?sig=$wantSig");
await req.response.close();
return;
}
if (req.uri.path == "/gone") {
req.response.statusCode = HttpStatus.notFound;
await req.response.close();
return;
}
if (wantSig != null && req.uri.queryParameters["sig"] != wantSig) {
req.response.statusCode = HttpStatus.forbidden;
await req.response.close();
return;
}
var start = 0;
var status = "200 OK";
final extra = <String>[];
if (range != null && !ignoreRange) {
start = int.parse(RegExp(r"bytes=(\d+)-").firstMatch(range)!.group(1)!);
if (start >= data.length) {
req.response.statusCode = HttpStatus.requestedRangeNotSatisfiable;
await req.response.close();
return;
}
status = "206 Partial Content";
extra.add("Content-Range: bytes $start-${data.length - 1}/${data.length}");
}
final body = Uint8List.sublistView(data, start);
// written by hand on the raw socket so it can be dropped mid body
final socket = await req.response.detachSocket(writeHeaders: false);
socket.write("HTTP/1.1 $status\r\n"
"Content-Length: ${body.length}\r\n"
"${extra.map((h) => "$h\r\n").join()}"
"Connection: close\r\n\r\n");
if (cutsLeft > 0) {
cutsLeft--;
socket.add(Uint8List.sublistView(body, 0, cutAfter.clamp(0, body.length)));
await socket.flush();
socket.destroy();
return;
}
socket.add(body);
await socket.flush();
await socket.close();
}
}
/// some bytes that arent all the same
List<int> noise(int length, {int seed = 7}) {
var x = seed;
return List<int>.generate(length, (_) {
x = (x * 1103515245 + 12345) & 0x7fffffff;
return x & 0xff;
});
}
/// runs [body] and hands back everything it printed
Future<List<String>> printsOf(Future<void> Function() body) async {
final lines = <String>[];
await runZonedPrints(body, lines);
return lines;
}
Future<void> runZonedPrints(Future<void> Function() body, List<String> into) {
return runZoned(
body,
zoneSpecification: ZoneSpecification(print: (self, parent, zone, line) => into.add(line)),
);
}
+415
View File
@@ -0,0 +1,415 @@
import "dart:async";
import "package:flutter/foundation.dart";
import "package:flutter/widgets.dart";
import "package:flutter_test/flutter_test.dart";
import "package:garage_ui/garage_ui.dart" show LinearProgressIndicator;
import "package:garage_updates/garage_updates.dart";
// GarageUpdater.launch against a driver that does whatever the test says
class FakeDriver implements UpdateDriver {
FakeDriver({this.installed = true});
@override
bool installed;
@override
String? get notInstalledReason => installed ? null : "this isn't a release build";
@override
FutureOr<void> Function()? onBeforeRestart;
final calls = <String>[];
/// what check() answers. a Completer to answer late, an error to throw
Object? answer;
bool startsKeepFailing = false;
Object? downloadError;
Object? installError;
Completer<void>? downloadGate;
@override
Future<bool> noteStart() async {
calls.add("noteStart");
return startsKeepFailing;
}
@override
Future<UpdateInfo> check() async {
calls.add("check");
final a = answer;
if (a is Completer<UpdateInfo>) return a.future;
if (a is UpdateInfo) return a;
throw a ?? StateError("no answer set");
}
@override
Future<void> download(UpdateRelease release, {DownloadProgress? onProgress}) async {
calls.add("download ${release.build}");
onProgress?.call(50, 100);
await downloadGate?.future;
final e = downloadError;
if (e != null) throw e;
onProgress?.call(100, 100);
}
@override
Future<void> install(UpdateRelease release) async {
calls.add("install ${release.build}");
final e = installError;
if (e != null) throw e;
}
@override
Future<void> restart({List<String> args = const []}) async {
await onBeforeRestart?.call();
calls.add("restart ${args.join(" ")}".trim());
}
@override
Future<void> markHealthy() async => calls.add("markHealthy");
}
const _release = UpdateRelease(
label: "v13",
build: 13,
notes: "Fixed the thing",
asset: UpdateAsset(url: "http://x/app.zip", filename: "app.zip", format: "zip", size: 100, sha256: "aa"),
);
const _current = UpdateInfo(status: UpdateStatus.current);
const _available = UpdateInfo(status: UpdateStatus.available, latest: _release);
const _required = UpdateInfo(status: UpdateStatus.required, minimumBuild: 13, latest: _release);
// the updater leaves a 6 hourly timer running, as it should. flutter_test
// counts timers the moment the body returns, before any tearDown, so the
// tidying has to happen in here
void updaterTest(
String name,
Future<void> Function(WidgetTester t) body, {
TargetPlatform platform = TargetPlatform.macOS,
}) {
testWidgets(name, (t) async {
GarageUpdater.reset();
// a flutter test says its android unless told otherwise
debugDefaultTargetPlatformOverride = platform;
try {
await body(t);
} finally {
// take the splash down first, that schedules the markHealthy timer
await t.pumpWidget(const SizedBox());
await t.pump();
GarageUpdater.reset();
debugDefaultTargetPlatformOverride = null;
}
});
}
void main() {
// starts the updater the way launch() does, with the splash going to the
// tester instead of runApp
({Future<void> done, bool Function() finished, Widget? Function() splash}) start(
FakeDriver driver, {
UpdateMode mode = UpdateMode.silent,
List<String> args = const ["--route=/x"],
}) {
Widget? shown;
var finished = false;
final done = GarageUpdater.instance
.start(
args: args,
project: "proj_1",
build: 12,
label: "v12",
branding: const UpdaterBranding(name: "Garage Stash"),
mode: mode,
driver: driver,
show: (w) => shown = w,
)
.then((_) => finished = true);
return (done: done, finished: () => finished, splash: () => shown);
}
updaterTest("up to date: the splash shows, then the app carries on", (t) async {
final d = FakeDriver()..answer = _current;
final run = start(d);
await t.pump();
expect(run.splash(), isA<UpdateSplashApp>());
await t.pumpWidget(run.splash()!);
await t.pump();
expect(run.finished(), isTrue);
expect(find.text("Starting"), findsOneWidget);
expect(d.calls, ["noteStart", "check"]);
expect(GarageUpdater.instance.ready.value, isNull);
expect(GarageUpdater.instance.label, "v12");
});
updaterTest("no answer in 2 seconds: the app starts, and the late answer is dealt with behind it", (t) async {
final late = Completer<UpdateInfo>();
final d = FakeDriver()..answer = late;
final run = start(d);
await t.pump();
await t.pumpWidget(run.splash()!);
await t.pump(const Duration(milliseconds: 1900));
expect(run.finished(), isFalse);
expect(find.text("Checking for updates"), findsOneWidget);
await t.pump(const Duration(milliseconds: 200));
expect(run.finished(), isTrue);
expect(d.calls, ["noteStart", "check"]);
final heard = <UpdateInfo>[];
GarageUpdater.instance.readyStream.listen(heard.add);
// the server finally answers, the app is long since up
late.complete(_available);
await t.pump();
await t.pump();
expect(d.calls, ["noteStart", "check", "download 13"]);
expect(GarageUpdater.instance.ready.value, same(_available));
expect(heard, [_available]);
expect(GarageUpdater.instance.notes, "Fixed the thing");
// downloaded, not installed. thats the apps call now
expect(d.calls.where((c) => c.startsWith("install")), isEmpty);
});
updaterTest("a check that fails lets the app start", (t) async {
final d = FakeDriver()..answer = UpdateError("network", "Couldn't reach the update server");
final run = start(d);
await t.pump();
await t.pumpWidget(run.splash()!);
await t.pump();
expect(run.finished(), isTrue);
expect(find.text("Retry"), findsNothing);
});
updaterTest("silent + available: downloaded, installed and restarted behind the splash", (t) async {
final gate = Completer<void>();
final d = FakeDriver()
..answer = _available
..downloadGate = gate;
final stopped = <String>[];
GarageUpdater.instance.onBeforeRestart = () => stopped.add("agent stopped");
final run = start(d);
await t.pump();
await t.pumpWidget(run.splash()!);
await t.pump();
await t.pump();
expect(find.text("Downloading update"), findsOneWidget);
expect(t.widget<LinearProgressIndicator>(find.byType(LinearProgressIndicator)).value, 0.5);
expect(run.finished(), isFalse);
gate.complete();
await t.pump();
await t.pump();
expect(d.calls, ["noteStart", "check", "download 13", "install 13", "restart --route=/x"]);
expect(stopped, ["agent stopped"]);
});
updaterTest("silent + available that fails: the old build starts anyway", (t) async {
final d = FakeDriver()
..answer = _available
..installError = UpdateError("install_failed", "The update could not be installed (3)");
final run = start(d);
await t.pump();
await t.pumpWidget(run.splash()!);
await t.pump();
await t.pump();
expect(run.finished(), isTrue);
expect(find.text("Retry"), findsNothing);
expect(d.calls.where((c) => c.startsWith("restart")), isEmpty);
});
updaterTest("prompt + available: nothing is installed, ready fires, restartToUpdate applies it", (t) async {
final d = FakeDriver()..answer = _available;
final run = start(d, mode: UpdateMode.prompt);
await t.pump();
await t.pumpWidget(run.splash()!);
await t.pump();
await t.pump();
expect(run.finished(), isTrue);
expect(d.calls, ["noteStart", "check", "download 13"]);
expect(GarageUpdater.instance.ready.value?.latest?.build, 13);
await GarageUpdater.instance.restartToUpdate();
expect(d.calls, ["noteStart", "check", "download 13", "install 13", "restart --route=/x"]);
});
updaterTest("android never installs at launch unless it has to, its installer always asks", (t) async {
final d = FakeDriver()..answer = _available;
final run = start(d);
await t.pump();
await t.pumpWidget(run.splash()!);
await t.pump();
await t.pump();
expect(run.finished(), isTrue);
expect(d.calls, ["noteStart", "check", "download 13"]);
expect(GarageUpdater.instance.ready.value?.latest?.build, 13);
}, platform: TargetPlatform.android);
updaterTest("required: the app is kept out, a failure offers Retry, and Retry goes again", (t) async {
final d = FakeDriver()
..answer = _required
..downloadError = UpdateError("checksum_mismatch", "The download didn't match its checksum");
final run = start(d);
await t.pump();
await t.pumpWidget(run.splash()!);
await t.pump();
await t.pump();
expect(run.finished(), isFalse);
expect(find.text("The download didn't match its checksum"), findsOneWidget);
expect(find.text("Retry"), findsOneWidget);
// still out, however long its left
await t.pump(const Duration(minutes: 10));
expect(run.finished(), isFalse);
expect(d.calls.where((c) => c.startsWith("install")), isEmpty);
d.downloadError = null;
await t.tap(find.text("Retry"));
await t.pump();
await t.pump();
await t.pump();
expect(d.calls, [
"noteStart",
"check",
"download 13",
"check",
"download 13",
"install 13",
"restart --route=/x",
]);
// a real restart ends the process. the fake comes back, which is androids
// case: the system installer is up and the app still must not start
expect(run.finished(), isFalse);
expect(find.text("Install the update to continue."), findsOneWidget);
});
updaterTest("required is required in prompt mode too", (t) async {
final d = FakeDriver()..answer = _required;
final run = start(d, mode: UpdateMode.prompt);
await t.pump();
await t.pumpWidget(run.splash()!);
await t.pump();
await t.pump();
expect(d.calls, contains("install 13"));
expect(run.finished(), isFalse);
});
updaterTest("required with nothing installable says so and keeps the app out", (t) async {
final d = FakeDriver()..answer = const UpdateInfo(status: UpdateStatus.required, minimumBuild: 13);
final run = start(d);
await t.pump();
await t.pumpWidget(run.splash()!);
await t.pump();
expect(run.finished(), isFalse);
expect(find.text("Retry"), findsOneWidget);
expect(d.calls.where((c) => c.startsWith("download")), isEmpty);
});
updaterTest("not installed in the layout: no splash, no check, nothing", (t) async {
final d = FakeDriver(installed: false);
final run = start(d);
await t.pump();
expect(run.finished(), isTrue);
expect(run.splash(), isNull);
expect(d.calls, isEmpty);
// and the rest of the surface is safe to call
await GarageUpdater.instance.markHealthy();
await GarageUpdater.instance.restartToUpdate();
expect(await GarageUpdater.instance.checkNow(), isNull);
expect(d.calls, isEmpty);
expect(GarageUpdater.instance.ready.value, isNull);
expect(GarageUpdater.instance.notes, isNull);
});
updaterTest("a start that put the old build back restarts before anything else", (t) async {
final d = FakeDriver()
..startsKeepFailing = true
..answer = _current;
start(d);
await t.pump();
expect(d.calls.take(2), ["noteStart", "restart --route=/x"]);
});
updaterTest("markHealthy is called a few seconds after the host apps first frame", (t) async {
final d = FakeDriver()..answer = _current;
final run = start(d);
await t.pump();
await t.pumpWidget(run.splash()!);
await t.pump();
expect(run.finished(), isTrue);
// sat on the splash, the app hasnt drawn anything of its own yet
await t.pump(const Duration(seconds: 10));
expect(d.calls, isNot(contains("markHealthy")));
await t.pumpWidget(const SizedBox(key: Key("the host app")));
await t.pump(const Duration(seconds: 2));
expect(d.calls, isNot(contains("markHealthy")));
await t.pump(const Duration(seconds: 2));
expect(d.calls, contains("markHealthy"));
});
updaterTest("checks again every 6 hours while the app runs", (t) async {
final d = FakeDriver()..answer = _current;
final run = start(d);
await t.pump();
await t.pumpWidget(run.splash()!);
await t.pump();
await t.pumpWidget(const SizedBox());
expect(d.calls.where((c) => c == "check").length, 1);
await t.pump(const Duration(hours: 5, minutes: 59));
expect(d.calls.where((c) => c == "check").length, 1);
d.answer = _available;
await t.pump(const Duration(minutes: 2));
await t.pump();
expect(d.calls.where((c) => c == "check").length, 2);
expect(d.calls, contains("download 13"));
expect(GarageUpdater.instance.ready.value?.latest?.build, 13);
// the same build again in another 6 hours isnt fetched twice
await t.pump(const Duration(hours: 6, minutes: 1));
await t.pump();
expect(d.calls.where((c) => c == "download 13").length, 1);
});
updaterTest("launch twice is ignored the second time", (t) async {
final d = FakeDriver()..answer = _current;
final run = start(d);
await t.pump();
await t.pumpWidget(run.splash()!);
await t.pump();
final again = start(FakeDriver()..answer = _required);
await t.pump();
expect(again.finished(), isTrue);
expect(again.splash(), isNull);
});
}
@@ -0,0 +1,440 @@
import "dart:convert";
import "dart:io";
import "package:flutter_test/flutter_test.dart";
import "package:garage_updates/core.dart";
import "support/fake_install.dart";
UpdateRelease _release(int build, {String format = "zip"}) => UpdateRelease(
label: "v$build",
build: build,
asset: UpdateAsset(url: "http://x/app.$format", filename: "app.$format", format: format, size: 3, sha256: "aa"),
);
void main() {
late FakeWindowsInstall fake;
setUp(() => fake = FakeWindowsInstall.create());
tearDown(() => fake.dispose());
WindowsInstaller locate([String? exe]) {
final found = WindowsInstaller.locate(exe ?? fake.exe.path, environment: const {});
expect(found.reason, isNull);
return found.installer as WindowsInstaller;
}
File zipIn(Directory staging) {
staging.createSync(recursive: true);
return File("${staging.path}/update-13.zip")..writeAsStringSync("zip");
}
group("finding the install", () {
test("an exe inside app-<build> finds the root, the stub and the build", () {
final w = locate();
expect(w.root.path, fake.root.path);
expect(w.stub.path, fake.stub.path);
expect(w.runningFolderBuild, 12);
expect(w.rootWritable, isTrue);
expect(w.staging.path, "${fake.root.path}/staging");
expect(w.blockedBuilds(), [11]);
// the writable probe cleaned up after itself
expect(File("${fake.root.path}/.garage_updates_probe").existsSync(), isFalse);
});
test("a helper exe finds the stub by the name in the state file", () {
final w = locate("${fake.versionFolder.path}/stash-agent.exe");
expect(w.stub.path, fake.stub.path);
});
test("the stub is still found when the state file is half written", () {
fake.stateFile.writeAsStringSync('{ "exe": "garage_st');
final w = locate();
expect(w.stub.path, fake.stub.path);
expect(w.blockedBuilds(), isEmpty);
});
test("a folder that isnt app-<build> is not an install", () {
final dev = Directory("${fake.tmp.path}/build/windows/x64/runner/Release")..createSync(recursive: true);
final found = WindowsInstaller.locate("${dev.path}/garage_stash.exe");
expect(found.installer, isNull);
expect(found.reason, contains("app-<build>"));
});
test("app-<build> with no state file beside it is not an install", () {
fake.stateFile.deleteSync();
final found = WindowsInstaller.locate(fake.exe.path);
expect(found.installer, isNull);
expect(found.reason, contains("garage_updates.json"));
});
test("an old stub left in root by an update isnt taken for the stub", () {
// nothing to go on but whats in the folder: the state wont read and
// the stub isnt named after the exe that is asking
fake.stub.renameSync("${fake.root.path}/launcher.exe");
File("${fake.root.path}/launcher.exe.old").writeAsStringSync("the stub before this one");
File("${fake.root.path}/launcher.exe.old-412-99").writeAsStringSync("and one that wouldnt delete");
fake.stateFile.writeAsStringSync('{ "exe": "garage_st');
final w = locate("${fake.versionFolder.path}/stash-agent.exe");
expect(w.stub.path, "${fake.root.path}/launcher.exe");
});
test("no stub, not an install", () {
fake.stub.deleteSync();
final found = WindowsInstaller.locate(fake.exe.path);
expect(found.installer, isNull);
expect(found.reason, contains("stub"));
});
});
group("applying", () {
test("runs the stub directly when the root is writable", () async {
final w = locate();
final zip = zipIn(w.staging);
await w.apply(zip, _release(13), runningBuild: 12);
expect(fake.runs, [
["--garage-apply", zip.path, "13"],
]);
expect(Directory("${fake.root.path}/app-13").existsSync(), isTrue);
expect(w.state.read()!.current, 13);
// the zip is spent
expect(zip.existsSync(), isFalse);
});
test("a path with spaces reaches the stub as one argument", () async {
final w = locate();
// the root is "Garage Stash", so the zip path has a space in it allready
final zip = zipIn(w.staging);
expect(zip.path, contains(" "));
await w.apply(zip, _release(13), runningBuild: 12);
expect(fake.runs.single[1], zip.path);
});
test("a stub that exits non zero fails the install and keeps the zip", () async {
File("${fake.root.path}/stub-exit").writeAsStringSync("3");
final w = locate();
final zip = zipIn(w.staging);
await expectLater(
w.apply(zip, _release(13), runningBuild: 12),
throwsA(isA<UpdateError>().having((e) => e.code, "code", "install_failed")),
);
expect(zip.existsSync(), isTrue);
expect(w.state.read()!.current, 12);
});
test("a stub that says 0 without moving current is still a failure", () async {
File("${fake.root.path}/stub-lazy").writeAsStringSync("");
final w = locate();
await expectLater(
w.apply(zipIn(w.staging), _release(13), runningBuild: 12),
throwsA(isA<UpdateError>().having((e) => e.code, "code", "install_failed")),
);
});
test("anything but a zip is refused before the stub is run", () async {
final w = locate();
await expectLater(
w.apply(zipIn(w.staging), _release(13, format: "dmg"), runningBuild: 12),
throwsA(isA<UpdateError>().having((e) => e.code, "code", "format")),
);
expect(fake.runs, isEmpty);
});
});
group("a root we cant write to", () {
test("a read only root is noticed", () {
Process.runSync("/bin/chmod", ["555", fake.root.path]);
final w = locate();
expect(w.rootWritable, isFalse);
});
test("staging moves to LOCALAPPDATA, under app_id when the state has one", () {
final local = "${fake.tmp.path}/Local";
var w = WindowsInstaller(
root: fake.root,
stub: fake.stub,
runningFolderBuild: 12,
environment: {"LOCALAPPDATA": local},
rootWritable: () => false,
);
// no app_id in the file, so the folders name
expect(w.staging.path, "$local/Garage Stash/staging");
fake.stateFile.writeAsStringSync('{ "exe": "garage_stash.exe", "current": 12, "app_id": "net.imbenji.stash" }');
w = WindowsInstaller(
root: fake.root,
stub: fake.stub,
runningFolderBuild: 12,
environment: {"LOCALAPPDATA": local},
rootWritable: () => false,
);
expect(w.staging.path, "$local/net.imbenji.stash/staging");
});
test("the stub is run elevated, through powershell", () async {
String? ranExe;
List<String>? ranArgs;
final w = WindowsInstaller(
root: fake.root,
stub: fake.stub,
runningFolderBuild: 12,
environment: {"LOCALAPPDATA": "${fake.tmp.path}/Local"},
rootWritable: () => false,
run: (exe, args) async {
ranExe = exe;
ranArgs = args;
// the elevated stub did its job
fake.stateFile.writeAsStringSync(jsonEncode({"exe": "garage_stash.exe", "current": 13, "previous": 12}));
return ProcessResult(1, 0, "", "");
},
);
final zip = zipIn(w.staging);
await w.apply(zip, _release(13), runningBuild: 12);
expect(ranExe, "powershell");
expect(ranArgs!.sublist(0, ranArgs!.length - 1),
["-NoProfile", "-ExecutionPolicy", "Bypass", "-WindowStyle", "Hidden", "-Command"]);
final script = ranArgs!.last;
expect(script, contains("Start-Process -FilePath '${fake.stub.path}'"));
expect(script, contains("-Verb RunAs"));
expect(script, contains("-Wait"));
// the zip path has a space, so its quoted inside the argument list
expect(script, contains("-ArgumentList '--garage-apply \"${zip.path}\" 13'"));
expect(script, contains("exit \$p.ExitCode"));
// the stub itself was never run unelevated
expect(fake.runs, isEmpty);
});
test("a UAC prompt turned down is its own error", () async {
final w = WindowsInstaller(
root: fake.root,
stub: fake.stub,
runningFolderBuild: 12,
environment: const {},
rootWritable: () => false,
run: (exe, args) async => ProcessResult(1, kElevationRefused, "", "The operation was canceled by the user."),
);
await expectLater(
w.apply(zipIn(Directory("${fake.tmp.path}/st")), _release(13), runningBuild: 12),
throwsA(isA<UpdateError>().having((e) => e.code, "code", "elevation_refused")),
);
});
});
group("starts counted for the user", () {
const state13 = '{ "exe": "garage_stash.exe", "current": 13, "previous": 12, "failed_starts": 0, "blocked": [11] }';
Map userJson() => jsonDecode(fake.userStateFile.readAsStringSync()) as Map;
setUp(() {
Directory("${fake.root.path}/app-13").createSync();
fake.stateFile.writeAsStringSync(state13);
});
test("the count goes in the users file, root is left as it was", () {
final w = fake.installer(readOnly: true);
expect(w.userState!.file.path, fake.userStateFile.path);
expect(fake.plainLaunch(readOnly: true), 13);
expect(fake.plainLaunch(readOnly: true), 13);
expect(userJson(), {"failed_starts": 2, "blocked": [], "for_current": 13, "run_instead": null});
expect(fake.stateFile.readAsStringSync(), state13);
expect(w.startsBuild, 13);
expect(w.blockedBuilds(), [11]);
});
test("the users file goes under app_id when the state has one", () {
fake.stateFile.writeAsStringSync('{ "exe": "garage_stash.exe", "current": 13, "app_id": "net.imbenji.stash" }');
final w = fake.installer(readOnly: true);
expect(w.userState!.file.path, "${fake.local.path}/net.imbenji.stash/garage_updates.json");
// one that couldnt be a folder name is the same as none, as in the stub
fake.stateFile.writeAsStringSync('{ "exe": "garage_stash.exe", "current": 13, "app_id": "net:imbenji" }');
expect(w.userState!.file.path, fake.userStateFile.path);
});
test("markHealthy zeroes the users count and nothing else", () async {
final w = fake.installer(readOnly: true);
fake.plainLaunch(readOnly: true);
fake.plainLaunch(readOnly: true);
await w.markHealthy();
expect(userJson(), {"failed_starts": 0, "blocked": [], "for_current": 13, "run_instead": null});
expect(fake.stateFile.readAsStringSync(), state13);
expect(fake.local.listSync(recursive: true).whereType<File>().map((f) => f.path), [fake.userStateFile.path]);
});
test("three starts that never got healthy: blocked for the user, the previous build runs instead", () {
final w = fake.installer(readOnly: true);
for (var i = 0; i < 3; i++) {
expect(fake.plainLaunch(readOnly: true), 13);
}
expect(w.startsBuild, 13);
expect(fake.plainLaunch(readOnly: true), 12);
expect(userJson(), {
"failed_starts": 0,
"blocked": [13],
"for_current": 13,
"run_instead": 12,
});
// and it stays there
expect(fake.plainLaunch(readOnly: true), 12);
expect(w.startsBuild, 12);
expect(w.blockedBuilds(), [11, 13]);
// nobody else on the machine was moved
expect(fake.stateFile.readAsStringSync(), state13);
});
test("a build to run instead that has gone is not what we say is started", () {
fake.userStateFile.parent.createSync(recursive: true);
fake.userStateFile.writeAsStringSync('{ "failed_starts": 0, "blocked": [13], "for_current": 13, "run_instead": 10 }');
final w = fake.installer(readOnly: true);
expect(w.startsBuild, 13);
expect(fake.plainLaunch(readOnly: true), 13);
expect(userJson()["run_instead"], isNull);
});
test("an update going in starts the count again, what was blocked stays", () {
final w = fake.installer(readOnly: true);
for (var i = 0; i < 4; i++) {
fake.plainLaunch(readOnly: true);
}
expect(w.startsBuild, 12);
// the elevated apply
Directory("${fake.root.path}/app-14").createSync();
fake.stateFile.writeAsStringSync('{ "exe": "garage_stash.exe", "current": 14, "previous": 13, "failed_starts": 0, "blocked": [] }');
// before the stub has even been started again
expect(w.startsBuild, 14);
expect(w.blockedBuilds(), [13]);
expect(fake.plainLaunch(readOnly: true), 14);
expect(userJson(), {"failed_starts": 1, "blocked": [13], "for_current": 14, "run_instead": null});
});
test("a previous that allready failed the user is not gone back to", () {
fake.userStateFile.parent.createSync(recursive: true);
fake.userStateFile.writeAsStringSync('{ "failed_starts": 3, "blocked": [12], "for_current": 13, "run_instead": null }');
expect(fake.plainLaunch(readOnly: true), 13);
expect(userJson()["run_instead"], isNull);
expect(userJson()["blocked"], [12]);
});
test("a users file that is half written is read as none", () async {
fake.userStateFile.parent.createSync(recursive: true);
fake.userStateFile.writeAsStringSync('{ "failed_sta');
final w = fake.installer(readOnly: true);
expect(w.blockedBuilds(), [11]);
expect(w.startsBuild, 13);
await w.markHealthy();
expect(fake.userStateFile.readAsStringSync(), '{ "failed_sta');
});
test("a root that can be written never gets a users file", () async {
final w = fake.installer();
expect(fake.plainLaunch(), 13);
expect(fake.plainLaunch(), 13);
expect(w.state.read()!.failedStarts, 2);
expect(w.blockedBuilds(), [11]);
expect(w.startsBuild, 13);
await w.markHealthy();
expect(w.state.read()!.failedStarts, 0);
expect(fake.userStateFile.existsSync(), isFalse);
expect(fake.local.existsSync(), isFalse);
// and falling back there is still the root file changing
for (var i = 0; i < 3; i++) {
fake.plainLaunch();
}
expect(fake.plainLaunch(), 12);
final s = w.state.read()!;
expect(s.current, 12);
expect(s.blocked, [11, 13]);
expect(w.startsBuild, 12);
expect(fake.local.existsSync(), isFalse);
});
});
group("quoting", () {
test("windows arguments", () {
expect(windowsQuoteArg("--garage-apply"), "--garage-apply");
expect(windowsQuoteArg("13"), "13");
expect(windowsQuoteArg(""), '""');
expect(windowsQuoteArg(r"C:\Program Files\App\x.zip"), r'"C:\Program Files\App\x.zip"');
// a trailing backslash would otherwise eat the closing quote
expect(windowsQuoteArg(r"C:\My Apps\"), r'"C:\My Apps\\"');
expect(windowsQuoteArg(r'say "hi"'), r'"say \"hi\""');
expect(windowsQuoteArg(r'a\"b c'), r'"a\\\"b c"');
});
test("powershell strings", () {
expect(powershellQuote(r"C:\Users\O'Brien\app.exe"), r"'C:\Users\O''Brien\app.exe'");
expect(powershellQuote(r"$env:x `n"), r"'$env:x `n'");
});
test("the elevation script survives a quote in the path", () {
final args = elevationArgs(r"C:\Users\O'Brien\App\app.exe", ["--garage-apply", r"C:\Users\O'Brien\x.zip", "13"]);
expect(args.last, contains(r"-FilePath 'C:\Users\O''Brien\App\app.exe'"));
expect(args.last, contains(r"-ArgumentList '--garage-apply C:\Users\O''Brien\x.zip 13'"));
});
});
test("relaunch starts the stub with the apps own arguments", () async {
final w = locate();
await w.relaunch(["--route=/settings", "two words"]);
// its detached, give it a moment to run
for (var i = 0; i < 100 && fake.runs.isEmpty; i++) {
await Future<void>.delayed(const Duration(milliseconds: 50));
}
expect(fake.runs, [
["--route=/settings", "two words"],
]);
});
test("markHealthy zeroes failed_starts and nothing else", () async {
final w = locate();
await w.markHealthy();
final j = jsonDecode(fake.stateFile.readAsStringSync()) as Map;
expect(j["failed_starts"], 0);
expect(j["current"], 12);
expect(j["previous"], 9);
expect(j["blocked"], [11]);
expect(j["exe"], "garage_stash.exe");
});
test("markHealthy leaves a half written state file alone", () async {
fake.stateFile.writeAsStringSync('{ "exe": "garage_st');
await locate().markHealthy();
expect(fake.stateFile.readAsStringSync(), '{ "exe": "garage_st');
});
test("the stub counts starts on windows, not us", () async {
final w = locate();
expect(await w.noteStart(12), isFalse);
expect(w.state.read()!.failedStarts, 1);
});
}
+26
View File
@@ -0,0 +1,26 @@
# garage_updates on windows is no plugin code at all, only the stub. the
# pubspec says ffiPlugin so that flutter adds this folder to the host apps
# build, and what comes out is garage_stub.exe sat beside the app.
cmake_minimum_required(VERSION 3.14)
set(PROJECT_NAME "garage_updates")
project(${PROJECT_NAME} LANGUAGES CXX)
cmake_policy(VERSION 3.14...3.25)
# the host apps own icon, where flutter create puts it. an app that keeps it
# somewhere else sets GARAGE_STUB_ICON in its windows/CMakeLists.txt before
# generated_plugins.cmake is included
if(NOT GARAGE_STUB_ICON)
set(GARAGE_STUB_ICON "${CMAKE_SOURCE_DIR}/runner/resources/app_icon.ico")
endif()
add_subdirectory("stub")
# flutter installs everything in this list next to the app exe. its meant for
# dlls but its install(FILES), so an exe goes along just the same
set(garage_updates_bundled_libraries
"$<TARGET_FILE:garage_stub>"
PARENT_SCOPE
)
@@ -0,0 +1,71 @@
# the stub exe. in a folder of its own so the runtime switch below stays off
# everything else in the build.
#
# two things can be set before this is added:
# GARAGE_STUB_ICON an .ico for it. shortcuts point at the stub, so this
# is the icon people see
# GARAGE_STUB_OUT_DIR where the exe goes, for a build that has to know
cmake_minimum_required(VERSION 3.14)
# the stub sits on its own in <root>. the vc runtime dlls, if the app ships
# them at all, are a folder down where it cant see them. so its linked static.
# flutters project() runs before its cmake_policy(), which leaves /MD sat in
# the flags and MSVC_RUNTIME_LIBRARY ignored, so both ways are covered
foreach(_flags
CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_PROFILE CMAKE_CXX_FLAGS_RELEASE
CMAKE_CXX_FLAGS_RELWITHDEBINFO CMAKE_CXX_FLAGS_MINSIZEREL)
if(DEFINED ${_flags})
string(REPLACE "/MDd" "/MTd" ${_flags} "${${_flags}}")
string(REPLACE "/MD" "/MT" ${_flags} "${${_flags}}")
endif()
endforeach()
set(_stub_sources "garage_stub.cpp" "garage_common.h")
if(MSVC)
# as a source so the linker merges it. through the .rc it would collide with
# the manifest the linker makes itself
list(APPEND _stub_sources "garage_stub.exe.manifest")
endif()
set(GARAGE_STUB_ICON_LINE "")
if(GARAGE_STUB_ICON AND EXISTS "${GARAGE_STUB_ICON}")
# forward slashes. a backslash inside an .rc string is an escape
file(TO_CMAKE_PATH "${GARAGE_STUB_ICON}" _stub_icon)
set(GARAGE_STUB_ICON_LINE "1 ICON \"${_stub_icon}\"")
else()
message(STATUS "garage_updates: no icon for the stub, it gets the plain windows one")
endif()
# with msvc and no icon there would be nothing in the .rc at all, so it stays out
if(GARAGE_STUB_ICON_LINE OR NOT MSVC)
set(GARAGE_STUB_MANIFEST_FILE "${CMAKE_CURRENT_SOURCE_DIR}/garage_stub.exe.manifest")
configure_file("garage_stub.rc.in" "${CMAKE_CURRENT_BINARY_DIR}/garage_stub.rc" @ONLY)
list(APPEND _stub_sources "${CMAKE_CURRENT_BINARY_DIR}/garage_stub.rc")
if(NOT MSVC)
set_property(SOURCE "${CMAKE_CURRENT_BINARY_DIR}/garage_stub.rc" APPEND PROPERTY
COMPILE_DEFINITIONS GARAGE_RC_MANIFEST)
endif()
endif()
add_executable(garage_stub WIN32 ${_stub_sources})
target_compile_features(garage_stub PRIVATE cxx_std_17)
target_compile_definitions(garage_stub PRIVATE UNICODE _UNICODE)
set_target_properties(garage_stub PROPERTIES
OUTPUT_NAME "garage_stub"
MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
if(MSVC)
# no APPLY_STANDARD_SETTINGS. thats /WX, and this has never been through msvc
target_compile_options(garage_stub PRIVATE /W4 /EHsc /utf-8)
endif()
if(MINGW)
# mingw only looks for wWinMain when its told to
target_link_options(garage_stub PRIVATE -municode "-Wl,--subsystem,windows")
endif()
target_link_libraries(garage_stub PRIVATE user32 shell32 advapi32)
if(GARAGE_STUB_OUT_DIR)
# the empty genex stops visual studio adding a Release\ on the end
set_target_properties(garage_stub PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${GARAGE_STUB_OUT_DIR}$<0:>")
endif()
+652
View File
@@ -0,0 +1,652 @@
// the bits the stub and the installer both need. header only and everything
// is inline, so whichever of the two doesnt call a function doesnt get told
// off about it.
//
// nothing in here logs. it leaves GetLastError alone for the caller to report.
#pragma once
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0A00
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <string.h>
#include <string>
#include <vector>
namespace garage {
inline std::wstring widen(const std::string& s) {
if (s.empty()) return L"";
int n = MultiByteToWideChar(CP_UTF8, 0, s.data(), (int)s.size(), nullptr, 0);
if (n <= 0) return L"";
std::wstring w((size_t)n, L'\0');
MultiByteToWideChar(CP_UTF8, 0, s.data(), (int)s.size(), &w[0], n);
return w;
}
inline std::string narrow(const std::wstring& w) {
if (w.empty()) return "";
int n = WideCharToMultiByte(CP_UTF8, 0, w.data(), (int)w.size(), nullptr, 0, nullptr, nullptr);
if (n <= 0) return "";
std::string s((size_t)n, '\0');
WideCharToMultiByte(CP_UTF8, 0, w.data(), (int)w.size(), &s[0], n, nullptr, nullptr);
return s;
}
inline std::wstring num(long long v) {
return std::to_wstring(v);
}
// "5 Access is denied". winhttp keeps its own messages in its dll
inline std::wstring win_error(DWORD code) {
wchar_t buf[512];
DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
HMODULE from = nullptr;
if (code >= 12000 && code < 12200) {
from = GetModuleHandleW(L"winhttp.dll");
if (from) flags |= FORMAT_MESSAGE_FROM_HMODULE;
}
DWORD n = FormatMessageW(flags, from, code, 0, buf, ARRAYSIZE(buf), nullptr);
while (n > 0 && (buf[n - 1] == L'\r' || buf[n - 1] == L'\n' || buf[n - 1] == L' ' || buf[n - 1] == L'.')) n--;
std::wstring out = num(code);
if (n > 0) {
out += L" ";
out.append(buf, n);
}
return out;
}
// ---- paths ----
// only long ones get the prefix. with it on nothing is normalised any more,
// so short paths are better off without
inline std::wstring lp(const std::wstring& p) {
if (p.size() < 240) return p;
if (p.compare(0, 4, L"\\\\?\\") == 0) return p;
if (p.compare(0, 2, L"\\\\") == 0) return L"\\\\?\\UNC\\" + p.substr(2);
if (p.size() > 2 && p[1] == L':') return L"\\\\?\\" + p;
return p;
}
inline std::wstring join(const std::wstring& a, const std::wstring& b) {
if (a.empty()) return b;
wchar_t last = a[a.size() - 1];
if (last == L'\\' || last == L'/') return a + b;
return a + L"\\" + b;
}
inline std::wstring parent(const std::wstring& p) {
size_t at = p.find_last_of(L"\\/");
if (at == std::wstring::npos) return L"";
return p.substr(0, at);
}
inline std::wstring leaf(const std::wstring& p) {
size_t at = p.find_last_of(L"\\/");
if (at == std::wstring::npos) return p;
return p.substr(at + 1);
}
inline bool exists(const std::wstring& p) {
return GetFileAttributesW(lp(p).c_str()) != INVALID_FILE_ATTRIBUTES;
}
inline bool is_dir(const std::wstring& p) {
DWORD a = GetFileAttributesW(lp(p).c_str());
return a != INVALID_FILE_ATTRIBUTES && (a & FILE_ATTRIBUTE_DIRECTORY) != 0;
}
inline std::wstring absolute(const std::wstring& p) {
DWORD need = GetFullPathNameW(p.c_str(), 0, nullptr, nullptr);
if (need == 0) return p;
std::wstring out((size_t)need, L'\0');
DWORD got = GetFullPathNameW(p.c_str(), need, &out[0], nullptr);
if (got == 0 || got >= need) return p;
out.resize(got);
return out;
}
inline long long file_size(const std::wstring& p) {
WIN32_FILE_ATTRIBUTE_DATA info;
if (!GetFileAttributesExW(lp(p).c_str(), GetFileExInfoStandard, &info)) return -1;
return ((long long)info.nFileSizeHigh << 32) | (long long)info.nFileSizeLow;
}
inline bool same_text(const std::wstring& a, const std::wstring& b) {
return CompareStringOrdinal(a.data(), (int)a.size(), b.data(), (int)b.size(), TRUE) == CSTR_EQUAL;
}
inline bool starts_with(const std::wstring& s, const std::wstring& prefix) {
if (s.size() < prefix.size()) return false;
return CompareStringOrdinal(s.data(), (int)prefix.size(), prefix.data(), (int)prefix.size(), TRUE) == CSTR_EQUAL;
}
inline bool is_ascii(const std::wstring& s) {
for (size_t i = 0; i < s.size(); i++) {
if (s[i] > 126 || s[i] < 32) return false;
}
return true;
}
// deletes a folder and whats in it. keeps going past things it cant delete
// and hands back the first error, the caller says what to do about it
inline bool remove_tree(const std::wstring& dir, DWORD* firstError) {
bool clean = true;
WIN32_FIND_DATAW fd;
HANDLE find = FindFirstFileW(lp(join(dir, L"*")).c_str(), &fd);
if (find != INVALID_HANDLE_VALUE) {
do {
std::wstring name = fd.cFileName;
if (name == L"." || name == L"..") continue;
std::wstring full = join(dir, name);
bool isDir = (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
bool isLink = (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0;
if (isDir && !isLink) {
if (!remove_tree(full, firstError)) clean = false;
continue;
}
if (fd.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
SetFileAttributesW(lp(full).c_str(), fd.dwFileAttributes & ~(DWORD)FILE_ATTRIBUTE_READONLY);
}
// a junction is taken away as a folder, never walked in to
BOOL gone = isDir ? RemoveDirectoryW(lp(full).c_str()) : DeleteFileW(lp(full).c_str());
if (!gone) {
if (firstError && *firstError == 0) *firstError = GetLastError();
clean = false;
}
} while (FindNextFileW(find, &fd));
FindClose(find);
}
if (!RemoveDirectoryW(lp(dir).c_str())) {
DWORD err = GetLastError();
if (err != ERROR_FILE_NOT_FOUND && err != ERROR_PATH_NOT_FOUND) {
if (firstError && *firstError == 0) *firstError = err;
clean = false;
}
}
return clean;
}
inline bool read_file(const std::wstring& path, std::string& out, size_t cap) {
out.clear();
HANDLE h = INVALID_HANDLE_VALUE;
// the other side may be half way through swapping it
for (int i = 0; i < 10; i++) {
h = CreateFileW(lp(path).c_str(), GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (h != INVALID_HANDLE_VALUE) break;
if (GetLastError() != ERROR_SHARING_VIOLATION) return false;
Sleep(20);
}
if (h == INVALID_HANDLE_VALUE) return false;
char chunk[4096];
DWORD got = 0;
bool ok = true;
for (;;) {
if (!ReadFile(h, chunk, sizeof(chunk), &got, nullptr)) { ok = false; break; }
if (got == 0) break;
out.append(chunk, got);
if (out.size() > cap) break;
}
DWORD err = GetLastError();
CloseHandle(h);
SetLastError(err);
return ok;
}
// temp file beside it, then swapped in. a reader sees the old one or the new
// one and never half of either
inline bool write_atomic(const std::wstring& path, const std::string& bytes) {
std::wstring tmp = path + L".tmp" + num((long long)GetCurrentProcessId());
HANDLE h = CreateFileW(lp(tmp).c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, nullptr);
if (h == INVALID_HANDLE_VALUE) return false;
DWORD wrote = 0;
bool ok = WriteFile(h, bytes.data(), (DWORD)bytes.size(), &wrote, nullptr) && wrote == (DWORD)bytes.size();
if (ok) FlushFileBuffers(h);
DWORD err = GetLastError();
CloseHandle(h);
if (!ok) {
DeleteFileW(lp(tmp).c_str());
SetLastError(err);
return false;
}
for (int i = 0; i < 20; i++) {
if (MoveFileExW(lp(tmp).c_str(), lp(path).c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) {
return true;
}
err = GetLastError();
// somebody has it open to read. they wont for long
if (err != ERROR_SHARING_VIOLATION && err != ERROR_ACCESS_DENIED) break;
Sleep(25);
}
DeleteFileW(lp(tmp).c_str());
SetLastError(err);
return false;
}
// ---- json ----
// small, but a real parser. objects, arrays, strings, whole numbers, the
// three words. a number with a fraction keeps the part before the dot.
struct JVal {
enum Kind { Null, Bool, Num, Str, Arr, Obj };
Kind kind = Null;
bool b = false;
long long n = 0;
std::string s;
std::vector<std::string> keys;
std::vector<JVal> items;
const JVal* get(const char* key) const {
if (kind != Obj) return nullptr;
for (size_t i = 0; i < keys.size(); i++) {
if (keys[i] == key) return &items[i];
}
return nullptr;
}
std::string str(const char* key) const {
const JVal* v = get(key);
return v && v->kind == Str ? v->s : std::string();
}
long long number(const char* key, long long fallback) const {
const JVal* v = get(key);
return v && v->kind == Num ? v->n : fallback;
}
};
struct JParser {
const char* p;
const char* end;
int depth;
};
inline void j_ws(JParser& j) {
while (j.p < j.end && (*j.p == ' ' || *j.p == '\t' || *j.p == '\r' || *j.p == '\n')) j.p++;
}
inline void j_utf8(std::string& out, unsigned long cp) {
if (cp < 0x80) {
out += (char)cp;
} else if (cp < 0x800) {
out += (char)(0xC0 | (cp >> 6));
out += (char)(0x80 | (cp & 0x3F));
} else if (cp < 0x10000) {
out += (char)(0xE0 | (cp >> 12));
out += (char)(0x80 | ((cp >> 6) & 0x3F));
out += (char)(0x80 | (cp & 0x3F));
} else {
out += (char)(0xF0 | (cp >> 18));
out += (char)(0x80 | ((cp >> 12) & 0x3F));
out += (char)(0x80 | ((cp >> 6) & 0x3F));
out += (char)(0x80 | (cp & 0x3F));
}
}
inline bool j_hex4(JParser& j, unsigned long& out) {
if (j.end - j.p < 4) return false;
out = 0;
for (int i = 0; i < 4; i++) {
char c = *j.p++;
out <<= 4;
if (c >= '0' && c <= '9') out |= (unsigned long)(c - '0');
else if (c >= 'a' && c <= 'f') out |= (unsigned long)(c - 'a' + 10);
else if (c >= 'A' && c <= 'F') out |= (unsigned long)(c - 'A' + 10);
else return false;
}
return true;
}
inline bool j_string(JParser& j, std::string& out) {
if (j.p >= j.end || *j.p != '"') return false;
j.p++;
while (j.p < j.end) {
char c = *j.p++;
if (c == '"') return true;
if (c != '\\') { out += c; continue; }
if (j.p >= j.end) return false;
char e = *j.p++;
switch (e) {
case 'n': out += '\n'; break;
case 't': out += '\t'; break;
case 'r': out += '\r'; break;
case 'b': out += '\b'; break;
case 'f': out += '\f'; break;
case 'u': {
unsigned long cp = 0;
if (!j_hex4(j, cp)) return false;
// two of them make one character above the bmp
if (cp >= 0xD800 && cp < 0xDC00 && j.end - j.p >= 6 && j.p[0] == '\\' && j.p[1] == 'u') {
JParser look = j;
look.p += 2;
unsigned long low = 0;
if (j_hex4(look, low) && low >= 0xDC00 && low < 0xE000) {
cp = 0x10000 + ((cp - 0xD800) << 10) + (low - 0xDC00);
j.p = look.p;
}
}
j_utf8(out, cp);
break;
}
default: out += e; break;
}
}
return false;
}
inline bool j_word(JParser& j, const char* word) {
size_t n = strlen(word);
if ((size_t)(j.end - j.p) < n || strncmp(j.p, word, n) != 0) return false;
j.p += n;
return true;
}
inline bool j_value(JParser& j, JVal& out) {
j_ws(j);
if (j.p >= j.end) return false;
char c = *j.p;
if (c == '"') {
out.kind = JVal::Str;
return j_string(j, out.s);
}
if (c == '{' || c == '[') {
bool isObj = c == '{';
char close = isObj ? '}' : ']';
out.kind = isObj ? JVal::Obj : JVal::Arr;
if (++j.depth > 32) return false;
j.p++;
j_ws(j);
if (j.p < j.end && *j.p == close) { j.p++; j.depth--; return true; }
for (;;) {
if (isObj) {
j_ws(j);
std::string key;
if (!j_string(j, key)) return false;
j_ws(j);
if (j.p >= j.end || *j.p != ':') return false;
j.p++;
out.keys.push_back(key);
}
out.items.push_back(JVal());
if (!j_value(j, out.items.back())) return false;
j_ws(j);
if (j.p >= j.end) return false;
if (*j.p == ',') { j.p++; continue; }
if (*j.p == close) { j.p++; j.depth--; return true; }
return false;
}
}
if (c == '-' || (c >= '0' && c <= '9')) {
bool neg = c == '-';
if (neg) j.p++;
if (j.p >= j.end || *j.p < '0' || *j.p > '9') return false;
long long v = 0;
while (j.p < j.end && *j.p >= '0' && *j.p <= '9') {
if (v < 900000000000000000LL) v = v * 10 + (*j.p - '0');
j.p++;
}
// whatever comes after the whole part is stepped over
while (j.p < j.end && (*j.p == '.' || *j.p == 'e' || *j.p == 'E' || *j.p == '+' || *j.p == '-' ||
(*j.p >= '0' && *j.p <= '9'))) {
j.p++;
}
out.kind = JVal::Num;
out.n = neg ? -v : v;
return true;
}
if (j_word(j, "true")) { out.kind = JVal::Bool; out.b = true; return true; }
if (j_word(j, "false")) { out.kind = JVal::Bool; out.b = false; return true; }
if (j_word(j, "null")) { out.kind = JVal::Null; return true; }
return false;
}
inline bool json_parse(const std::string& text, JVal& out) {
JParser j;
j.p = text.data();
j.end = text.data() + text.size();
j.depth = 0;
// some editors put a bom on the front
if (text.size() >= 3 && (unsigned char)text[0] == 0xEF && (unsigned char)text[1] == 0xBB &&
(unsigned char)text[2] == 0xBF) {
j.p += 3;
}
if (!j_value(j, out)) return false;
j_ws(j);
return j.p == j.end;
}
inline std::string json_quote(const std::string& s) {
static const char hex[] = "0123456789abcdef";
std::string out = "\"";
for (size_t i = 0; i < s.size(); i++) {
unsigned char c = (unsigned char)s[i];
if (c == '"' || c == '\\') {
out += '\\';
out += (char)c;
} else if (c < 0x20) {
out += "\\u00";
out += hex[c >> 4];
out += hex[c & 15];
} else {
out += (char)c;
}
}
out += '"';
return out;
}
inline std::string json_print(const JVal& v) {
switch (v.kind) {
case JVal::Null: return "null";
case JVal::Bool: return v.b ? "true" : "false";
case JVal::Num: return std::to_string(v.n);
case JVal::Str: return json_quote(v.s);
default: break;
}
bool isObj = v.kind == JVal::Obj;
std::string out = isObj ? "{" : "[";
for (size_t i = 0; i < v.items.size(); i++) {
if (i > 0) out += ", ";
if (isObj) out += json_quote(v.keys[i]) + ": ";
out += json_print(v.items[i]);
}
out += isObj ? "}" : "]";
return out;
}
// ---- garage_updates.json ----
struct State {
std::wstring exe;
long long current = -1; // -1 is "there isnt one"
long long previous = -1;
long long failedStarts = 0;
std::vector<long long> blocked;
// anything else thats in the file (the dart side keeps app_id in there).
// not ours, so it goes back out the way it came in
std::vector<std::string> extraKeys;
std::vector<JVal> extraVals;
std::wstring extra(const char* key) const {
for (size_t i = 0; i < extraKeys.size(); i++) {
if (extraKeys[i] == key && extraVals[i].kind == JVal::Str) return widen(extraVals[i].s);
}
return L"";
}
void set_extra(const char* key, const std::wstring& value) {
JVal v;
v.kind = JVal::Str;
v.s = narrow(value);
for (size_t i = 0; i < extraKeys.size(); i++) {
if (extraKeys[i] == key) { extraVals[i] = v; return; }
}
extraKeys.push_back(key);
extraVals.push_back(v);
}
bool is_blocked(long long build) const {
for (size_t i = 0; i < blocked.size(); i++) {
if (blocked[i] == build) return true;
}
return false;
}
};
inline bool parse_state(const std::string& text, State& st) {
JVal root;
if (!json_parse(text, root) || root.kind != JVal::Obj) return false;
st = State();
st.exe = widen(root.str("exe"));
st.current = root.number("current", -1);
st.previous = root.number("previous", -1);
st.failedStarts = root.number("failed_starts", 0);
if (st.failedStarts < 0) st.failedStarts = 0;
const JVal* blocked = root.get("blocked");
if (blocked && blocked->kind == JVal::Arr) {
for (size_t i = 0; i < blocked->items.size(); i++) {
if (blocked->items[i].kind == JVal::Num) st.blocked.push_back(blocked->items[i].n);
}
}
for (size_t i = 0; i < root.keys.size(); i++) {
const std::string& k = root.keys[i];
if (k == "exe" || k == "current" || k == "previous" || k == "failed_starts" || k == "blocked") continue;
st.extraKeys.push_back(k);
st.extraVals.push_back(root.items[i]);
}
return true;
}
inline std::string print_build(long long build) {
return build > 0 ? std::to_string(build) : std::string("null");
}
inline std::string print_state(const State& st) {
std::string out = "{\n";
out += " \"exe\": " + json_quote(narrow(st.exe)) + ",\n";
out += " \"current\": " + print_build(st.current) + ",\n";
out += " \"previous\": " + print_build(st.previous) + ",\n";
out += " \"failed_starts\": " + std::to_string(st.failedStarts) + ",\n";
out += " \"blocked\": [";
for (size_t i = 0; i < st.blocked.size(); i++) {
if (i > 0) out += ", ";
out += std::to_string(st.blocked[i]);
}
out += "]";
for (size_t i = 0; i < st.extraKeys.size(); i++) {
out += ",\n " + json_quote(st.extraKeys[i]) + ": " + json_print(st.extraVals[i]);
}
out += "\n}\n";
return out;
}
inline std::wstring state_path(const std::wstring& root) {
return join(root, L"garage_updates.json");
}
inline std::wstring version_dir(const std::wstring& root, long long build) {
return join(root, L"app-" + num(build));
}
// "app-12" and nothing else. a half unpacked folder has a different name on
// purpose so it never gets past this
inline bool parse_version_name(const std::wstring& name, long long& build) {
if (name.size() < 5 || name.size() > 4 + 17) return false;
if (name.compare(0, 4, L"app-") != 0) return false;
long long v = 0;
for (size_t i = 4; i < name.size(); i++) {
if (name[i] < L'0' || name[i] > L'9') return false;
v = v * 10 + (name[i] - L'0');
}
if (v <= 0) return false;
build = v;
return true;
}
inline std::vector<long long> list_versions(const std::wstring& root) {
std::vector<long long> out;
WIN32_FIND_DATAW fd;
HANDLE find = FindFirstFileW(lp(join(root, L"app-*")).c_str(), &fd);
if (find == INVALID_HANDLE_VALUE) return out;
do {
long long build = 0;
if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && parse_version_name(fd.cFileName, build)) {
out.push_back(build);
}
} while (FindNextFileW(find, &fd));
FindClose(find);
return out;
}
// ---- processes ----
// one argument, quoted so that CommandLineToArgvW on the other end gives
// back exactly this
inline std::wstring quote_arg(const std::wstring& arg) {
if (!arg.empty() && arg.find_first_of(L" \t\"") == std::wstring::npos) return arg;
std::wstring out = L"\"";
size_t slashes = 0;
for (size_t i = 0; i < arg.size(); i++) {
wchar_t c = arg[i];
if (c == L'\\') {
slashes++;
continue;
}
if (c == L'"') {
out.append(slashes * 2 + 1, L'\\');
} else {
out.append(slashes, L'\\');
}
slashes = 0;
out += c;
}
// the ones at the very end sit in front of our closing quote
out.append(slashes * 2, L'\\');
out += L"\"";
return out;
}
// runs something with no window and waits for it. `output` (may be null) gets
// its stdout and stderr and has to be an inheritable handle
inline bool run_wait(const std::wstring& exe, const std::wstring& args, const std::wstring& cwd,
HANDLE output, DWORD& exitCode) {
std::wstring cmd = quote_arg(exe);
if (!args.empty()) cmd += L" " + args;
STARTUPINFOW si = {};
si.cb = sizeof(si);
if (output) {
si.dwFlags |= STARTF_USESTDHANDLES;
si.hStdOutput = output;
si.hStdError = output;
}
PROCESS_INFORMATION pi = {};
if (!CreateProcessW(exe.c_str(), &cmd[0], nullptr, nullptr, output ? TRUE : FALSE,
CREATE_NO_WINDOW, nullptr, cwd.empty() ? nullptr : cwd.c_str(), &si, &pi)) {
return false;
}
WaitForSingleObject(pi.hProcess, INFINITE);
exitCode = 1;
GetExitCodeProcess(pi.hProcess, &exitCode);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
return true;
}
} // namespace garage
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<requestedExecutionLevel level="asInvoker" uiAccess="false"/>
</requestedPrivileges>
</security>
</trustInfo>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
</application>
</compatibility>
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
<longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
</windowsSettings>
</application>
</assembly>
@@ -0,0 +1,9 @@
// the stub is what the shortcuts point at, so it wears the apps icon
#pragma code_page(65001)
@GARAGE_STUB_ICON_LINE@
// msvc gets the manifest handed to the linker instead, two of them collide
#ifdef GARAGE_RC_MANIFEST
1 24 "@GARAGE_STUB_MANIFEST_FILE@"
#endif
@@ -0,0 +1,114 @@
# the first-time installer for an app that uses garage_updates. built once by
# the developer, per app:
#
# cmake -S . -B build -A x64 -DGARAGE_APP_NAME="Garage Stash" -DGARAGE_APP_ID=net.imbenji.stash
# -DGARAGE_PROJECT_ID=<project id> -DGARAGE_EXE_NAME=garage_stash.exe -DGARAGE_ICON=C:/.../app_icon.ico
# cmake --build build --config Release
#
# and out comes "<AppName>-Setup.exe" with the stub inside it. build_installer.bat
# does the same with shorter flags.
cmake_minimum_required(VERSION 3.15)
project(garage_installer LANGUAGES CXX)
# static runtime, its handed to people who have nothing installed yet
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
set(GARAGE_APP_NAME "" CACHE STRING "The apps name as people see it")
set(GARAGE_APP_ID "" CACHE STRING "A stable id, e.g. net.imbenji.stash. Names the uninstall entry")
set(GARAGE_PROJECT_ID "" CACHE STRING "The Garage project the releases are published on")
set(GARAGE_EXE_NAME "" CACHE STRING "The apps exe inside a build, e.g. garage_stash.exe")
set(GARAGE_API_BASE "https://pay.imbenji.net/api" CACHE STRING "Where the update check goes")
set(GARAGE_PUBLISHER "" CACHE STRING "Shown in Installed apps. Optional")
set(GARAGE_ICON "" CACHE FILEPATH "An .ico for the installer, the stub and the shortcuts. Optional")
set(GARAGE_DEFAULT_LOCATION "me" CACHE STRING "me (LocalAppData) or everyone (Program Files)")
option(GARAGE_SHOW_CHOICE "Ask just me / everyone. Off goes with the default without asking" ON)
option(GARAGE_DESKTOP_SHORTCUT "A desktop shortcut as well as the start menu one" OFF)
foreach(_needed GARAGE_APP_NAME GARAGE_APP_ID GARAGE_PROJECT_ID GARAGE_EXE_NAME)
if("${${_needed}}" STREQUAL "")
message(FATAL_ERROR "${_needed} has to be set, e.g. -D${_needed}=...")
endif()
endforeach()
if(NOT GARAGE_EXE_NAME MATCHES "\\.exe$")
message(FATAL_ERROR "GARAGE_EXE_NAME is the file name with .exe on it, got \"${GARAGE_EXE_NAME}\"")
endif()
if(GARAGE_APP_ID MATCHES "[\\\\/:*?\"<>| ]")
message(FATAL_ERROR "GARAGE_APP_ID ends up as a folder and a registry key, keep it to letters, digits, dots and dashes")
endif()
if(NOT GARAGE_DEFAULT_LOCATION MATCHES "^(me|everyone)$")
message(FATAL_ERROR "GARAGE_DEFAULT_LOCATION is me or everyone, got \"${GARAGE_DEFAULT_LOCATION}\"")
endif()
if(GARAGE_ICON AND NOT EXISTS "${GARAGE_ICON}")
message(FATAL_ERROR "GARAGE_ICON: theres no ${GARAGE_ICON}")
endif()
# these land inside L"..." in a header
foreach(_text GARAGE_APP_NAME GARAGE_APP_ID GARAGE_PROJECT_ID GARAGE_EXE_NAME GARAGE_API_BASE GARAGE_PUBLISHER)
string(REPLACE "\\" "\\\\" ${_text}_C "${${_text}}")
string(REPLACE "\"" "\\\"" ${_text}_C "${${_text}_C}")
endforeach()
# no slash on the end, the code puts its own on
string(REGEX REPLACE "/+$" "" GARAGE_API_BASE_C "${GARAGE_API_BASE_C}")
set(GARAGE_DEFAULT_EVERYONE_C 0)
if(GARAGE_DEFAULT_LOCATION STREQUAL "everyone")
set(GARAGE_DEFAULT_EVERYONE_C 1)
endif()
set(GARAGE_SHOW_CHOICE_C 0)
if(GARAGE_SHOW_CHOICE)
set(GARAGE_SHOW_CHOICE_C 1)
endif()
set(GARAGE_DESKTOP_SHORTCUT_C 0)
if(GARAGE_DESKTOP_SHORTCUT)
set(GARAGE_DESKTOP_SHORTCUT_C 1)
endif()
set(_generated "${CMAKE_CURRENT_BINARY_DIR}/generated")
configure_file("installer_config.h.in" "${_generated}/installer_config.h" @ONLY)
# the stub is the plugins one, built here with this apps icon on it and put
# somewhere the .rc can name
set(_stub_dir "${CMAKE_CURRENT_SOURCE_DIR}/../windows/stub")
set(GARAGE_STUB_ICON "${GARAGE_ICON}")
set(GARAGE_STUB_OUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/stub_out")
add_subdirectory("${_stub_dir}" "${CMAKE_CURRENT_BINARY_DIR}/stub")
set(GARAGE_STUB_FILE "${GARAGE_STUB_OUT_DIR}/garage_stub.exe")
set(GARAGE_ICON_LINE "")
if(GARAGE_ICON)
file(TO_CMAKE_PATH "${GARAGE_ICON}" _icon)
set(GARAGE_ICON_LINE "1 ICON \"${_icon}\"")
endif()
set(GARAGE_MANIFEST_FILE "${CMAKE_CURRENT_SOURCE_DIR}/installer.exe.manifest")
configure_file("installer.rc.in" "${_generated}/installer.rc" @ONLY)
set(_sources "installer.cpp" "${_generated}/installer_config.h" "${_generated}/installer.rc")
if(MSVC)
list(APPEND _sources "installer.exe.manifest")
endif()
add_executable(garage_installer WIN32 ${_sources})
target_compile_features(garage_installer PRIVATE cxx_std_17)
target_compile_definitions(garage_installer PRIVATE UNICODE _UNICODE)
target_include_directories(garage_installer PRIVATE "${_generated}" "${_stub_dir}")
if(MSVC)
target_compile_options(garage_installer PRIVATE /W4 /EHsc /utf-8)
else()
# not msvc, so nothing merges the manifest for us. it goes in through the .rc
set_property(SOURCE "${_generated}/installer.rc" APPEND PROPERTY COMPILE_DEFINITIONS GARAGE_RC_MANIFEST)
endif()
if(MINGW)
target_link_options(garage_installer PRIVATE -municode "-Wl,--subsystem,windows")
endif()
target_link_libraries(garage_installer PRIVATE
user32 shell32 advapi32 ole32 uuid comctl32 winhttp bcrypt)
# the .rc pulls the stub in as a file, which cmake cant see for itself
add_dependencies(garage_installer garage_stub)
set_property(SOURCE "${_generated}/installer.rc" APPEND PROPERTY OBJECT_DEPENDS "${GARAGE_STUB_FILE}")
# the name with whatever a file name cant have taken out
string(REGEX REPLACE "[\\\\/:*?\"<>|]" "" _file_name "${GARAGE_APP_NAME}")
set_target_properties(garage_installer PROPERTIES OUTPUT_NAME "${_file_name}-Setup")
@@ -0,0 +1,82 @@
@echo off
setlocal
rem builds "<AppName>-Setup.exe" for one app. needs cmake and visual studio's
rem c++ tools, the same things flutter build windows needs.
rem
rem build_installer.bat --name "Garage Stash" --id net.imbenji.stash ^
rem --project <garage project id> --exe garage_stash.exe ^
rem --icon C:\path\app_icon.ico
rem
rem optional:
rem --api <url> where the update check goes (default pay.imbenji.net/api)
rem --publisher "<name>" shown in Installed apps
rem --default me^|everyone which one is ticked to begin with (default me)
rem --hide-choice dont ask, go with the default
rem --desktop a desktop shortcut as well
rem --arch x64^|arm64 default x64
rem --out <folder> where the exe is put (default: the folder youre in)
set "HERE=%~dp0"
set "NAME="
set "ID="
set "PROJECT="
set "EXE="
set "ICON="
set "API=https://pay.imbenji.net/api"
set "PUBLISHER="
set "LOCATION=me"
set "CHOICE=ON"
set "DESKTOP=OFF"
set "ARCH=x64"
set "OUT=%CD%"
:args
if "%~1"=="" goto run
if /i "%~1"=="--name" ( set "NAME=%~2" & shift & shift & goto args )
if /i "%~1"=="--id" ( set "ID=%~2" & shift & shift & goto args )
if /i "%~1"=="--project" ( set "PROJECT=%~2" & shift & shift & goto args )
if /i "%~1"=="--exe" ( set "EXE=%~2" & shift & shift & goto args )
if /i "%~1"=="--icon" ( set "ICON=%~f2" & shift & shift & goto args )
if /i "%~1"=="--api" ( set "API=%~2" & shift & shift & goto args )
if /i "%~1"=="--publisher" ( set "PUBLISHER=%~2" & shift & shift & goto args )
if /i "%~1"=="--default" ( set "LOCATION=%~2" & shift & shift & goto args )
if /i "%~1"=="--arch" ( set "ARCH=%~2" & shift & shift & goto args )
if /i "%~1"=="--out" ( set "OUT=%~f2" & shift & shift & goto args )
if /i "%~1"=="--hide-choice" ( set "CHOICE=OFF" & shift & goto args )
if /i "%~1"=="--desktop" ( set "DESKTOP=ON" & shift & goto args )
echo build_installer: dont know what "%~1" is
exit /b 2
:run
if "%NAME%"=="" ( echo build_installer: --name is needed & exit /b 2 )
if "%ID%"=="" ( echo build_installer: --id is needed & exit /b 2 )
if "%PROJECT%"=="" ( echo build_installer: --project is needed & exit /b 2 )
if "%EXE%"=="" ( echo build_installer: --exe is needed & exit /b 2 )
set "VSARCH=x64"
if /i "%ARCH%"=="arm64" set "VSARCH=ARM64"
rem one build folder per app and arch, so two apps dont share a cache
set "BUILD=%HERE%build\%ID%-%ARCH%"
rem cmake wants forward slashes in a path it is going to paste in to an .rc
if defined ICON set "ICON=%ICON:\=/%"
cmake -S "%HERE%." -B "%BUILD%" -A %VSARCH% ^
"-DGARAGE_APP_NAME=%NAME%" "-DGARAGE_APP_ID=%ID%" "-DGARAGE_PROJECT_ID=%PROJECT%" ^
"-DGARAGE_EXE_NAME=%EXE%" "-DGARAGE_API_BASE=%API%" "-DGARAGE_PUBLISHER=%PUBLISHER%" ^
"-DGARAGE_ICON=%ICON%" "-DGARAGE_DEFAULT_LOCATION=%LOCATION%" ^
-DGARAGE_SHOW_CHOICE=%CHOICE% -DGARAGE_DESKTOP_SHORTCUT=%DESKTOP%
if errorlevel 1 ( echo build_installer: cmake couldnt set the build up & exit /b 1 )
cmake --build "%BUILD%" --config Release
if errorlevel 1 ( echo build_installer: the build failed & exit /b 1 )
if not exist "%OUT%" mkdir "%OUT%"
copy /y "%BUILD%\Release\*-Setup.exe" "%OUT%\" >nul
if errorlevel 1 ( echo build_installer: built, but couldnt copy the exe out of %BUILD%\Release & exit /b 1 )
echo.
echo the installer is in %OUT%
endlocal
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<!-- asInvoker on purpose. "just me" never needs admin, and "everyone" asks for it itself -->
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<requestedExecutionLevel level="asInvoker" uiAccess="false"/>
</requestedPrivileges>
</security>
</trustInfo>
<!-- the task dialog only exists in version 6 of the common controls -->
<dependency>
<dependentAssembly>
<assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0"
processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*"/>
</dependentAssembly>
</dependency>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
</application>
</compatibility>
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
<longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
</windowsSettings>
</application>
</assembly>
@@ -0,0 +1,12 @@
// made by cmake. the icon, the stub and (not for msvc) the manifest
#pragma code_page(65001)
@GARAGE_ICON_LINE@
// the stub, whole. its written out as <root>\<AppExe>.exe
STUB RCDATA "@GARAGE_STUB_FILE@"
// msvc gets the manifest handed to the linker instead, two of them collide
#ifdef GARAGE_RC_MANIFEST
1 24 "@GARAGE_MANIFEST_FILE@"
#endif
@@ -0,0 +1,24 @@
// made by cmake from the values the installer was built with. dont edit the
// copy in the build folder, it gets written over.
#pragma once
// what people see: the window, the shortcut, the folder, "installed apps"
#define GARAGE_APP_NAME L"@GARAGE_APP_NAME_C@"
// the key of the uninstall entry, and the folder under %LOCALAPPDATA% that
// downloads go to when the install itself is read only
#define GARAGE_APP_ID L"@GARAGE_APP_ID_C@"
#define GARAGE_PROJECT_ID L"@GARAGE_PROJECT_ID_C@"
#define GARAGE_API_BASE L"@GARAGE_API_BASE_C@"
// the apps exe inside a build. the stub goes in root under the same name
#define GARAGE_EXE_NAME L"@GARAGE_EXE_NAME_C@"
#define GARAGE_PUBLISHER L"@GARAGE_PUBLISHER_C@"
// 1 is "everyone on this pc" (program files), 0 is "just me"
#define GARAGE_DEFAULT_EVERYONE @GARAGE_DEFAULT_EVERYONE_C@
// 0 never asks and goes with the default
#define GARAGE_SHOW_CHOICE @GARAGE_SHOW_CHOICE_C@
#define GARAGE_DESKTOP_SHORTCUT @GARAGE_DESKTOP_SHORTCUT_C@