reduceDuplicates method

void reduceDuplicates()

Join together duplicate entries.

Implementation

void reduceDuplicates() {
  // The new list of entries.
  final List<Entry> newEntries = [];

  for (var entry in entries) {
    // The duplicate that comes before the current entry.
    Entry? prevEntry;

    try {
      prevEntry = newEntries.firstWhere((other) {
        // The msgid must be the same.
        if (entry.msgid != other.msgid) return false;

        // As well as the msgctxt.
        if (entry.msgctxt != other.msgctxt) return false;

        // And the plurals must match, or at least one of them must be null.
        if (entry.msgidPlural != other.msgidPlural &&
            entry.msgidPlural != null &&
            other.msgidPlural != null) {
          return false;
        }

        // And we don't join entries, that don't have msgstr empty.
        if (entry.msgstr.isNotEmpty || other.msgstr.isNotEmpty) return false;
        if (entry.msgstrList.isNotEmpty || other.msgstrList.isNotEmpty) {
          return false;
        }

        return true;
      });
    } on StateError {
      //
    }

    if (prevEntry == null) {
      newEntries.add(entry);
      continue;
    }

    prevEntry.translatorComment.addAll(entry.translatorComment);
    final translatorComment = prevEntry.translatorComment.toSet().toList();
    prevEntry.translatorComment.clear();
    prevEntry.translatorComment.addAll(translatorComment);

    prevEntry.extractedComment.addAll(entry.extractedComment);
    final extractedComment = prevEntry.extractedComment.toSet().toList();
    prevEntry.extractedComment.clear();
    prevEntry.extractedComment.addAll(extractedComment);

    prevEntry.references.addAll(entry.references);

    if (prevEntry.msgidPlural == null && entry.msgidPlural != null) {
      prevEntry.msgidPlural = entry.msgidPlural;
      prevEntry.msgstrList.clear();
      prevEntry.msgstrList.addAll(entry.msgstrList);
    }
  }

  entries.clear();
  entries.addAll(newEntries);
}