GeezerVison is showing github.com — Exception suggestion: raise when making a Commit with non-commit binsha · Issue #2254 · gitpython-developers/GitPython
Exception suggestion: raise when making a Commit with non-commit binsha #2254DescriptionConsider the following code snippet:
import git
repo = git.Repo('GitPython')
tag = repo.rev_parse('3.1.62')
commit = git.Commit(repo, tag.binsha)
index_file = git.IndexFile.new(repo, commit.tree)
If GitPython is a repo in the CWD, then upon running the above code, you will see a traceback like so:
Traceback (most recent call last):
File "my_python_file.py", line 5, in <module>
index_file = git.IndexFile.new(repo, commit.tree)
File "/usr/lib/python3.14/site-packages/git/index/base.py", line 330, in new
base_entries = aggressive_tree_merge(repo.odb, tree_sha_bytes)
File "/usr/lib/python3.14/site-packages/git/index/fun.py", line 505, in aggressive_tree_merge
for entry in traverse_tree_recursive(odb, tree_shas[-1], ""):
~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.14/site-packages/git/objects/fun.py", line 271, in traverse_tree_recursive
data = tree_entries_from_data(odb.stream(tree_sha).read())
File "/usr/lib/python3.14/site-packages/git/objects/fun.py", line 111, in tree_entries_from_data
while data[i] != 0:
~~~~^^^
IndexError: index out of range
This throws an out-of-bounds array index exception when trying to parse the tag's database stream as a tree, which should fail. However, the real user error occurred when trying to make a Commit object from a tag object's binsha: commit = git.Commit(repo, tag.binsha). The Commit constructor should raise an Exception with a message to this effect. For example, "Given sha value does not refer to a commit`. ActivityByron commented on Sep 28, 2026 I have a partial fix for it, which is in the realm of what can be done without affecting performance noticably.
Codex
The proposed fix catches the type mismatch before parsing: accessing Commit(repo, tag.binsha).tree for an annotated tag now raises a clear ValueError identifying the SHA, actual type, and expected type, instead of the unrelated IndexError.
The audit also improved related paths:
- The same validation covers blobs, trees, tags, and raw tree traversals used by index operations.
IndexFile.new() now preserves binary SHA inputs instead of converting them into Python string representations.
- Submodule diffs now represent their commit IDs without incorrectly treating them as blobs.
Commit(repo, tag.binsha) itself still succeeds. Constructors remain lazy because checking there would require a database lookup for every object created and interfere with representing placeholders or objects unavailable locally. Validation happens when metadata or data is requested.
MetadataMetadataDevelopmentNo branches or pull requestsIssue actions
|