detectColorProfile function

ColorProfile detectColorProfile({
  1. Map<String, String>? environment,
  2. bool? isTerminal,
})

Detects the ColorProfile of the terminal from environment variables.

environment defaults to Platform.environment and isTerminal to stdoutIsTerminal. Pass both to get a pure, repeatable result.

The rules, first match wins:

  1. FORCE_COLOR set to a non-zero value forces colour, even when output is not a terminal: 2 gives at least ColorProfile.ansi256, 3 gives ColorProfile.trueColor, and other values give at least ColorProfile.ansi. The terminal rules below can raise it further.
  2. NO_COLOR set to any non-empty value gives ColorProfile.noColor (https://no-color.org).
  3. CLICOLOR_FORCE forces colour like FORCE_COLOR.
  4. Output that is not a terminal, or TERM=dumb, gives ColorProfile.noColor.
  5. COLORTERM=truecolor or 24bit, and known true-colour terminals (kitty, Ghostty, WezTerm, Alacritty, foot, iTerm2, VS Code, Windows Terminal), give ColorProfile.trueColor.
  6. A TERM ending in 256color, tmux, GNU screen and Apple Terminal give ColorProfile.ansi256.
  7. Anything else gives ColorProfile.ansi.

Mirrors the env rules of charmbracelet/colorprofile env.go (https://github.com/charmbracelet/colorprofile/blob/main/env.go), with three differences: it adds FORCE_COLOR and TERM_PROGRAM, it trusts COLORTERM inside tmux instead of running tmux info, and an unset TERM is not treated as dumb (Windows terminals do not set it).

Implementation

ColorProfile detectColorProfile({
  Map<String, String>? environment,
  bool? isTerminal,
}) {
  final env = environment ?? Platform.environment;
  final forced = _forcedProfile(env['FORCE_COLOR']);
  if (forced != null) return _max(forced, _terminalProfile(env));
  if (_isSet(env['NO_COLOR'])) return ColorProfile.noColor;
  final cliForced = _forcedProfile(env['CLICOLOR_FORCE']);
  if (cliForced != null) return _max(cliForced, _terminalProfile(env));
  if (isPlainOutput(env, isTerminal ?? stdoutIsTerminal())) {
    return ColorProfile.noColor;
  }
  return _terminalProfile(env);
}