pathToUrl method
Returns a Uri from the current library to the one provided.
If possible, a package:
or dart:
URL scheme will be used to reference
the library, falling back to relative paths if required (such as in the
test
directory).
The support Uri.schemes are (others throw ArgumentError):
dart
package
asset
May throw ArgumentError if it is not possible to resolve a path.
Implementation
Uri pathToUrl(dynamic toUrlOrString) {
// TODO: https://github.com/dart-lang/source_gen/issues/672 - Take Object
ArgumentError.checkNotNull(toUrlOrString, 'toUrlOrString');
final to = toUrlOrString is Uri
? toUrlOrString
: Uri.parse(toUrlOrString as String);
if (to.scheme == 'dart') {
// Convert dart:core/map.dart to dart:core.
return normalizeDartUrl(to);
}
if (to.scheme == 'package') {
// Identity (no-op).
return to;
}
if (to.scheme == 'asset') {
// This is the same thing as a package: URL.
//
// i.e.
// asset:foo/lib/foo.dart ===
// package:foo/foo.dart
if (to.pathSegments.length > 1 && to.pathSegments[1] == 'lib') {
return assetToPackageUrl(to);
}
var from = element.source.uri;
// Normalize (convert to an asset: URL).
from = normalizeUrl(from);
if (_isRelative(from, to)) {
if (from == to) {
// Edge-case: p.relative('a.dart', 'a.dart') == '.', but that is not
// a valid import URL in Dart source code.
return Uri(path: to.pathSegments.last);
}
final relative = p.toUri(
p.relative(
to.toString(),
from: from.toString(),
),
);
// We now have a URL like "../b.dart", but we just want "b.dart".
return relative.replace(
pathSegments: relative.pathSegments.skip(1),
);
}
throw ArgumentError.value(to, 'to', 'Not relative to $from');
}
throw ArgumentError.value(to, 'to', 'Cannot use scheme "${to.scheme}"');
}