getResolvedPackageUris function

Map<String, Uri> getResolvedPackageUris(
  1. Uri packagesFileUri, {
  2. Uri? relativeTo,
})

Reads .packages file from packagesFileUri and returns map of package name to its location on disk.

If locations on disk are relative Uris, they are resolved by relativeTo. relativeTo defaults to the CWD.

Implementation

Map<String, Uri> getResolvedPackageUris(Uri packagesFileUri,
    {Uri? relativeTo}) {
  relativeTo ??= Directory.current.uri;

  final packagesFile = File.fromUri(packagesFileUri);
  if (!packagesFile.existsSync()) {
    throw StateError(
        "No .packages file found at '${packagesFileUri}'. Run 'pub get' in directory '${packagesFileUri.resolve("../")}'.");
  }
  return Map.fromEntries(packagesFile
      .readAsStringSync()
      .split("\n")
      .where((s) => !s.trimLeft().startsWith("#"))
      .where((s) => s.trim().isNotEmpty)
      .map((s) {
    final packageName = s.substring(0, s.indexOf(":"));
    final uri = Uri.parse(s.substring("$packageName:".length));

    if (uri.isAbsolute) {
      return MapEntry(packageName, Directory.fromUri(uri).parent.uri);
    }

    return MapEntry(
        packageName,
        Directory.fromUri(relativeTo!.resolveUri(uri).normalizePath())
            .parent
            .uri);
  }));
}