Skip to content

Instantly share code, notes, and snippets.

@ramyak-mehra
Created March 25, 2021 10:51
Show Gist options
  • Select an option

  • Save ramyak-mehra/fceb5529ffeb7a155b7be0f58e439dbd to your computer and use it in GitHub Desktop.

Select an option

Save ramyak-mehra/fceb5529ffeb7a155b7be0f58e439dbd to your computer and use it in GitHub Desktop.
import 'dart:io' as io;
import 'package:yaml/yaml.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
void main(List<String> args) async {
final httpClient = http.Client();
var results = [];
final listPackages = getPackages();
var futurePackages = listPackages.map<Future<void>>((p) async {
try {
var result = await _downloadFile(httpClient, p);
results.add(result);
} on Exception catch (e) {
print(e);
}
});
//log erros and also find if any package form result doesn't get downloaded
await Future.wait(futurePackages);
httpClient.close();
}
Future<DownloadResult> _downloadFile(
http.Client client, PackageInfo package) async {
final url =
'https://pub.dev/packages/${package.name}/versions/${package.version}.tar.gz';
try {
final request = await client.get(Uri.parse(url));
var packageFile = io.File('path_of_tarball');
await packageFile.writeAsBytes(request.bodyBytes);
//extract the package
//to specific location from the pub cache
return DownloadResult(package, true);
} catch (e) {
return DownloadResult(package, false);
}
}
List<PackageInfo> getPackages() {
var packages = <PackageInfo>[];
var file = io.File('pubspec.lock');
var yaml = file.readAsStringSync();
var map = loadYaml(yaml) as Map;
var decodedJMap = json.decode(json.encode(map)) as Map<String, dynamic>;
var map1 = decodedJMap['packages'] as Map<dynamic, dynamic>;
map1.forEach((key, value) {
var package = PackageInfo(key, value['version']);
packages.add(package);
});
return packages;
}
class PackageInfo {
final String name;
final String version;
PackageInfo(this.name, this.version);
}
class DownloadResult {
final PackageInfo package;
final bool completed;
DownloadResult(this.package, this.completed);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment