code: add side-by-side diff and merge-conflict resolver
- Commit
7c07ac1ec42c8f8c13736bdda9f4f52305f3e801- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-06 23:55 UTC (4 months ago)
- Parents
c139d14
Diff
code/src/main/java/com/vayunmathur/code/ui/DiffView.kt
diff --git a/code/src/main/java/com/vayunmathur/code/ui/DiffView.kt b/code/src/main/java/com/vayunmathur/code/ui/DiffView.ktnew file mode 100644index 0000000000..107c699cb4--- /dev/null+++ b/code/src/main/java/com/vayunmathur/code/ui/DiffView.kt@@ -0,0 +1,176 @@+package com.vayunmathur.code.ui++import androidx.compose.foundation.background+import androidx.compose.foundation.horizontalScroll+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.rememberScrollState+import androidx.compose.runtime.Composable+import androidx.compose.runtime.mutableStateListOf+import androidx.compose.runtime.remember+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.font.FontFamily+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.vayunmathur.code.R+import com.vayunmathur.code.util.DiffRow+import com.vayunmathur.code.util.DiffRowType+import com.vayunmathur.code.util.Resolution+import com.vayunmathur.code.util.parseConflicts+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton++private val MONO = TextStyle(fontFamily = FontFamily.Monospace, fontSize = 12.sp)++/** A side-by-side diff viewer: old on the left, new on the right, with add/remove tinting. */+@Composable+fun SideBySideDiffDialog(rows: List<DiffRow>, onDismiss: () -> Unit) {+ AlertDialog(+ onDismissRequest = onDismiss,+ title = { Text(stringResource(R.string.diff)) },+ text = {+ if (rows.isEmpty()) {+ Text(stringResource(R.string.no_changes), color = MaterialTheme.colorScheme.onSurfaceVariant)+ } else {+ LazyColumn(+ Modifier+ .fillMaxWidth()+ .heightIn(max = 460.dp)+ .horizontalScroll(rememberScrollState()),+ ) {+ items(rows) { row -> DiffRowView(row) }+ }+ }+ },+ confirmButton = {+ TextButton(onClick = onDismiss) { Text(stringResource(R.string.close)) }+ },+ )+}++@Composable+private fun DiffRowView(row: DiffRow) {+ if (row.type == DiffRowType.HUNK) {+ Text(+ text = row.text,+ style = MONO,+ color = MaterialTheme.colorScheme.primary,+ modifier = Modifier.fillMaxWidth().padding(vertical = 2.dp),+ )+ return+ }+ val removeBg = MaterialTheme.colorScheme.errorContainer+ val addBg = MaterialTheme.colorScheme.tertiaryContainer+ val leftText = if (row.type == DiffRowType.ADD) "" else row.text+ val rightText = if (row.type == DiffRowType.REMOVE) "" else row.text+ val leftBg = if (row.type == DiffRowType.REMOVE) removeBg else Color.Transparent+ val rightBg = if (row.type == DiffRowType.ADD) addBg else Color.Transparent+ Row(Modifier.fillMaxWidth()) {+ DiffCell(leftText, leftBg)+ Text(" ", style = MONO)+ DiffCell(rightText, rightBg)+ }+}++@Composable+private fun DiffCell(text: String, background: Color) {+ Text(+ text = text,+ style = MONO,+ color = MaterialTheme.colorScheme.onSurface,+ modifier = Modifier+ .width(260.dp)+ .background(background)+ .padding(horizontal = 4.dp),+ )+}++/**+ * A merge-conflict resolver: one card per conflict showing both sides, with an Ours/Theirs/Both+ * choice. Confirm applies the choices (in document order) back through the editor.+ */+@Composable+fun MergeResolverDialog(+ text: String,+ onResolve: (List<Resolution>) -> Unit,+ onDismiss: () -> Unit,+) {+ val conflicts = remember(text) { parseConflicts(text) }+ val choices = remember(conflicts.size) {+ mutableStateListOf<Resolution>().apply { repeat(conflicts.size) { add(Resolution.OURS) } }+ }++ AlertDialog(+ onDismissRequest = onDismiss,+ title = { Text(stringResource(R.string.resolve_conflicts)) },+ text = {+ if (conflicts.isEmpty()) {+ Text(+ stringResource(R.string.no_conflicts),+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ } else {+ LazyColumn(Modifier.fillMaxWidth().heightIn(max = 460.dp)) {+ items(conflicts.indices.toList()) { index ->+ ConflictCard(+ ours = conflicts[index].ours.joinToString("\n"),+ theirs = conflicts[index].theirs.joinToString("\n"),+ selected = choices[index],+ onSelect = { choices[index] = it },+ )+ }+ }+ }+ },+ confirmButton = {+ TextButton(+ onClick = { onResolve(choices.toList()); onDismiss() },+ enabled = conflicts.isNotEmpty(),+ ) { Text(stringResource(R.string.apply)) }+ },+ dismissButton = {+ TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }+ },+ )+}++@Composable+private fun ConflictCard(+ ours: String,+ theirs: String,+ selected: Resolution,+ onSelect: (Resolution) -> Unit,+) {+ Column(Modifier.fillMaxWidth().padding(vertical = 6.dp)) {+ Text(stringResource(R.string.conflict_ours), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.primary)+ Text(ours, style = MONO, color = MaterialTheme.colorScheme.onSurface)+ Text(stringResource(R.string.conflict_theirs), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.primary)+ Text(theirs, style = MONO, color = MaterialTheme.colorScheme.onSurface)+ Row(Modifier.fillMaxWidth()) {+ ChoiceButton(stringResource(R.string.conflict_keep_ours), selected == Resolution.OURS) { onSelect(Resolution.OURS) }+ ChoiceButton(stringResource(R.string.conflict_keep_theirs), selected == Resolution.THEIRS) { onSelect(Resolution.THEIRS) }+ ChoiceButton(stringResource(R.string.conflict_keep_both), selected == Resolution.BOTH) { onSelect(Resolution.BOTH) }+ }+ }+}++@Composable+private fun ChoiceButton(label: String, selected: Boolean, onClick: () -> Unit) {+ TextButton(onClick = onClick) {+ Text(+ label,+ color = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+}
code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt
diff --git a/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt b/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.ktindex ed5b6fbc30..5a353720eb 100644--- a/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt+++ b/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt@@ -147,6 +147,7 @@ fun EditorScreen( var showQuickOpen by remember { mutableStateOf(false) } var showPalette by remember { mutableStateOf(false) } var showOutline by remember { mutableStateOf(false) }+ var showMergeResolver by remember { mutableStateOf(false) } var showExitGuard by remember { mutableStateOf(false) } val anyDirty = state.tabs.any { it.isDirty } @@ -235,6 +236,7 @@ fun EditorScreen( }, onOpenPalette = { showPalette = true }, onOpenOutline = { showOutline = true },+ onResolveConflicts = { showMergeResolver = true }, ) HorizontalDivider() if (tab.changedOnDisk) {@@ -284,6 +286,7 @@ fun EditorScreen( showQuickOpen = true }, onOutline = { showOutline = true },+ onResolveConflicts = { showMergeResolver = true }, onOpenSearch = onOpenSearch, onOpenGit = onOpenGit, onOpenTerminal = onOpenTerminal,@@ -319,6 +322,14 @@ fun EditorScreen( onDismiss = { showOutline = false }, ) }+ val conflictTab = state.currentTab+ if (showMergeResolver && conflictTab != null) {+ MergeResolverDialog(+ text = conflictTab.value.text,+ onResolve = { actions.resolveConflicts(it) },+ onDismiss = { showMergeResolver = false },+ )+ } if (showExitGuard) { AlertDialog( onDismissRequest = { showExitGuard = false },@@ -438,6 +449,7 @@ private fun EditorToolbar( onOpenQuickOpen: () -> Unit = {}, onOpenPalette: () -> Unit = {}, onOpenOutline: () -> Unit = {},+ onResolveConflicts: () -> Unit = {}, ) { val tab = state.currentTab ?: return Row(@@ -470,6 +482,7 @@ private fun EditorToolbar( Item(text = stringResource(R.string.terminal)) { onOpenTerminal() } Item(text = stringResource(R.string.preview)) { onOpenPreview() } Item(text = stringResource(R.string.format_document)) { actions.formatDocument() }+ Item(text = stringResource(R.string.resolve_conflicts)) { onResolveConflicts() } } Spacer(Modifier.width(8.dp)) Text(@@ -544,6 +557,7 @@ private fun editorCommands( onGoToLine: () -> Unit, onQuickOpen: () -> Unit, onOutline: () -> Unit,+ onResolveConflicts: () -> Unit, onOpenSearch: () -> Unit, onOpenGit: () -> Unit, onOpenTerminal: () -> Unit,@@ -564,6 +578,7 @@ private fun editorCommands( PickerItem(stringResource(R.string.move_line_down)) { actions.moveLineDown() }, PickerItem(stringResource(R.string.delete_line)) { actions.deleteLine() }, PickerItem(stringResource(R.string.format_document)) { actions.formatDocument() },+ PickerItem(stringResource(R.string.resolve_conflicts)) { onResolveConflicts() }, PickerItem(stringResource(R.string.soft_wrap)) { actions.toggleSoftWrap() }, PickerItem(stringResource(R.string.undo)) { actions.undo() }, PickerItem(stringResource(R.string.redo)) { actions.redo() },
code/src/main/java/com/vayunmathur/code/ui/GitPage.kt
diff --git a/code/src/main/java/com/vayunmathur/code/ui/GitPage.kt b/code/src/main/java/com/vayunmathur/code/ui/GitPage.ktindex 93af3b3990..32bbb1e324 100644--- a/code/src/main/java/com/vayunmathur/code/ui/GitPage.kt+++ b/code/src/main/java/com/vayunmathur/code/ui/GitPage.kt@@ -38,6 +38,7 @@ import com.vayunmathur.library.ui.IconAdd import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.IconClose import com.vayunmathur.library.ui.IconMerge+import com.vayunmathur.library.ui.IconMoreVert import com.vayunmathur.library.ui.IconRefresh import com.vayunmathur.library.ui.IconRemove import com.vayunmathur.library.ui.MaterialTheme@@ -100,6 +101,10 @@ fun GitPage(viewModel: EditorViewModel, backStack: NavBackStack<Route>) { viewModel.gitDiff?.let { diff -> DiffDialog(diff = diff, onDismiss = { viewModel.clearGitDiff() }) }++ viewModel.gitDiffRows?.let { rows ->+ SideBySideDiffDialog(rows = rows, onDismiss = { viewModel.clearDiffRows() })+ } } @Composable@@ -249,6 +254,10 @@ private fun ChangeList(title: String, paths: List<String>, staged: Boolean, view verticalAlignment = Alignment.CenterVertically, ) { Text(path, Modifier.weight(1f), maxLines = 1, overflow = TextOverflow.Ellipsis)+ OverflowMenu(icon = { IconMoreVert() }) {+ Item(text = stringResource(R.string.diff)) { viewModel.loadGitDiff(path, staged) }+ Item(text = stringResource(R.string.side_by_side)) { viewModel.loadSideBySideDiff(path, staged) }+ } if (staged) { IconButton(onClick = { viewModel.gitUnstage(path) }) { IconRemove() } } else {
code/src/main/java/com/vayunmathur/code/util/CodeUiContract.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/CodeUiContract.kt b/code/src/main/java/com/vayunmathur/code/util/CodeUiContract.ktindex 3860478f53..b0ffee1d03 100644--- a/code/src/main/java/com/vayunmathur/code/util/CodeUiContract.kt+++ b/code/src/main/java/com/vayunmathur/code/util/CodeUiContract.kt@@ -148,6 +148,9 @@ interface CodeActions { /** Pretty-print the current file if it is JSON or XML (single undo step). */ fun formatDocument() {} + /** Replace the merge-conflict blocks in the current file with the chosen sides (single undo). */+ fun resolveConflicts(resolutions: List<Resolution>) {}+ /** Move the selection without recording an undo step (used by find navigation). */ fun setSelection(range: TextRange) {}
code/src/main/java/com/vayunmathur/code/util/DiffModel.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/DiffModel.kt b/code/src/main/java/com/vayunmathur/code/util/DiffModel.ktnew file mode 100644index 0000000000..096b7ab7e4--- /dev/null+++ b/code/src/main/java/com/vayunmathur/code/util/DiffModel.kt@@ -0,0 +1,59 @@+package com.vayunmathur.code.util++/** The role of a diff row in a side-by-side view. */+enum class DiffRowType { CONTEXT, ADD, REMOVE, HUNK }++/**+ * One aligned row of a side-by-side diff. [leftNumber]/[rightNumber] are 1-based line numbers on the+ * old/new sides (null when the row does not exist on that side). [HUNK] rows carry the `@@` header.+ */+data class DiffRow(+ val type: DiffRowType,+ val leftNumber: Int?,+ val rightNumber: Int?,+ val text: String,+)++/**+ * Parses a unified diff (as produced by [GitRepo.diff]) into aligned rows for a two-column view.+ * Pure and unit-tested: metadata before the first hunk is skipped, and inside a hunk each line is+ * classified strictly by its leading character so removed lines beginning with `-` are not mistaken+ * for file headers.+ */+fun parseUnifiedDiff(diff: String): List<DiffRow> {+ val rows = ArrayList<DiffRow>()+ val header = Regex("^@@ -(\\d+)(?:,\\d+)? \\+(\\d+)(?:,\\d+)? @@")+ var oldLine = 0+ var newLine = 0+ var inHunk = false++ for (raw in diff.split("\n")) {+ when {+ raw.startsWith("@@") -> {+ header.find(raw)?.let {+ oldLine = it.groupValues[1].toInt()+ newLine = it.groupValues[2].toInt()+ }+ inHunk = true+ rows.add(DiffRow(DiffRowType.HUNK, null, null, raw))+ }+ raw.startsWith("diff ") -> inHunk = false // start of the next file section+ !inHunk -> Unit // skip index/---/+++/new file/etc. before the first hunk+ raw.startsWith("+") -> {+ rows.add(DiffRow(DiffRowType.ADD, null, newLine, raw.substring(1)))+ newLine+++ }+ raw.startsWith("-") -> {+ rows.add(DiffRow(DiffRowType.REMOVE, oldLine, null, raw.substring(1)))+ oldLine+++ }+ raw.startsWith(" ") -> {+ rows.add(DiffRow(DiffRowType.CONTEXT, oldLine, newLine, raw.substring(1)))+ oldLine+++ newLine+++ }+ // "\ No newline at end of file" and blank trailing lines fall through and are ignored.+ }+ }+ return rows+}
code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt b/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.ktindex af3875685b..446ec07375 100644--- a/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt+++ b/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt@@ -187,6 +187,8 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), private set var gitDiff by mutableStateOf<String?>(null) private set+ var gitDiffRows by mutableStateOf<List<DiffRow>?>(null)+ private set private val _gitUsername = mutableStateOf("") val gitUsername: String get() = _gitUsername.value@@ -756,6 +758,20 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), } } + /** Loads the side-by-side (aligned rows) diff for [path] into [gitDiffRows]. */+ fun loadSideBySideDiff(path: String, staged: Boolean) {+ val dir = rootDir ?: return+ viewModelScope.launch {+ gitDiffRows = runCatching {+ withContext(Dispatchers.IO) { GitRepo.structuredDiff(dir, path, staged) }+ }.getOrDefault(emptyList())+ }+ }++ fun clearDiffRows() {+ gitDiffRows = null+ }+ fun clearGitDiff() { gitDiff = null }@@ -872,6 +888,15 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), if (autoSave) scheduleAutoSave() } + override fun resolveConflicts(resolutions: List<Resolution>) {+ val tab = currentTab ?: return+ val resolved = applyResolutions(tab.value.text, resolutions)+ if (resolved == tab.value.text) return+ tab.pushUndo(tab.value)+ tab.value = TextFieldValue(resolved, TextRange(resolved.length))+ if (autoSave) scheduleAutoSave()+ }+ /** Moves the caret to the start of [line] (1-based), without recording an undo step. */ override fun goToLine(line: Int) { val tab = currentTab ?: return
code/src/main/java/com/vayunmathur/code/util/GitRepo.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/GitRepo.kt b/code/src/main/java/com/vayunmathur/code/util/GitRepo.ktindex cbd7eb9b04..2e20012ecd 100644--- a/code/src/main/java/com/vayunmathur/code/util/GitRepo.kt+++ b/code/src/main/java/com/vayunmathur/code/util/GitRepo.kt@@ -104,6 +104,10 @@ object GitRepo { } } + /** The [diff] for [path] parsed into aligned rows for the side-by-side viewer. */+ fun structuredDiff(dir: File, path: String, staged: Boolean): List<DiffRow> =+ parseUnifiedDiff(diff(dir, path, staged))+ fun branches(dir: File): List<String> = withRepo(dir) { git -> git.branchList().call().map { it.name.removePrefix(Constants.R_HEADS) } }
code/src/main/java/com/vayunmathur/code/util/MergeConflicts.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/MergeConflicts.kt b/code/src/main/java/com/vayunmathur/code/util/MergeConflicts.ktnew file mode 100644index 0000000000..f78193da27--- /dev/null+++ b/code/src/main/java/com/vayunmathur/code/util/MergeConflicts.kt@@ -0,0 +1,104 @@+package com.vayunmathur.code.util++/** How a single merge conflict should be resolved. */+enum class Resolution { OURS, THEIRS, BOTH }++/**+ * One Git merge conflict block. [startLine]/[endLine] are 0-based, inclusive line indices spanning+ * the `<<<<<<<` … `>>>>>>>` markers; [ours] is the current-branch side, [theirs] the incoming side.+ */+data class Conflict(+ val startLine: Int,+ val endLine: Int,+ val ours: List<String>,+ val theirs: List<String>,+)++private const val OURS_MARKER = "<<<<<<<"+private const val SEPARATOR_MARKER = "======="+private const val THEIRS_MARKER = ">>>>>>>"++/**+ * Pure detection + resolution of Git merge-conflict markers. Kept out of the UI so both are+ * unit-tested directly.+ */++/** Finds every well-formed conflict block in [text]. Malformed/unterminated blocks are ignored. */+fun parseConflicts(text: String): List<Conflict> {+ val lines = text.split("\n")+ val out = ArrayList<Conflict>()+ var i = 0+ while (i < lines.size) {+ if (!lines[i].startsWith(OURS_MARKER)) {+ i+++ continue+ }+ val start = i+ var sep = -1+ var end = -1+ var j = i + 1+ while (j < lines.size) {+ when {+ sep == -1 && lines[j].startsWith(SEPARATOR_MARKER) -> sep = j+ lines[j].startsWith(THEIRS_MARKER) -> {+ end = j+ break+ }+ lines[j].startsWith(OURS_MARKER) -> break // a new conflict started; this one is malformed+ }+ j+++ }+ if (sep != -1 && end != -1) {+ out.add(+ Conflict(+ startLine = start,+ endLine = end,+ ours = lines.subList(start + 1, sep).toList(),+ theirs = lines.subList(sep + 1, end).toList(),+ ),+ )+ i = end + 1+ } else {+ i = start + 1+ }+ }+ return out+}++/**+ * Rewrites [text], replacing each conflict block with the chosen side. [resolutions] is applied in+ * document order; if it is shorter than the number of conflicts, the remaining blocks are left+ * untouched. [Resolution.BOTH] keeps ours followed by theirs.+ */+fun applyResolutions(text: String, resolutions: List<Resolution>): String {+ val conflicts = parseConflicts(text)+ if (conflicts.isEmpty()) return text+ val lines = text.split("\n")+ val out = ArrayList<String>(lines.size)+ var i = 0+ var ci = 0+ while (i < lines.size) {+ val conflict = conflicts.getOrNull(ci)+ if (conflict != null && i == conflict.startLine) {+ val resolution = resolutions.getOrNull(ci)+ if (resolution == null) {+ // No choice supplied: keep the original block verbatim.+ out.addAll(lines.subList(conflict.startLine, conflict.endLine + 1))+ } else {+ out.addAll(+ when (resolution) {+ Resolution.OURS -> conflict.ours+ Resolution.THEIRS -> conflict.theirs+ Resolution.BOTH -> conflict.ours + conflict.theirs+ },+ )+ }+ i = conflict.endLine + 1+ ci+++ } else {+ out.add(lines[i])+ i+++ }+ }+ return out.joinToString("\n")+}
code/src/main/res/values/strings.xml
diff --git a/code/src/main/res/values/strings.xml b/code/src/main/res/values/strings.xmlindex 80ac39d08a..60f34aefc3 100644--- a/code/src/main/res/values/strings.xml+++ b/code/src/main/res/values/strings.xml@@ -113,4 +113,13 @@ <string name="language">Language</string> <string name="go_to_symbol">Go to symbol</string> <string name="go_to_symbol_hint">Type a symbol name</string>+ <string name="side_by_side">Side by side</string>+ <string name="resolve_conflicts">Resolve conflicts</string>+ <string name="no_conflicts">No merge conflicts in this file.</string>+ <string name="apply">Apply</string>+ <string name="conflict_ours">Current (ours)</string>+ <string name="conflict_theirs">Incoming (theirs)</string>+ <string name="conflict_keep_ours">Ours</string>+ <string name="conflict_keep_theirs">Theirs</string>+ <string name="conflict_keep_both">Both</string> </resources>
code/src/test/java/com/vayunmathur/code/util/DiffModelTest.kt
diff --git a/code/src/test/java/com/vayunmathur/code/util/DiffModelTest.kt b/code/src/test/java/com/vayunmathur/code/util/DiffModelTest.ktnew file mode 100644index 0000000000..3100e25473--- /dev/null+++ b/code/src/test/java/com/vayunmathur/code/util/DiffModelTest.kt@@ -0,0 +1,63 @@+package com.vayunmathur.code.util++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** Unit tests for the pure unified-diff parser. */+class DiffModelTest {++ private val sample = """+ diff --git a/f.txt b/f.txt+ index 111..222 100644+ --- a/f.txt+ +++ b/f.txt+ @@ -1,3 +1,3 @@+ context+ -old line+ +new line+ tail+ """.trimIndent()++ @Test+ fun skipsMetadataBeforeHunk() {+ val rows = parseUnifiedDiff(sample)+ assertTrue(rows.none { it.text.startsWith("diff ") || it.text.startsWith("index ") })+ assertEquals(DiffRowType.HUNK, rows.first().type)+ }++ @Test+ fun classifiesRowsAndLineNumbers() {+ val rows = parseUnifiedDiff(sample).filter { it.type != DiffRowType.HUNK }+ assertEquals(DiffRowType.CONTEXT, rows[0].type)+ assertEquals(1, rows[0].leftNumber)+ assertEquals(1, rows[0].rightNumber)++ assertEquals(DiffRowType.REMOVE, rows[1].type)+ assertEquals("old line", rows[1].text)+ assertEquals(2, rows[1].leftNumber)+ assertEquals(null, rows[1].rightNumber)++ assertEquals(DiffRowType.ADD, rows[2].type)+ assertEquals("new line", rows[2].text)+ assertEquals(null, rows[2].leftNumber)+ assertEquals(2, rows[2].rightNumber)++ assertEquals(DiffRowType.CONTEXT, rows[3].type)+ assertEquals(3, rows[3].leftNumber)+ assertEquals(3, rows[3].rightNumber)+ }++ @Test+ fun removedLineStartingWithDashIsNotAHeader() {+ val diff = "@@ -1,1 +1,1 @@\n--- a dashed removed line\n+kept"+ val rows = parseUnifiedDiff(diff)+ val removed = rows.first { it.type == DiffRowType.REMOVE }+ assertEquals("-- a dashed removed line", removed.text)+ }++ @Test+ fun emptyDiffYieldsNoRows() {+ assertTrue(parseUnifiedDiff("").isEmpty())+ }+}
code/src/test/java/com/vayunmathur/code/util/MergeConflictsTest.kt
diff --git a/code/src/test/java/com/vayunmathur/code/util/MergeConflictsTest.kt b/code/src/test/java/com/vayunmathur/code/util/MergeConflictsTest.ktnew file mode 100644index 0000000000..916d123058--- /dev/null+++ b/code/src/test/java/com/vayunmathur/code/util/MergeConflictsTest.kt@@ -0,0 +1,78 @@+package com.vayunmathur.code.util++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** Unit tests for the pure merge-conflict parser and resolver. */+class MergeConflictsTest {++ private val conflicted = buildString {+ append("line before\n")+ append("<<<<<<< HEAD\n")+ append("our change\n")+ append("=======\n")+ append("their change\n")+ append(">>>>>>> branch\n")+ append("line after")+ }++ @Test+ fun parsesSingleConflict() {+ val conflicts = parseConflicts(conflicted)+ assertEquals(1, conflicts.size)+ assertEquals(listOf("our change"), conflicts[0].ours)+ assertEquals(listOf("their change"), conflicts[0].theirs)+ assertEquals(1, conflicts[0].startLine)+ assertEquals(5, conflicts[0].endLine)+ }++ @Test+ fun noConflictsInCleanText() {+ assertTrue(parseConflicts("just\nsome\nlines").isEmpty())+ }++ @Test+ fun resolvesOurs() {+ val result = applyResolutions(conflicted, listOf(Resolution.OURS))+ assertEquals("line before\nour change\nline after", result)+ }++ @Test+ fun resolvesTheirs() {+ val result = applyResolutions(conflicted, listOf(Resolution.THEIRS))+ assertEquals("line before\ntheir change\nline after", result)+ }++ @Test+ fun resolvesBothKeepsOursThenTheirs() {+ val result = applyResolutions(conflicted, listOf(Resolution.BOTH))+ assertEquals("line before\nour change\ntheir change\nline after", result)+ }++ @Test+ fun handlesMultipleConflictsIndependently() {+ val text = buildString {+ append("<<<<<<< HEAD\n")+ append("a1\n")+ append("=======\n")+ append("b1\n")+ append(">>>>>>> x\n")+ append("middle\n")+ append("<<<<<<< HEAD\n")+ append("a2\n")+ append("=======\n")+ append("b2\n")+ append(">>>>>>> y")+ }+ assertEquals(2, parseConflicts(text).size)+ val result = applyResolutions(text, listOf(Resolution.OURS, Resolution.THEIRS))+ assertEquals("a1\nmiddle\nb2", result)+ }++ @Test+ fun missingChoiceLeavesBlockUntouched() {+ val result = applyResolutions(conflicted, emptyList())+ assertEquals(conflicted, result)+ }+}