relativePath function

String relativePath(
  1. String from,
  2. String to
)

Computes the relative path from from to to.

Both paths are normalized before computation. If a relative path cannot be constructed (e.g. different drive letters on Windows), to is returned unchanged.

Implementation

String relativePath(String from, String to) {
  final nFrom = normalizePath(from).split('/');
  final nTo = normalizePath(to).split('/');

  // Find the common prefix length.
  var common = 0;
  while (common < nFrom.length &&
      common < nTo.length &&
      nFrom[common] == nTo[common]) {
    common++;
  }

  final ups = List.filled(nFrom.length - common, '..');
  final tail = nTo.sublist(common);
  final parts = [...ups, ...tail];
  if (parts.isEmpty) return '.';
  return parts.join('/');
}