AssetId.resolve constructor

AssetId.resolve(String uri, { AssetId from })

Creates a new AssetId from an uri String.

This gracefully handles package: or asset: URIs.

Resolve a package: URI when creating an AssetId from an import or export directive pointing to a package's lib directory:

AssetId assetOfDirective(UriReferencedElement element) {
  return new AssetId.resolve(element.uri);
}

When resolving a relative URI with no scheme, specifyg the origin asset (from) - otherwise an ArgumentError will be thrown.

AssetId assetOfDirective(AssetId origin, UriReferencedElement element) {
  return new AssetId.resolve(element.uri, from: origin);
}

asset: uris have the format '$package/$path', including the top level directory.

Implementation

factory AssetId.resolve(String uri, {AssetId from}) {
  final parsedUri = Uri.parse(uri);
  if (parsedUri.hasScheme) {
    if (parsedUri.scheme == 'package') {
      return AssetId(parsedUri.pathSegments.first,
          p.url.join('lib', p.url.joinAll(parsedUri.pathSegments.skip(1))));
    } else if (parsedUri.scheme == 'asset') {
      return AssetId(parsedUri.pathSegments.first,
          p.url.joinAll(parsedUri.pathSegments.skip(1)));
    }
    throw UnsupportedError(
        'Cannot resolve $uri; only "package" and "asset" schemes supported');
  }
  if (from == null) {
    throw ArgumentError.value(from, 'from',
        'An AssetId "from" must be specified to resolve a relative URI');
  }
  return AssetId(p.url.normalize(from.package),
      p.url.join(p.url.dirname(from.path), uri));
}