load static method

Loads the configuration from the .gatekeeper directory.

Returns an empty configuration if the directory or its files are absent.

Implementation

static GatekeeperClientConfig load() {
  final dir = resolveDirectory();
  if (dir == null || !dir.existsSync()) {
    return const GatekeeperClientConfig();
  }

  String? host;
  int? port;
  String? accessKey;
  var verbose = false;

  final configFile = File('${dir.path}${Platform.pathSeparator}config.json');
  if (configFile.existsSync()) {
    try {
      final content = configFile.readAsStringSync().trim();
      if (content.isNotEmpty) {
        final json = jsonDecode(content);
        if (json is Map) {
          host = _asString(json['host']);
          port = _asInt(json['port']);
          accessKey =
              _asString(json['access-key']) ?? _asString(json['accessKey']);
          verbose = json['verbose'] == true;
        }
      }
    } catch (e) {
      stderr.writeln(
          'Error reading Gatekeeper config file `${configFile.path}`: $e');
    }
  }

  // Optional dedicated access-key file, used only when `config.json` didn't
  // provide one:
  if (accessKey == null || accessKey.isEmpty) {
    final keyFile = File('${dir.path}${Platform.pathSeparator}access-key');
    if (keyFile.existsSync()) {
      try {
        final key = keyFile.readAsStringSync().trim();
        if (key.isNotEmpty) accessKey = key;
      } catch (e) {
        stderr.writeln(
            'Error reading Gatekeeper access-key file `${keyFile.path}`: $e');
      }
    }
  }

  return GatekeeperClientConfig(
    host: host,
    port: port,
    accessKey: accessKey,
    verbose: verbose,
  );
}