ghosttyTerminalShellEnvironment function

Map<String, String> ghosttyTerminalShellEnvironment({
  1. required Map<String, String> platformEnvironment,
  2. Map<String, String> overrides = const <String, String>{},
  3. GhosttyTerminalShellEnvironmentOptions options = const GhosttyTerminalShellEnvironmentOptions(),
})

Builds a shell-friendly environment from a platform environment map.

This keeps the caller's existing environment intact, then applies terminal defaults such as TERM, COLORTERM, HOME-derived XDG paths, and a UTF-8 locale when the input environment did not already provide one.

Implementation

Map<String, String> ghosttyTerminalShellEnvironment({
  required Map<String, String> platformEnvironment,
  Map<String, String> overrides = const <String, String>{},
  GhosttyTerminalShellEnvironmentOptions options =
      const GhosttyTerminalShellEnvironmentOptions(),
}) {
  final environment = <String, String>{...platformEnvironment, ...overrides};

  environment['TERM'] = environment['TERM']?.isNotEmpty == true
      ? environment['TERM']!
      : options.term;
  final colorTerm = options.colorTerm;
  if (colorTerm != null &&
      (environment['COLORTERM'] == null || environment['COLORTERM']!.isEmpty)) {
    environment['COLORTERM'] = colorTerm;
  }

  final home = _resolvedHome(environment);
  if (home != null) {
    environment['HOME'] ??= home;
    if (options.ensureXdgPaths) {
      environment['XDG_CONFIG_HOME'] ??= '$home/.config';
      environment['XDG_CACHE_HOME'] ??= '$home/.cache';
      environment['XDG_DATA_HOME'] ??= '$home/.local/share';
      environment['XDG_STATE_HOME'] ??= '$home/.local/state';
    }
  }

  if (options.ensureUtf8Locale) {
    final utf8Locale = _resolvedUtf8Locale(
      environment,
      fallback: options.fallbackUtf8Locale,
    );
    if ((environment['LC_ALL'] == null || environment['LC_ALL']!.isEmpty) &&
        utf8Locale != null) {
      final lang = environment['LANG'];
      if (lang == null || !_containsUtf8Locale(lang)) {
        environment['LANG'] = utf8Locale;
      }
      final lcCtype = environment['LC_CTYPE'];
      if (lcCtype == null || !_containsUtf8Locale(lcCtype)) {
        environment['LC_CTYPE'] = utf8Locale;
      }
    }
  }

  return environment;
}