Skip to content

Commit d491eca

Browse files
committed
fix(objects): read commit and tag headers by name instead of position
<!-- agent --> `Commit._deserialize()`, which parses `git cat-file commit` output on the CLI backend, took the line after the parent headers as the author and the next one as the committer without checking their names, and counted any header starting with `parent` as a parent. Git finds these headers by name: `parse_commit_buffer()` accepts only `parent ` lines right after `tree`, and `find_commit_header()` and the pretty formatter look up `author` and `committer` anywhere in the header block. Whoever authors a commit controls its headers, so a commit with tree ... x-note Linus Torvalds <torvalds@linux-foundation.org> 1700000000 +0000 author Mallory <mallory@evil.example> 1112591163 +0200 committer Mallory <mallory@evil.example> 1112591163 +0200 is shown by `git log`, `git show --format=%an` and `git for-each-ref --format=%(authorname)` as authored by Mallory, while `Commit.author` and `Commit.authored_date` reported Linus Torvalds and his date. The same header between `author` and `committer` replaced the committer. A `parentx <oid>` header added a parent that Git does not see. Without a committer line, the parse ran into the message: the subject was lost, and a message line starting with `gpgsig ` became `Commit.gpgsig` of an unsigned commit. `git fsck` reports these commits (`missingAuthor`, `missingCommitter`), but with the default `transfer.fsckObjects=false` a clone or fetch accepts them. GixPython 0.3.0 refuses to decode them, so the Gix backend falls back to the same parser and reported the same values. `TagObject._set_cache_()` read tags the same way on its CLI path. It took the tagger only from the fourth line and the message from a fixed line after it, so a header before `tagger` hid the tagger and put header lines into `TagObject.message`, and an extra header after `tagger` leaked into the message. `git for-each-ref --format=%(taggername)%00%(contents)` finds the tagger by name and the message after the first empty line. Read the author and committer by name in the existing header loop, and require `parent ` for parents. Continuation lines, such as those of a `mergetag`, start with a space and match no header name, so the separate `mergetag` skip is no longer needed. For tags, take the first `tagger` header after the `tag` line and the message after the first empty line. When a commit repeats a header, use the first one, as `find_commit_header()` does for `commit -C`/`--amend`, the sequencer and `for-each-ref`. Git's pretty formatter takes the last one, so Git is not consistent there itself. Commits and tags laid out the way Git writes them parse as before. Limitation: commits with an `encoding` header still take author and committer names from Git's pretty formatter, so such a commit that also repeats `author` pairs the last name with the first date, as before. Validation: a `header-names` case in `tests/fixtures/commit.sh` backs `test_deserialization_finds_headers_by_name` in `test/test_commit.py`. It compares commit and tag fields with `git show` and `git for-each-ref` for a header before `author`/`tagger`, a header between `author` and `committer` (after `tagger`), a missing committer, and a `parentx` header. All four cases fail before the change and pass after it with `GIT_PYTHON_BACKEND=cli` and `GIT_PYTHON_BACKEND=gix`, and the tag assertions also fail with only the commit change applied. A scratch comparison of 14 crafted commits against `git for-each-ref`, which also covered repeated headers, `encoding` or `gpgsig` before `author`, a `mergetag` and a missing author, differed in 10 cases before the change and matched in all of them after it, on both backends. The full suite passes on both backends (2086 passed on `cli`, 2189 on `gix`; Git 2.56.0, GixPython 0.3.0, Python 3.11), as do `pre-commit` (ruff, shellcheck), `mypy` and `basedpyright --warnings`. Agent-Model: claude-opus-5-5
1 parent 9232dc5 commit d491eca

4 files changed

Lines changed: 85 additions & 25 deletions

File tree

