Skip to content

Instantly share code, notes, and snippets.

@maks
Created January 12, 2021 08:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save maks/4643e49b5afb86459fc75047a8578556 to your computer and use it in GitHub Desktop.
Save maks/4643e49b5afb86459fc75047a8578556 to your computer and use it in GitHub Desktop.
Example of basic Dart REPL using vm_service package
import 'dart:developer' as dev;
import 'dart:io';
import 'package:vm_service/vm_service.dart' show InstanceRef, VmService;
import 'package:vm_service/vm_service_io.dart' as vms;
import 'package:vm_service/utils.dart' as vmutils;
// based on early version of:
// https://github.com/BlackHC/dart_repl/
// and example in:
// https://github.com/dart-lang/sdk/blob/master/pkg/vm_service/example/vm_service_tester.dart
// and the recharge package: https://github.com/ajinasokan/recharge
// Globals for easy access inside REPL
VmService vmService;
Future main(List<String> args) async {
vmService = await getOwnVmService();
final vm = await vmService.getVM();
print(vm.version);
print('Type `exit()` to quit.');
await repl(vmService);
}
Future repl(VmService vmService) async {
// Get currently running VM
final vm = await vmService.getVM();
final isolateRef = vm.isolates.first;
final isolate = await vmService.getIsolate(isolateRef.id);
while (true) {
stdout.write('>>> ');
final input = stdin.readLineSync();
if (input == null || input == 'exit()') {
if (input == null) {
stdout.write('\n');
}
break;
}
try {
final result = await vmService.evaluate(
isolateRef.id, isolate.rootLib.id, input) as InstanceRef;
final value = await result?.valueAsString;
if (value != null) {
print(value);
}
} on Exception catch (errorRef) {
print(errorRef);
}
}
exit(0);
}
Future<VmService> getOwnVmService() async {
// Observatory URL is like: http://127.0.0.1:8181/u31D8b3VvmM=/
// Websocket endpoint for that will be: ws://127.0.0.1:8181/reBbXy32L6g=/ws
final serverUri = (await dev.Service.getInfo()).serverUri;
if (serverUri == null) {
throw Exception('No VM service. Run with --enable-vm-service');
}
final wsUri = vmutils.convertToWebSocketUrl(serviceProtocolUrl: serverUri);
// Get VM service
return await vms.vmServiceConnectUri(wsUri.toString());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment