fileToUri function

String fileToUri(
  1. String path
)

Converts an absolute file path to a file:// URI (omp's fileToUri).

Path segments are percent-encoded; Windows drive letters are mapped to the /C:/... form. Paths are expected absolute with / separators (the harness's FileSystem namespace).

Implementation

String fileToUri(String path) {
  var p = path;
  // Windows drive: `C:\x` or `C:/x` → `/C:/x`.
  final drive = RegExp(r'^([a-zA-Z]):[\\/]').firstMatch(p);
  if (drive != null) {
    p = '/${drive.group(1)!.toUpperCase()}:${p.substring(2).replaceAll(r'\', '/')}';
  }
  if (!p.startsWith('/')) p = '/$p';
  final buffer = StringBuffer('file://');
  final segments = p.split('/');
  for (var i = 0; i < segments.length; i++) {
    if (i > 0) buffer.write('/');
    final segment = segments[i];
    // Keep the drive-letter colon (`C:`) readable per file-URI convention.
    if (i == 1 && RegExp(r'^[a-zA-Z]:$').hasMatch(segment)) {
      buffer.write(segment);
    } else {
      buffer.write(Uri.encodeComponent(segment));
    }
  }
  return buffer.toString();
}