-
-
Save liudonghua123/f640fbc1d99bb58c6cb5e9b50dcb2e60 to your computer and use it in GitHub Desktop.
Example of basic Dart REPL using vm_service package
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: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 | |
late 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
Run it with
dart --enable-vm-service repl.dart