expand static method

String expand(
  1. String path
)

Returns the expanded path.

Expands the following parts:

  • Environment variables (IEEE Std 1003.1-2001), eg. $HOME/dart-sdk/pub
  • Home directory of the current user, eg ~/dart-sdk/pub

Implementation

static String expand(String path) {
  if (path.isEmpty) {
    return path;
  }

  path = _expand(path);
  if (path[0] != '~') {
    return path;
  }

  // TODO: add support of '~user' format.
  String? home;
  if (_isWindows) {
    final drive = Platform.environment['HOMEDRIVE'];
    final path = Platform.environment['HOMEPATH'];
    if (drive != null &&
        drive.isNotEmpty &&
        path != null &&
        path.isNotEmpty) {
      home = drive + path;
    } else {
      home = Platform.environment['USERPROFILE'];
    }

    home = home!.replaceAll('\\', '/');
  } else {
    home = Platform.environment['HOME'];
  }

  if (home == null || home.isEmpty) {
    return path;
  }

  if (home.endsWith('/') || home.endsWith('\\')) {
    home = home.substring(0, home.length - 1);
  }

  if (path == '~' || path == '~/') {
    return home;
  }

  if (path.startsWith('~/')) {
    return home + '/' + path.substring(2);
  }

  return path;
}