defmodule GitGud.Git.DiffParserTest do
use ExUnit.Case, async: true
alias GitGud.Git.DiffParser
test "parses a simple modify with one hunk" do
text = """
diff --git a/lib/foo.ex b/lib/foo.ex
index 1111111..2222222 100644
--- a/lib/foo.ex
+++ b/lib/foo.ex
@@ -1,3 +1,4 @@
defmodule Foo do
- def x, do: 1
+ def x, do: 2
+ def y, do: 3
end
"""
assert [file] = DiffParser.parse(text)
assert file.path == "lib/foo.ex"
assert file.status == :modified
assert file.insertions == 2
assert file.deletions == 1
assert [hunk] = file.hunks
assert hunk.old_start == 1 and hunk.old_count == 3
assert hunk.new_start == 1 and hunk.new_count == 4
types = Enum.map(hunk.lines, & &1.type)
assert types == [:context, :del, :add, :add, :context]
end
test "tracks line numbers correctly across context + add + del" do
text = """
diff --git a/a.txt b/a.txt
--- a/a.txt
+++ b/a.txt
@@ -10,3 +10,4 @@
ten
-eleven
+eleven new
+bonus
twelve
"""
[%{hunks: [hunk]}] = DiffParser.parse(text)
assert Enum.map(hunk.lines, fn l -> {l.type, l.old_line, l.new_line} end) == [
{:context, 10, 10},
{:del, 11, nil},
{:add, nil, 11},
{:add, nil, 12},
{:context, 12, 13}
]
end
test "added file (old side /dev/null)" do
text = """
diff --git a/new.txt b/new.txt
new file mode 100644
--- /dev/null
+++ b/new.txt
@@ -0,0 +1,2 @@
+line one
+line two
"""
assert [file] = DiffParser.parse(text)
assert file.status == :added
assert file.path == "new.txt"
assert file.insertions == 2
assert file.deletions == 0
end
test "deleted file (new side /dev/null)" do
text = """
diff --git a/old.txt b/old.txt
deleted file mode 100644
--- a/old.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-gone
-bye
"""
assert [file] = DiffParser.parse(text)
assert file.status == :deleted
assert file.path == "old.txt"
assert file.deletions == 2
end
test "binary file produces an empty-hunk record flagged binary" do
text = """
diff --git a/img.png b/img.png
index abc..def 100644
Binary files a/img.png and b/img.png differ
"""
assert [file] = DiffParser.parse(text)
assert file.binary?
assert file.hunks == []
end
test "handles `\\ No newline at end of file` marker gracefully" do
text = """
diff --git a/a.txt b/a.txt
--- a/a.txt
+++ b/a.txt
@@ -1 +1 @@
-old
\\ No newline at end of file
+new
"""
[%{hunks: [hunk]}] = DiffParser.parse(text)
assert Enum.map(hunk.lines, & &1.type) == [:del, :add]
end
test "multiple files in one diff" do
text = """
diff --git a/a.txt b/a.txt
--- a/a.txt
+++ b/a.txt
@@ -1 +1 @@
-a
+A
diff --git a/b.txt b/b.txt
--- a/b.txt
+++ b/b.txt
@@ -1 +1 @@
-b
+B
"""
files = DiffParser.parse(text)
assert length(files) == 2
assert Enum.map(files, & &1.path) == ["a.txt", "b.txt"]
end
test "empty input returns []" do
assert DiffParser.parse("") == []
end
end
3.2 KiB · text
5af55d9