addNativeAssets function

Future<void> addNativeAssets(
  1. BuildInput input,
  2. BuildOutputBuilder output,
  3. List<NativeLibrary> libraries
)

Fetch (or find) the C library for the target of input, and declare each of libraries as a bundled code asset of its package.

Implementation

Future<void> addNativeAssets(BuildInput input, BuildOutputBuilder output, List<NativeLibrary> libraries) async {
  if (!input.config.buildCodeAssets) return;
  // the browser tests (`dart test -p chrome`, `bb dart-web`) still run this hook for the host and need no native library: the file they leave declares none
  // (a hook sees no environment variable of ours, so the signal is a file in the package; it is not under version control)
  if (File.fromUri(input.packageRoot.resolve('.dart_tool/emon_native_skip')).existsSync()) return;
  final code = input.config.code;
  final triple = targetTriple(code);
  if (triple == null) return;
  final root = await resolveNativeSource(input, output, triple);
  for (final lib in libraries) {
    final dirs = [lib.directory ?? 'lib', 'lib', 'bin', '.'];
    final names = lib.fileName != null
        ? [lib.fileName!]
        : [_fileName(code.targetOS, lib.stem), if (code.targetOS == OS.windows) 'lib${lib.stem}.dll'];
    File? found;
    for (final d in dirs) {
      for (final n in names) {
        final f = File(p.join(root, d, n));
        if (f.existsSync()) {
          found = f;
          break;
        }
      }
      if (found != null) break;
    }
    if (found == null) {
      if (lib.optional) continue;
      throw StateError('the archive for $triple has no ${names.first} (looked in ${dirs.join(', ')} of $root)');
    }
    output.assets.code.add(CodeAsset(
      package: input.packageName,
      name: lib.assetName,
      linkMode: DynamicLoadingBundled(),
      file: found.uri,
    ));
    output.dependencies.add(found.uri);
  }
}