Created
March 27, 2022 00:05
-
-
Save jonahwilliams/9f7b99f00f357dab0e4d1ddf4bf16112 to your computer and use it in GitHub Desktop.
Hot Reload for Dart CLI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
import 'dart:convert'; | |
import 'dart:io'; | |
import 'package:vm_service/vm_service_io.dart'; | |
void main() async { | |
var process = await Process.start('dart', ['run', '--enable-vm-service', 'lib/main.dart']); | |
var completer = Completer<String>(); | |
process.stdout | |
.transform(utf8.decoder) | |
.transform(const LineSplitter()) | |
.listen((String line) { | |
print(line); | |
const message = 'Observatory listening on '; | |
if (line.startsWith(message)) { | |
completer.complete(line.split(message)[1].trim()); | |
} | |
}); | |
process.stderr | |
.transform(utf8.decoder) | |
.transform(const LineSplitter()) | |
.listen(print); | |
var url = Uri.parse(await completer.future); | |
print('connecting to ${url.replace(scheme: 'ws').toString() + 'ws/'}'); | |
var service = await vmServiceConnectUri(url.replace(scheme: 'ws').toString() + 'ws/'); | |
stdin.echoMode = false; | |
stdin.lineMode = false; | |
var pending = false; | |
print('Ready'); | |
stdin.transform(utf8.decoder).listen((String command) async { | |
if (pending) { | |
return; | |
} | |
try { | |
pending = true; | |
switch (command) { | |
case 'h': | |
print('Press r to hot reload and q to quit'); | |
break; | |
case 'r': | |
case 'R': | |
var vm = await service.getVM(); | |
for (var isolateRef in vm.isolates!) { | |
var report = await service.reloadSources(isolateRef.id!); | |
print(report); | |
} | |
break; | |
case 'q': | |
await service.dispose(); | |
process.kill(); | |
exit(0); | |
} | |
} finally { | |
pending = false; | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment