fetchNativeLibraries function

Future<void> fetchNativeLibraries({
  1. String? targetDir,
})

Downloads native libraries from GitHub releases with manifest support

Implementation

Future<void> fetchNativeLibraries({String? targetDir}) async {
  final version = await detectVersion();
  final packageName = await detectPackageName();

  // Determine the target directory (where we'll download the libraries)
  String nativePath;

  if (targetDir != null) {
    // If a specific target directory is provided, use it (e.g., from flutter_lmdb2)
    nativePath = targetDir;
  } else {
    // No target provided - we need to determine the dart_lmdb2 package directory
    // Use package URI resolution to find the dart_lmdb2 package location
    try {
      final packageUri = Uri.parse('package:dart_lmdb2/lmdb.dart');
      final resolvedUri = await Isolate.resolvePackageUri(packageUri);

      if (resolvedUri == null) {
        throw Exception('Could not resolve dart_lmdb2 package location');
      }

      // Get the package root (two levels up from lib/lmdb.dart)
      // Use path.dirname for platform-independent path handling
      final libDir = path.dirname(resolvedUri.toFilePath());
      final packageRoot = path.dirname(libDir);
      nativePath = path.join(packageRoot, 'lib', 'src', 'native');

      print('Resolved dart_lmdb2 package at: $packageRoot');
    } catch (e) {
      // Fallback to current directory if package resolution fails
      print('Warning: Could not resolve package path: $e');
      print('Falling back to local directory');
      nativePath = path.join('lib', 'src', 'native');
    }
  }

  print('Fetching native libraries for $packageName v$version...');
  print('Target directory: $nativePath');

  // Check if libraries already exist with correct version
  if (await checkVersionMatch(nativePath, version)) {
    print('Native libraries are up to date (v$version).');
    return;
  }

  // Construct the tag name and asset name
  // Always download from dart_lmdb2 releases, even if called from flutter_lmdb2
  final tagName = 'dart_lmdb2_v$version';
  final assetName = 'dart_lmdb2-$version-native-libs.tar.gz';

  // Download the tarball
  final tarballPath = path.join(Directory.systemTemp.path, assetName);
  await downloadReleaseTarball('dart_lmdb2', version, tagName, tarballPath);

  // Extract to target directory
  await extractTarball(tarballPath, nativePath);

  // Verify checksums
  await verifyChecksums(nativePath);

  // Clean up
  File(tarballPath).deleteSync();

  print('Native libraries successfully downloaded and extracted!');
}