applyToPubspec method

void applyToPubspec(
  1. Map<String, String> map
)

套用至pubspec.yaml

Implementation

void applyToPubspec(Map<String, String> map) {
  final pubspecFile = File(pubspecYamlPath!);
  final allLine = pubspecFile.readAsLinesSync();

  final assetsRegex = RegExp('-\x20*$assetsPath(.+)');

  bool haveChange = false;

  for (int i = 0; i < allLine.length; i++) {
    final text = allLine[i];

    final match = assetsRegex.firstMatch(text);
    if (match != null && match.groupCount == 1) {
      haveChange = true;
      final relativePath = match.group(1)!;
      final obfuscateRelativePath =
      relativePath.split('/').map((e) => map[e] ?? e).join('/');

      final replaceText =
          '${text.substring(0, match.start)}- $assetsPath$obfuscateRelativePath';

      allLine[i] = replaceText;
    }
  }

  if (haveChange) {
    // 將替換好的文字寫回去
    pubspecFile.writeAsStringSync(allLine.join('\n'));
  }
}