formatUri function
Format a URI to a relative path if possible.
Implementation
String formatUri(String? uri, {String? cwd}) {
if (uri == null || uri.isEmpty) {
return '<unknown location>';
}
var filePath = uri.replaceFirst(RegExp(r'^file://'), '');
// Windows drive-letter paths: /C:/path → C:/path
if (RegExp(r'^/[A-Za-z]:').hasMatch(filePath)) {
filePath = filePath.substring(1);
}
// Decode URI encoding.
try {
filePath = Uri.decodeFull(filePath);
} catch (_) {
// Use un-decoded path on failure.
}
// Convert to relative path if cwd provided.
if (cwd != null && cwd.isNotEmpty) {
if (filePath.startsWith(cwd)) {
var relative = filePath.substring(cwd.length);
if (relative.startsWith('/') || relative.startsWith('\\')) {
relative = relative.substring(1);
}
// Normalize separators.
relative = relative.replaceAll('\\', '/');
if (relative.length < filePath.length && !relative.startsWith('../../')) {
return relative;
}
}
}
return filePath.replaceAll('\\', '/');
}