detectCompletionShell function

CompletionShell? detectCompletionShell({
  1. Map<String, String>? environment,
  2. Iterable<List<String>>? ancestorCommandLines,
  3. bool? isWindows,
})

Determines the shell that the user most likely runs the program from, or null if there is no such CompletionShell.

The alternatives are tried in this order:

  1. The nearest ancestor process that is a supported shell which the user types in. A shell that runs a script or a command (bash wrapper.sh, sh -c ...) is passed over, so that a wrapper script of the program does not hide the shell it was started from.
  2. The user's login shell, from the SHELL environment variable.
  3. PowerShell on Windows, where the ancestor processes are not inspected.

CompletionShell.carapace is a completion framework rather than a shell and is never detected.

environment defaults to the environment of the process, and isWindows to the platform it runs on. ancestorCommandLines are the command lines (the executable followed by its arguments) of the ancestor processes, nearest first. By default they are read with ps.

Implementation

CompletionShell? detectCompletionShell({
  final Map<String, String>? environment,
  final Iterable<List<String>>? ancestorCommandLines,
  final bool? isWindows,
}) {
  final windows = isWindows ?? Platform.isWindows;
  final commandLines =
      ancestorCommandLines ??
      (windows ? const <List<String>>[] : _ancestorCommandLines());
  for (final commandLine in commandLines) {
    final shell = _typedInShell(commandLine);
    if (shell != null) return shell;
  }

  final loginShell = (environment ?? Platform.environment)['SHELL'];
  final shell = loginShell == null ? null : _shellOfExecutable(loginShell);
  return shell ?? (windows ? CompletionShell.powershell : null);
}