compileAndRun function
Compiles script to a native executable with dart compile exe, runs it
with arguments, and returns its exit code.
AOT-compiled code is what most apps ship, and it has no JIT warmup, so
its numbers are usually the ones worth publishing. The executable goes to
outputDir, named after script. Its output is shown in this terminal.
Parameters:
script: the Dart file with amainto compile.arguments: arguments for the compiled program.outputDir: where the executable is written; created if missing.
Returns the compiler's exit code if compiling fails, otherwise the program's.
Throws:
- ProcessException if a process cannot be started.
Implementation
Future<int> compileAndRun(
String script, {
List<String> arguments = const [],
String outputDir = 'build',
}) async {
final dir = Directory(outputDir)..createSync(recursive: true);
var name = script.split(RegExp(r'[\\/]')).last;
if (name.endsWith('.dart')) name = name.substring(0, name.length - 5);
if (Platform.isWindows) name = '$name.exe';
final exe = File('${dir.absolute.path}${Platform.pathSeparator}$name').path;
final compile = await Process.start(
Platform.resolvedExecutable,
['compile', 'exe', script, '-o', exe],
mode: ProcessStartMode.inheritStdio,
);
final code = await compile.exitCode;
if (code != 0) return code;
final run = await Process.start(
exe,
arguments,
mode: ProcessStartMode.inheritStdio,
);
return run.exitCode;
}