downloadPackage method

Future<Directory> downloadPackage(
  1. String packageName,
  2. String version, {
  3. String? archiveUrl,
})

Download and extract a package archive to a temporary directory. Returns the path to the extracted package root.

Implementation

Future<Directory> downloadPackage(
  String packageName,
  String version, {
  String? archiveUrl,
}) async {
  final url =
      archiveUrl ??
      '$registryUrl/api/packages/$packageName/versions/$version/archive';
  final response = await _http.get(Uri.parse(url));
  if (response.statusCode != 200) {
    throw StateError(
      'Failed to download $packageName@$version: '
      '${response.statusCode} ${response.reasonPhrase}',
    );
  }

  final archive = GZipDecoder().decodeBytes(response.bodyBytes);
  final tarArchive = TarDecoder().decodeBytes(archive);

  final tempDir = await Directory.systemTemp.createTemp('ball_pub_');
  for (final file in tarArchive) {
    if (file.isFile) {
      final outFile = File('${tempDir.path}/${file.name}');
      await outFile.parent.create(recursive: true);
      await outFile.writeAsBytes(file.content as List<int>);
    }
  }
  return tempDir;
}