detect function

Profile detect({
  1. required bool isTty,
  2. required Map<String, String> env,
  3. bool isWindows = false,
})

Detect the terminal color profile from an "is TTY?" signal and environment.

This is a Dart port of charmbracelet/colorprofile's env/tty rules (minus terminfo probing in the initial version).

For I/O-dependent detection (e.g. from an IOSink), use detectForSink() in package:artisanal.

Implementation

Profile detect({
  required bool isTty,
  required Map<String, String> env,
  bool isWindows = false,
}) {
  final term = env['TERM'];
  final isDumb =
      ((term == null || term.isEmpty) && !isWindows) || term == _dumbTerm;

  final envp = _envColorProfile(env: env, isWindows: isWindows);

  var p = (!isTty || isDumb) ? Profile.noTty : envp;

  // NO_COLOR disables colors (but not decoration) when output is a TTY.
  if (isTty && envNoColor(env)) {
    if (p > Profile.ascii) p = Profile.ascii;
    return p;
  }

  // CLICOLOR_FORCE forces colors, even when we would otherwise be NoTTY/dumb.
  if (cliColorForced(env)) {
    if (p < Profile.ansi) p = Profile.ansi;
    if (envp > p) p = envp;
    return p;
  }

  // CLICOLOR enables at least ANSI colors when TERM is not defined.
  if (cliColor(env)) {
    if (isTty && !isDumb && p < Profile.ansi) {
      p = Profile.ansi;
    }
  }

  return p;
}