parse method

Map<String, dynamic> parse([
  1. List<String>? args
])

Parse configuration from environment and (optional) cli arguments.

Implementation

Map<String, dynamic> parse([List<String>? args]) {
  final cliValues = _parseCli(args);
  final values = <String, dynamic>{};
  for (final param in _params) {
    dynamic raw = param.defaultValue;
    if (!nullOrWhitespace(param.environment) &&
        Platform.environment.containsKey(param.environment)) {
      raw = Platform.environment[param.environment];
    }
    if (cliValues.containsKey(param)) {
      raw = cliValues[param];
    }

    if (param.required && raw == null) {
      throw BoostException('Missing value for config param "${param.name}".');
    }

    if (param.type == String) {
      values[param.name] = raw?.toString();
    } else if (param.type == int) {
      if (raw is int) {
        values[param.name] = raw;
      } else if (raw == null) {
        values[param.name] = null;
      } else {
        try {
          values[param.name] = int.parse(raw.toString());
        } catch (_) {
          throw BoostException(
              'Expected type int for param ${param.name}, instead got "$raw".');
        }
      }
    } else if (param.type == double) {
      if (raw is double) {
        values[param.name] = raw;
      } else if (raw == null) {
        values[param.name] = null;
      } else {
        try {
          values[param.name] = double.parse(raw.toString());
        } catch (_) {
          throw BoostException(
              'Expected type double for param ${param.name}, instead got "$raw".');
        }
      }
    } else if (param.type == bool) {
      if (raw is bool) {
        values[param.name] = raw;
      } else if (raw is num) {
        values[param.name] = raw > 0;
      } else if (raw == null) {
        values[param.name] = null;
      } else {
        values[param.name] = raw.toString().toLowerCase() == 'true';
      }
    } else {
      throw BoostException(
          'Type "${param.type}" not supported by ConfigParser.');
    }
  }

  return values;
}