Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix comparing of csv files with non-default file encoding #19

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions csv_diff/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,12 @@
is_flag=True,
help="Show unchanged fields for rows with at least one change",
)
def cli(previous, current, key, format, json, singular, plural, show_unchanged):
@click.option(
"--encoding",
default=None,
help="Specify text encoding of the csv files",
)
def cli(previous, current, key, format, json, singular, plural, show_unchanged, encoding):
"Diff two CSV or JSON files"
dialect = {
"csv": "excel",
Expand All @@ -51,10 +56,10 @@ def cli(previous, current, key, format, json, singular, plural, show_unchanged):

def load(filename):
if format == "json":
return load_json(open(filename), key=key)
return load_json(open(filename, encoding=encoding), key=key)
else:
return load_csv(
open(filename, newline=""), key=key, dialect=dialect.get(format)
open(filename, newline="", encoding=encoding), key=key, dialect=dialect.get(format)
)

diff = compare(load(previous), load(current), show_unchanged)
Expand Down
40 changes: 40 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,3 +234,43 @@ def test_semicolon_delimited(tmpdir):
"columns_added": [],
"columns_removed": [],
} == json.loads(result.output.strip())


def test_human_cli_non_utf8_encoding(tmpdir):
# This test confirms the ability to parse csv files that are not encoded using utf-8.
# The names in the files contain characters that would cause UnicodeDecodeErrors if they
# are encoeded using cp1252 and then parsed using utf-8.
encoding = "cp1252"
one = tmpdir / "one.csv"
two = tmpdir / "two.csv"
one.write_binary(
dedent(
"""
id;name
1;José
"""
).strip().encode(encoding)
)
two.write_binary(
dedent(
"""
id;name
1;Ángela
"""
).strip().encode(encoding)
)
result = CliRunner().invoke(
cli.cli, [str(one), str(two), "--key", "id", "--encoding", encoding], catch_exceptions=False
)
assert 0 == result.exit_code
assert (
dedent(
"""
1 row changed

id: 1
name: "José" => "Ángela"
"""
).strip()
== result.output.strip()
)