CSV Diff — Go 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 Go implementation — the same logic the interactive tool runs, in a shareable, citable form.
// Package csvdiff is the Go twin of CosmoDev's src/lib/csv-diff.ts (dual
// source: the web lib is TypeScript, the CLI lib is Go — kept in lock-step).
// Pure + deterministic, never panics. The table-driven tests in
// csv-diff_test.go share vectors with src/lib/csv-diff.test.ts so the two
// implementations are held to the same contract.
//
// Algorithm mirrors the TS lib exactly: a hand-rolled RFC-4180 parser
// (quoted cells with embedded commas, newlines and escaped double quotes;
// CRLF line endings; a no-trailing-newline flush; blank and quoted-blank-only
// rows dropped) → strict per-side record tables (identical headers required,
// duplicate column / duplicate key / ragged row errors with row numbers and
// side labels) → a key-based row diff whose keys and changed columns come out
// sorted, so row order on either side never matters.
package csvdiff
import (
"fmt"
"slices"
"sort"
"strings"
)
// Options configures CsvDiff. The zero value (Options{}) matches the TS
// default (csvDiff(left, right) with no options): the key column is the
// first header column.
type Options struct {
// KeyColumn names the column whose value identifies a row across the
// two CSVs. Empty string (the zero value) means "use the first header
// column", matching the TS default.
KeyColumn string
}
// RowDiff.Type values.
const (
TypeAdded = "added"
TypeRemoved = "removed"
TypeChanged = "changed"
)
// RowDiff is one differing row of the diff. Columns is set on "changed" rows
// only (the differing column names, sorted); Before is set on "removed" and
// "changed"; After is set on "added" and "changed" — mirroring the TS
// CsvRowDiff surface.
type RowDiff struct {
Key string
Type string
Columns []string
Before map[string]string
After map[string]string
}
// Result mirrors the TS CsvDiffResult: either a full diff (Error == "") or an
// error (Rows empty, Same false, Error holding the message).
type Result struct {
Rows []RowDiff
Same bool
Error string // "" mirrors TS null (success)
}
// parseCsv parses RFC-4180 CSV text into rows of cells, mirroring parseCsv()
// in src/lib/csv-diff.ts byte for byte: a `"` outside quotes opens a quoted
// cell (any character, including commas and newlines, is literal inside);
// `""` inside quotes is an escaped `"`; `\n` and `\r` (or CRLF) end a row;
// the final row is flushed even without a trailing newline; rows consisting
// of a single empty cell (blank or quoted-blank-only lines) are dropped.
// Ragged rows are NOT an error here — toRecords enforces that.
func parseCsv(text string) [][]string {
var rows [][]string
var row []string
var cell strings.Builder
inQuotes := false
for i := 0; i < len(text); i++ {
ch := text[i]
if inQuotes {
if ch == '"' {
if i+1 < len(text) && text[i+1] == '"' {
cell.WriteByte('"')
i++
} else {
inQuotes = false
}
} else {
cell.WriteByte(ch)
}
} else if ch == '"' {
inQuotes = true
} else if ch == ',' {
row = append(row, cell.String())
cell.Reset()
} else if ch == '\n' || ch == '\r' {
if ch == '\r' && i+1 < len(text) && text[i+1] == '\n' {
i++
}
row = append(row, cell.String())
cell.Reset()
rows = append(rows, row)
row = nil
} else {
cell.WriteByte(ch)
}
}
if cell.Len() != 0 || len(row) > 0 {
row = append(row, cell.String())
rows = append(rows, row)
}
var filtered [][]string
for _, r := range rows {
if len(r) == 1 && r[0] == "" {
continue
}
filtered = append(filtered, r)
}
return filtered
}
// records is one side's parsed CSV: the header row plus one map per data row,
// in input order (the TS keeps insertion-ordered Map entries keyed by row
// number; the order is what matters, so the Go port uses a slice).
type records struct {
header []string
rows []map[string]string
}
// toRecords validates parsed rows into a header + record maps, mirroring
// toRecords() in the TS lib: empty document, duplicate header names and
// ragged rows are errors carrying the side label (and row number, 1-based
// counting the header as row 1).
func toRecords(rows [][]string, label string) (records, error) {
if len(rows) == 0 {
return records{}, &csvError{label + ": empty CSV"}
}
header := rows[0]
seen := make(map[string]bool, len(header))
for _, name := range header {
if seen[name] {
return records{}, &csvError{label + `: duplicate column "` + name + `"`}
}
seen[name] = true
}
recs := records{header: header}
for i, row := range rows {
if i == 0 {
continue
}
if len(row) != len(header) {
return records{}, &csvError{
fmt.Sprintf("%s: row %d has %d cells, expected %d", label, i+1, len(row), len(header)),
}
}
rec := make(map[string]string, len(header))
for c, name := range header {
rec[name] = row[c]
}
recs.rows = append(recs.rows, rec)
}
return recs, nil
}
// csvError is a plain message-carrying error, mirroring the TS throw sites
// whose messages are surfaced verbatim in Result.Error.
type csvError struct{ msg string }
func (e *csvError) Error() string { return e.msg }
// CsvDiff diffs two RFC-4180 CSV documents by the key column (Options{} →
// the first header column). It is the Go twin of csvDiff() in
// src/lib/csv-diff.ts and must agree with it on every shared vector:
// identical headers are required, one row per key on each side, keys and
// changed columns are sorted, and row order on either side never matters.
func CsvDiff(leftRaw, rightRaw string, opts Options) Result {
errResult := func(msg string) Result {
return Result{Rows: []RowDiff{}, Same: false, Error: msg}
}
if strings.TrimSpace(leftRaw) == "" || strings.TrimSpace(rightRaw) == "" {
return errResult("Both inputs are required")
}
left, err := toRecords(parseCsv(leftRaw), "Left")
if err != nil {
return errResult(err.Error())
}
right, err := toRecords(parseCsv(rightRaw), "Right")
if err != nil {
return errResult(err.Error())
}
key := opts.KeyColumn
if key == "" {
key = left.header[0]
}
if !slices.Contains(left.header, key) {
return errResult(`Left: no key column "` + key + `"`)
}
if !slices.Contains(right.header, key) {
return errResult(`Right: no key column "` + key + `"`)
}
if !slices.Equal(left.header, right.header) {
return errResult("Headers differ: left [" + strings.Join(left.header, ", ") +
"] vs right [" + strings.Join(right.header, ", ") + "]")
}
leftBy := make(map[string]map[string]string, len(left.rows))
for _, rec := range left.rows {
k := rec[key]
if _, dup := leftBy[k]; dup {
return errResult(`Left: duplicate key "` + k + `"`)
}
leftBy[k] = rec
}
rightBy := make(map[string]map[string]string, len(right.rows))
for _, rec := range right.rows {
k := rec[key]
if _, dup := rightBy[k]; dup {
return errResult(`Right: duplicate key "` + k + `"`)
}
rightBy[k] = rec
}
keys := make([]string, 0, len(leftBy)+len(rightBy))
for k := range leftBy {
keys = append(keys, k)
}
for k := range rightBy {
if _, inLeft := leftBy[k]; !inLeft {
keys = append(keys, k)
}
}
sort.Strings(keys)
rows := []RowDiff{}
for _, k := range keys {
l, inLeft := leftBy[k]
r, inRight := rightBy[k]
switch {
case !inLeft:
rows = append(rows, RowDiff{Key: k, Type: TypeAdded, After: r})
case !inRight:
rows = append(rows, RowDiff{Key: k, Type: TypeRemoved, Before: l})
default:
var columns []string
for _, name := range left.header {
if name != key && l[name] != r[name] {
columns = append(columns, name)
}
}
sort.Strings(columns)
if len(columns) > 0 {
rows = append(rows, RowDiff{
Key: k, Type: TypeChanged,
Columns: columns, Before: l, After: r,
})
}
}
}
return Result{Rows: rows, Same: len(rows) == 0, Error: ""}
}
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 →