normalizeDiskPath function

String normalizeDiskPath(
  1. String path, {
  2. String? disk,
})

Normalizes a disk path the way Flysystem does.

Backslashes become /, empty and . segments are dropped, and .. removes the segment before it. A .. that would climb above the root throws DiskPathTraversalException, and control characters throw DiskCorruptedPathException. A leading / is relative to the disk's root, so /avatars and avatars are the same path. Nothing is URL-decoded: %2e%2e is a file name, not ...

The result has no leading or trailing slash; the root is ''.

Implementation

String normalizeDiskPath(String path, {String? disk}) {
  if (_controlCharacters.hasMatch(path)) {
    throw DiskCorruptedPathException(path, disk: disk);
  }
  final List<String> segments = [];
  for (final String segment in path.replaceAll(r'\', '/').split('/')) {
    if (segment.isEmpty || segment == '.') continue;
    if (segment == '..') {
      if (segments.isEmpty) throw DiskPathTraversalException(path, disk: disk);
      segments.removeLast();
      continue;
    }
    segments.add(segment);
  }
  return segments.join('/');
}