Skip to content

CSV Diff — Kotlin source

Diff two CSVs by a key column: rows added, removed and changed, with the differing columns named. Quoted cells with commas, quotes and newlines are handled. Runs locally with a shareable link.

This is the Kotlin implementation — the same logic the interactive tool runs, in a shareable, citable form.

// csv-diff — key-based row diff of two RFC-4180 CSVs. Kotlin port (canonical
// TS: src/lib/csv-diff.ts; Go twin: cli/csv-diff). Mirrors the sibling
// ports: an RFC-4180 parser (quoted cells with embedded commas, quotes and
// newlines; CR dropped; a trailing field without a newline still completes
// its row) with blank single-cell rows dropped as trailing noise, strict
// per-side validation (empty CSV, duplicate columns, ragged rows, duplicate
// keys — the pinned error strings, carried as strings, never exceptions out
// of the entry point), then a key-based diff over the sorted key union:
// added/removed rows and changed rows whose differing column names come out
// sorted.

/** One row of the diff result; before/after hold the full records. */
data class RowDiff(
    val key: String,
    val type: String, // "added" | "removed" | "changed"
    val columns: List<String>? = null, // differing names on "changed", sorted
    val before: Map<String, String>? = null,
    val after: Map<String, String>? = null,
)
data class DiffResult(val rows: List<RowDiff>, val same: Boolean, val error: String?)

/** RFC 4180 parser mirroring the TS loop: lenient quotes, CR dropped, a
 *  trailing field without a newline still completes its row. */
fun csvToRows(csv: String): List<List<String>> {
    val rows = mutableListOf<List<String>>()
    val field = StringBuilder()
    var row = mutableListOf<String>()
    var inQ = false
    var i = 0
    while (i < csv.length) {
        val ch = csv[i]
        if (inQ) {
            if (ch == '"') {
                if (i + 1 < csv.length && csv[i + 1] == '"') { field.append('"'); i++ } else inQ = false
            } else field.append(ch)
        } else when {
            ch == '"' -> inQ = true
            ch == ',' -> { row.add(field.toString()); field.setLength(0) }
            ch == '\n' -> { row.add(field.toString()); field.setLength(0); rows.add(row); row = mutableListOf() }
            ch != '\r' -> field.append(ch)
        }
        i++
    }
    if (field.isNotEmpty() || row.isNotEmpty()) { row.add(field.toString()); rows.add(row) }
    return rows
}

/** Blank single-cell rows are trailing noise to a diff, not data. */
fun parseCsv(text: String): List<List<String>> =
    csvToRows(text).filterNot { it.size == 1 && it[0].isEmpty() }

/** Strict per-side validation → header to records; IllegalStateException
 *  carries the pinned strings (empty CSV, duplicate column, ragged row). */
fun toRecords(rows: List<List<String>>, label: String): Pair<List<String>, List<Map<String, String>>> {
    if (rows.isEmpty()) throw IllegalStateException("$label: empty CSV")
    val header = rows[0]
    header.forEachIndexed { c, name ->
        if (header.subList(0, c).contains(name)) throw IllegalStateException("$label: duplicate column \"$name\"")
    }
    val records = mutableListOf<Map<String, String>>()
    for (r in 1 until rows.size) {
        if (rows[r].size != header.size)
            throw IllegalStateException("$label: row ${r + 1} has ${rows[r].size} cells, expected ${header.size}")
        records.add(header.zip(rows[r]).toMap())
    }
    return header to records
}

/** Diff two CSVs by key column (default: the first header column). */
fun csvDiff(leftRaw: String, rightRaw: String, keyColumn: String? = null): DiffResult {
    if (leftRaw.isBlank() || rightRaw.isBlank()) return DiffResult(emptyList(), false, "Both inputs are required")
    return try {
        val (lheader, lrecs) = toRecords(parseCsv(leftRaw), "Left")
        val (rheader, rrecs) = toRecords(parseCsv(rightRaw), "Right")
        val key = keyColumn ?: lheader[0]
        if (key !in lheader) return DiffResult(emptyList(), false, "Left: no key column \"$key\"")
        if (key !in rheader) return DiffResult(emptyList(), false, "Right: no key column \"$key\"")
        if (lheader != rheader)
            return DiffResult(emptyList(), false,
                "Headers differ: left [${lheader.joinToString(", ")}] vs right [${rheader.joinToString(", ")}]")
        // LinkedHashMap keeps insertion order so duplicate keys are detected
        // in row order; the diff itself runs over the sorted key union.
        fun index(recs: List<Map<String, String>>, label: String): LinkedHashMap<String, Map<String, String>> {
            val by = LinkedHashMap<String, Map<String, String>>()
            for (rec in recs) {
                val k = rec.getValue(key)
                check(by[k] == null) { "$label: duplicate key \"$k\"" }
                by[k] = rec
            }
            return by
        }
        val leftBy = index(lrecs, "Left")
        val rightBy = index(rrecs, "Right")
        val rows = mutableListOf<RowDiff>()
        for (k in (leftBy.keys + rightBy.keys).toSortedSet()) {
            val l = leftBy[k]
            val r = rightBy[k]
            when {
                l == null -> rows.add(RowDiff(k, "added", after = r))
                r == null -> rows.add(RowDiff(k, "removed", before = l))
                else -> {
                    val columns = lheader.filter { it != key && l[it] != r[it] }.sorted()
                    if (columns.isNotEmpty()) rows.add(RowDiff(k, "changed", columns, l, r))
                }
            }
        }
        DiffResult(rows, rows.isEmpty(), null)
    } catch (e: IllegalStateException) {
        DiffResult(emptyList(), false, e.message)
    }
}

fun main() {
    val res = csvDiff("id,name\n1,Ada\n2,Bob", "id,name\n1,Ada\n2,Robert\n3,New")
    res.rows.forEach { d ->
        println(d.key + " " + d.type + when (d.type) {
            "changed" -> " (${d.columns}: ${d.before} -> ${d.after})"
            else -> ""
        })
    }
    println("same: ${res.same}") // same: false
    println(csvDiff("id,name\n1,Ada\n1,Bob", "id,name\n1,Ada").error) // Left: duplicate key "1"
}

Also available in 12 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →