parentOf method

String parentOf (
  1. String path
)

Removes the final path component of a path, using the platform's path separator to split the path.

Will not remove the root component of a Windows path, like "C:\" or "\\server_name\". Ignores trailing path separators, and leaves no trailing path separators.

Implementation

static String parentOf(String path) {
  int rootEnd = -1;
  if (Platform.isWindows) {
    if (path.startsWith(_absoluteWindowsPathPattern)) {
      // Root ends at first / or \ after the first two characters.
      rootEnd = path.indexOf(new RegExp(r'[/\\]'), 2);
      if (rootEnd == -1) return path;
    } else if (path.startsWith('\\') || path.startsWith('/')) {
      rootEnd = 0;
    }
  } else if (path.startsWith('/')) {
    rootEnd = 0;
  }
  // Ignore trailing slashes.
  // All non-trivial cases have separators between two non-separators.
  int pos = path.lastIndexOf(_parentRegExp);
  if (pos > rootEnd) {
    return path.substring(0, pos + 1);
  } else if (rootEnd > -1) {
    return path.substring(0, rootEnd + 1);
  } else {
    return '.';
  }
}