run method

  1. @override
Future<void> run()
override

Runs this command.

The return value is wrapped in a Future if necessary and returned by CommandRunner.runCommand.

Implementation

@override
Future<void> run() async {
  try {
    // Setup arg table for script mode
    setupArgTable(
      originalArgs: originalArgs,
      scriptPath: scriptPath,
      scriptArgs: scriptArgs,
    );

    // Execute the script
    final file = File(scriptPath);
    if (!file.existsSync()) {
      safePrint('Error: Script file "$scriptPath" not found');
      exit(1);
    }

    final bytes = await file.readAsBytes();

    // Get absolute path for better debugging
    final absolutePath = file.absolute.path;
    _updateScriptMetadata(absolutePath);

    if (looksLikeTrackedLuaBytecodeBytes(bytes)) {
      final loadResult = await bridge.vm.loadChunk(
        LuaChunkLoadRequest(
          source: Value(LuaString.fromBytes(Uint8List.fromList(bytes))),
          chunkName: absolutePath,
          mode: 'b',
        ),
      );
      if (!loadResult.isSuccess) {
        throw Exception(loadResult.errorMessage ?? 'failed to load chunk');
      }
      await bridge.vm.callFunction(loadResult.chunk!, const <Object?>[]);
      return;
    }

    final sourceCode = () {
      try {
        return utf8.decode(bytes);
      } on FormatException {
        // Lua suite files such as strings.lua still use raw Latin-1 bytes.
        return latin1.decode(bytes);
      }
    }();

    await bridge.execute(sourceCode, scriptPath: absolutePath);
  } catch (e, s) {
    safePrint('Error executing script "$scriptPath": $e');
    safePrint(s.toString());
    rethrow;
  }
}