mergeContent method
Merge two versions of a memory file.
Implementation
String mergeContent(String local, String remote, {String? base}) {
final localSections = MemoryParser.parse(local);
final remoteSections = MemoryParser.parse(remote);
final baseSections = base != null
? MemoryParser.parse(base)
: <MemorySection>[];
final mergedSections = <MemorySection>[];
final processedHeadings = <String>{};
// Process local sections.
for (final ls in localSections) {
final rs = remoteSections
.where((s) => s.heading == ls.heading)
.firstOrNull;
final bs = baseSections.where((s) => s.heading == ls.heading).firstOrNull;
processedHeadings.add(ls.heading);
if (rs == null) {
// Only in local — keep if new (not in base) or if modified.
if (bs == null || ls.content != bs.content) {
mergedSections.add(ls);
}
} else if (ls.content == rs.content) {
// Same in both — keep.
mergedSections.add(ls);
} else if (bs != null) {
// Three-way merge.
if (ls.content == bs.content) {
// Only remote changed.
mergedSections.add(
MemorySection(
heading: ls.heading,
level: ls.level,
content: rs.content,
),
);
} else if (rs.content == bs.content) {
// Only local changed.
mergedSections.add(ls);
} else {
// Both changed — concatenate with markers.
mergedSections.add(
MemorySection(
heading: ls.heading,
level: ls.level,
content:
'${ls.content}\n\n<!-- Remote changes -->\n${rs.content}',
),
);
}
} else {
// No base — concatenate.
mergedSections.add(
MemorySection(
heading: ls.heading,
level: ls.level,
content: '${ls.content}\n\n${rs.content}',
),
);
}
}
// Add remote-only sections.
for (final rs in remoteSections) {
if (!processedHeadings.contains(rs.heading)) {
mergedSections.add(rs);
}
}
return MemoryParser.build(mergedSections);
}