injectNativeAssetsPubspecDeps function

bool injectNativeAssetsPubspecDeps(
  1. String pubspecPath, {
  2. Map<String, String>? deps,
})

Adds any missing deps (default nativeAssetsHookDeps) under the dependencies: block of the pubspec at pubspecPath. Returns true if the file was changed. The external-cmake hook passes only {hooks, code_assets} (it has no CBuilder, so native_toolchain_c — which pins hooks ^2.x — must not be forced onto a hooks ^1.x plugin).

Implementation

bool injectNativeAssetsPubspecDeps(String pubspecPath, {Map<String, String>? deps}) {
  final f = File(pubspecPath);
  if (!f.existsSync()) return false;
  var content = f.readAsStringSync();
  final missing = (deps ?? nativeAssetsHookDeps).entries
      .where((e) => !RegExp('^  ${e.key}:', multiLine: true).hasMatch(content))
      .toList();
  if (missing.isEmpty) return false;
  final depsMatch = RegExp(r'^dependencies:[ \t]*$', multiLine: true).firstMatch(content);
  if (depsMatch == null) return false;
  final insert = '\n${missing.map((e) => '  ${e.key}: ${e.value}').join('\n')}';
  content = content.replaceRange(depsMatch.end, depsMatch.end, insert);
  f.writeAsStringSync(content);
  return true;
}