shouldEmitAnsi function

bool shouldEmitAnsi({
  1. required ColorPreference preference,
  2. required bool hasTerminal,
  3. required bool supportsAnsiEscapes,
  4. required Map<String, String> environment,
})

Returns whether ANSI escape codes should be written, given a preference, the target stream's capabilities (hasTerminal / supportsAnsiEscapes), and the process environment.

This is a pure function of its inputs so callers can unit-test every branch without a real terminal.

Implementation

bool shouldEmitAnsi({
  required ColorPreference preference,
  required bool hasTerminal,
  required bool supportsAnsiEscapes,
  required Map<String, String> environment,
}) {
  switch (preference) {
    case ColorPreference.never:
      return false;
    case ColorPreference.always:
      return true;
    case ColorPreference.auto:
      final noColor = environment['NO_COLOR'];
      if (noColor != null && noColor.isNotEmpty) return false;

      final forceColor = environment['FORCE_COLOR'];
      if (forceColor != null &&
          forceColor.isNotEmpty &&
          forceColor != '0' &&
          forceColor.toLowerCase() != 'false') {
        return true;
      }

      if (environment['TERM'] == 'dumb') return false;

      return hasTerminal && supportsAnsiEscapes;
  }
}