runCommand static method

Future<int> runCommand(
  1. List<String> arguments, {
  2. required List<NyCommand?> allCommands,
  3. required String menu,
})

Runs a command from the terminal. menu lists the runnable commands. Returns the exit code; an action that does not return an int counts as 0.

Implementation

static Future<int> runCommand(
  List<String> arguments, {
  required List<NyCommand?> allCommands,
  required String menu,
}) async {
  List<String> argumentsForAction = arguments.toList();

  if (argumentsForAction.isEmpty) {
    MetroConsole.writeInBlack(menu);
    return 0;
  }

  List<String> argumentSplit = arguments[0].split(":");

  if (argumentSplit.isEmpty || argumentSplit.length <= 1) {
    MetroConsole.writeInBlack('Invalid arguments $arguments');
    exit(2);
  }

  String type = argumentSplit[0];
  String action = argumentSplit[1];

  NyCommand? nyCommand = allCommands.firstWhereOrNull(
    (command) => type == command?.category && command?.name == action,
  );

  if (nyCommand == null) {
    MetroConsole.writeInBlack('Invalid arguments $arguments');
    exit(1);
  }

  argumentsForAction.removeAt(0);
  final dynamic result = await nyCommand.action!(argumentsForAction);
  return result is int ? result : 0;
}