generateOrMerge static method

void generateOrMerge({
  1. required Map<String, String> newStrings,
  2. required String filePath,
  3. String locale = 'en',
  4. bool suggestMeaningfulKeys = true,
  5. String keyFormat = 'camelCase',
})

Generate or merge ARB file, avoid key duplication, suggest meaningful keys, support custom key format

Implementation

static void generateOrMerge({
  required Map<String, String> newStrings,
  required String filePath,
  String locale = 'en',
  bool suggestMeaningfulKeys = true,
  String keyFormat = 'camelCase', // Options: snake_case, camelCase, dot.case
}) {
  final file = File(filePath);

  // Create directory if it doesn't exist
  final directory = file.parent;
  if (!directory.existsSync()) {
    directory.createSync(recursive: true);
  }

  Map<String, dynamic> arbData = {};
  bool fileExists = file.existsSync();

  if (fileExists) {
    try {
      arbData = jsonDecode(file.readAsStringSync());
      print('📝 Merging with existing ARB file: ${file.path}');
    } catch (e) {
      print('âš ī¸ Error reading existing ARB file: $e');
      print('Creating a new ARB file instead.');
      fileExists = false;
    }
  }

  int newAdded = 0;

  for (final entry in newStrings.entries) {
    final value = entry.value;

    // Always respect the original key if provided
    String key = entry.key;

    print('📍 Processing value: $value for key: $key');

    // Convert Dart interpolation to ICU format first
    String icuValue = _convertToIcuInterpolation(value);

    bool needsPluralization =
        icuValue.contains('(s)') || icuValue.contains('{count}');
    dynamic processedValue = needsPluralization
        ? _generatePluralOrGenderValue(icuValue)
        : (_needsPluralOrGenderSupport(icuValue)
            ? _generatePluralOrGenderValue(icuValue)
            : icuValue);

    print('âœī¸ Generated value: $processedValue');

    // Always write the value since we know it's new or an update
    arbData[key] = processedValue;
    newAdded++;
  }

  print('đŸ“Ļ Final ARB data: $arbData');
  // Add context notes and save
  arbData = addContextNotes(arbData);
  var arbContent = JsonEncoder.withIndent('  ').convert(arbData);
  file.writeAsStringSync(arbContent);

  if (newAdded > 0) {
    print('✅ Added $newAdded new strings to ${file.path}');
  } else {
    print('â„šī¸ No new strings added to ${file.path}');
  }
}