Skip to content

Report CSV rows with missing fields clearly instead of crashing (fixes #30) - #56

Open
varunavy wants to merge 2 commits into
simonw:mainfrom
varunavy:fix-issue-30
Open

varunavy wants to merge 2 commits into
simonw:mainfrom
varunavy:fix-issue-30

Conversation

@varunavy

Copy link
Copy Markdown

Fixes #30

Problem: If a CSV row has fewer fields than the header, csv-diff crashes later in
compare() with "ValueError: not enough values to unpack", which does not explain the cause.

Root cause: load_csv() builds rows with dict(zip(headings, line)). zip() stops at the
shorter list, so missing fields are silently dropped and the row ends up with fewer columns
than the header. dictdiffer then reports an "add" instead of a "change", which compare()
cannot unpack.

Fix:

  • load_csv() now raises a ValueError naming the line number and the expected/found field counts.
  • The CLI catches it and prints a clean message instead of a traceback:
    Error: a.csv: Line 4: expected 4 fields but found 3
  • Completely blank lines are skipped.
  • Rows with extra fields keep the existing behaviour, since existing tests rely on it.
    Happy to add a warning for that case if you'd like.

Tests: Added tests for missing fields, empty fields, quoted commas, blank lines,
extra fields and the CLI error message. Full suite passes locally (30 passed).

AI assistance: I used Claude to help understand the root cause and draft parts of the
tests and this description; I ran and verified everything locally.

@varunavy

Copy link
Copy Markdown
Author

I’ve opened #56 with a fix for this.

@HRtech-lab HRtech-lab left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The missing-field diagnostic works with --format=tsv, but default delimiter detection can silently turn the same input into a misleading diff. This pair reproduces it on b466aec:

printf 'id\tname\tage\n1\tCleo\t4\n2\tPancakes\n' > old.tsv
printf 'id\tname\tage\n1\tCleo\t4\n2\tPancakes\t2\n' > new.tsv
csv-diff old.tsv new.tsv

The command exits 0 and reports 3 columns added, 1 column removed, 2 rows added, 2 rows removed. With --key=id, it raises KeyError('id'). With --format=tsv --key=id, it correctly reports Line 3: expected 3 fields but found 2.

The short row prevents Sniffer from detecting the tabs in old.tsv, so the comma fallback treats its entire header as one field. A regression test using the default CLI options would catch this alongside the explicit-format case.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BUG: incomplete last line causes unhandled error that's hard to debug

2 participants