resolvePath method

String resolvePath(
  1. String path
)

Resolves the given path relative to the currentDirectory. The resolved path is normalized and checked to ensure it stays within the rootDirectory.

If the path is absolute and matches part of the currentDirectory, the common prefix is removed.

If the path is relative, it is resolved relative to the currentDirectory.

Examples:

// Given rootDirectory = '/home/user/project' and currentDirectory = '/home/user/project/subdir'
resolvePath('file.txt'); // Returns: '/home/user/project/subdir/file.txt'
resolvePath('/home/user/project/subdir/file.txt'); // Returns: '/home/user/project/subdir/file.txt'
resolvePath('/home/user'); // Throws FileSystemException (outside root)
resolvePath('../../file.txt'); // Throws FileSystemException (attempt to go above root)

Implementation

String resolvePath(String path) {
  // Normalize both the current directory and the provided path
  String normalizedCurrentDir = p.normalize(currentDirectory);
  String normalizedRootDirectory = p.normalize(rootDirectory);
  String normalizedPath = p.normalize(path);

  // If the path is absolute, strip the common prefix with the current directory
  if (p.isAbsolute(normalizedPath)) {
    if (normalizedPath.startsWith(normalizedRootDirectory)) {
      // Remove the common prefix (root directory) from the path
      normalizedPath =
          p.relative(normalizedPath, from: normalizedRootDirectory);
    }
    if (p.isAbsolute(normalizedPath)) {
      // Resolve the remaining path relative to the root directory
      return _resolvePathWithinRoot(p.relative(normalizedPath, from: '/'));
    } else {
      return _resolvePathWithinRoot(normalizedPath);
    }
  } else {
    // For relative paths, resolve it as usual
    return _resolvePathWithinRoot(
        p.join(normalizedCurrentDir, normalizedPath));
  }
}