‎git/objects/commit.py‎

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -979,7 +979,7 @@ def _deserialize(self, stream: BytesIO, *, text_encoding: Union[str, None] = Non
979979
next_line = None
980980
while True:
981981
parent_line = readline()
982-
if not parent_line.startswith(b"parent"):
982+
if not parent_line.startswith(b"parent "):
983983
next_line = parent_line
984984
break
985985
# END abort reading parents
@@ -988,29 +988,24 @@ def _deserialize(self, stream: BytesIO, *, text_encoding: Union[str, None] = Non
988988
self.parents = tuple(self.parents)
989989

990990
# We don't know actual author encoding before we have parsed it, so keep the
991-
# lines around.
992-
author_line = next_line
993-
committer_line = readline()
994-
995-
# We might run into one or more mergetag blocks, skip those for now.
996-
next_line = readline()
997-
while next_line.startswith(b"mergetag "):
998-
next_line = readline()
999-
while next_line.startswith(b" "):
1000-
next_line = readline()
1001-
# END skip mergetags
1002-
1003-
# Now we can have the encoding line, or an empty line followed by the optional
1004-
# message.
991+
# lines around. Like Git, find them by header name rather than by position.
992+
author_line = committer_line = b""
993+
1005994
self.encoding = self.default_encoding
1006995
gpgsig = b""
1007996
encoding_seen = False
1008997

1009-
# Read headers.
998+
# Read headers. Continuation lines, such as those of a mergetag, start with a
999+
# space and match no header name.
10101000
enc = next_line
10111001
buf = enc.rstrip(b"\n")
10121002
while buf:
1013-
if buf.startswith(b"encoding "):
1003+
if buf.startswith(b"author "):
1004+
# Git uses the first header of each name (find_commit_header).
1005+
author_line = author_line or buf
1006+
elif buf.startswith(b"committer "):
1007+
committer_line = committer_line or buf
1008+
elif buf.startswith(b"encoding "):
10141009
if not encoding_seen:
10151010
encoding_seen = True
10161011
raw_encoding = buf[9:]

‎git/objects/tag.py‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -134,10 +134,10 @@ def _set_cache_(self, attr: str) -> None:
134134
)
135135
except GitCommandError as exc:
136136
raise BadObject(self.binsha) from exc
137-
# Git terminates tag headers only at line feeds.
138-
lines: List[str] = raw.decode(defenc, "replace").split("\n")
139-
if lines and lines[-1] == "":
140-
lines.pop()
137+
# Git terminates tag headers only at line feeds, and the header block at
138+
# the first empty line.
139+
headers, _, message = raw.decode(defenc, "replace").partition("\n\n")
140+
lines: List[str] = headers.split("\n")
141141

142142
_obj, hexsha = lines[0].split(" ")
143143
_type_token, type_name = lines[1].split(" ")
@@ -146,10 +146,10 @@ def _set_cache_(self, attr: str) -> None:
146146

147147
self.tag = lines[2][4:] # tag <tag name>
148148

149-
has_tagger = len(lines) > 3 and lines[3].startswith("tagger ")
150-
self.tagger, self.tagged_date, self.tagger_tz_offset = parse_actor_and_date(lines[3] if has_tagger else "")
151-
message_start = 5 if has_tagger else 4
152-
self.message = "\n".join(lines[message_start:])
149+
# Like Git, find the first tagger header by name rather than by position.
150+
tagger = next((line for line in lines[3:] if line.startswith("tagger ")), "")
151+
self.tagger, self.tagged_date, self.tagger_tz_offset = parse_actor_and_date(tagger)
152+
self.message = message[:-1] if message.endswith("\n") else message
153153
# END check our attributes
154154
else:
155155
super()._set_cache_(attr)

‎test/test_commit.py‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -681,6 +681,45 @@ def test_deserialization_headers_end_at_empty_line(self):
681681
key = ("commit.decode", "CLI: " + reason)
682682
self.assertEqual(_backend.statistics().get(key, 0), before.get(key, 0) + 1)
683683

684+
def test_deserialization_finds_headers_by_name(self):
685+
"""Like Git, read identities by header name and parents only from ``parent`` headers."""
686+
for variant in ("before-author", "before-committer", "no-committer", "parent-prefix"):
687+
with self.subTest(variant=variant), fixture_repo("commit.sh", "header-names", variant) as repo:
688+
root = Path(repo.working_dir).parent
689+
oid = (root / "object-id").read_text().strip()
690+
expected = repo.git.show(
691+
"--no-patch",
692+
"--no-notes",
693+
"--no-show-signature",
694+
"--no-use-mailmap",
695+
"--format=format:%an%x00%ae%x00%at%x00%cn%x00%ce%x00%P%x00%B",
696+
oid,
697+
"--",
698+
strip_newline_in_stdout=False,
699+
).split("\0")
700+
committer = ["", ""] if variant == "no-committer" else ["C", "c@example.com"]
701+
self.assertEqual(expected, ["A", "a@example.com", "1112591163", *committer, "", "subject\n\nbody\n"])
702+
raw = repo.git.cat_file("commit", oid, stdout_as_string=False, strip_newline_in_stdout=False)
703+
before = _backend.statistics()
704+
for cmt in (
705+
Commit(repo, bytes.fromhex(oid))._deserialize(BytesIO(raw)),
706+
Commit(repo, bytes.fromhex(oid)),
707+
):
708+
actual = [cmt.author.name, cmt.author.email, str(cmt.authored_date)]
709+
actual += [cmt.committer.name, cmt.committer.email or ""]
710+
actual += [" ".join(parent.hexsha for parent in cmt.parents), cmt.message]
711+
self.assertEqual(actual, expected)
712+
expected = repo.git.for_each_ref("--format=%(taggername)%00%(contents)", "refs/tags/v1")
713+
self.assertEqual(expected, "T\0subject\n\nbody\n")
714+
tag = TagObject(repo, bytes.fromhex((root / "tag-id").read_text().strip()))
715+
self.assertEqual((tag.tagger.name, tag.message), ("T", "subject\n\nbody"))
716+
if _backend.name == "gix":
717+
key = ("commit.decode", "CLI: native decoder diagnostics")
718+
self.assertEqual(_backend.statistics().get(key, 0), before.get(key, 0) + 1)
719+
key = ("tag.decode", "CLI: native decoder diagnostics")
720+
tag_fallback = variant in ("before-author", "before-committer")
721+
self.assertEqual(_backend.statistics().get(key, 0), before.get(key, 0) + tag_fallback)
722+
684723
def test_deserialization_reads_date_after_email(self):
685724
"""Only the date right after the email counts, as in Git's split_ident_line."""
686725
with fixture_repo("commit.sh", "trailing-date") as repo:

‎tests/fixtures/commit.sh‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,32 @@ case "$1" in
7878
} | git hash-object --literally -w -t tag --stdin > ../tag-id
7979
git update-ref refs/tags/v1 "$(cat ../tag-id)"
8080
;;
81+
header-names)
82+
tree=$(git mktree </dev/null)
83+
other=$(git commit-tree "$tree" -m other)
84+
note='x-note L <l@example.com> 1700000000 +0000'
85+
{
86+
printf 'tree %s\n' "$tree"
87+
case "$2" in
88+
before-author) printf '%s\n' "$note" ;;
89+
parent-prefix) printf 'parentx %s\n' "$other" ;;
90+
before-committer|no-committer) ;;
91+
*) exit 1 ;;
92+
esac
93+
printf 'author A <a@example.com> 1112591163 +0200\n'
94+
if [ "$2" = before-committer ]; then printf '%s\n' "$note"; fi
95+
if [ "$2" != no-committer ]; then printf 'committer C <c@example.com> 1112591163 +0200\n'; fi
96+
printf '\nsubject\n\nbody\n'
97+
} | git hash-object --literally -w -t commit --stdin > ../object-id
98+
{
99+
printf 'object %s\ntype commit\ntag v1\n' "$other"
100+
if [ "$2" = before-author ]; then printf '%s\n' "$note"; fi
101+
printf 'tagger T <t@example.com> 1112591163 +0200\n'
102+
if [ "$2" = before-committer ]; then printf '%s\n' "$note"; fi
103+
printf '\nsubject\n\nbody\n'
104+
} | git hash-object --literally -w -t tag --stdin > ../tag-id
105+
git update-ref refs/tags/v1 "$(cat ../tag-id)"
106+
;;
81107
whitespace-headers)
82108
tree=$(git mktree </dev/null)
83109
{

0 commit comments

Comments
 (0)