A staged rename report is not always one status plus one filename. Rename and copy records contain both an original and a destination path. Parsing the output as lines or splitting every record into two fields breaks as soon as those cases appear.
This tutorial asks Git for NUL-delimited name-status output and parses its field structure directly. The fixture renames a file whose original name contains a newline to a name containing a tab. It creates a disposable repository under the current directory and removes it afterward.
Prerequisites
Use Git and Python 3.12 on Linux. The example was executed with Git 2.43.0. Save the program as renames.py in a scratch directory. It needs no remote, user identity or commits.
Complete example
import os
from pathlib import Path
import subprocess
import tempfile
def git(repo, *args):
return subprocess.run(["git", "-C", str(repo), *args], check=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
timeout=5).stdout
def parse(raw):
if not raw:
return []
if not raw.endswith(b"\0"):
raise ValueError("unterminated Git output")
fields = iter(raw[:-1].split(b"\0"))
result = []
try:
for status in fields:
first = next(fields)
second = next(fields) if status.startswith((b"R", b"C")) else None
result.append((status, first, second))
except StopIteration as error:
raise ValueError("truncated record") from error
return result
with tempfile.TemporaryDirectory(prefix="rename-", dir=".") as folder:
repo = Path(folder).resolve()
git(repo, "init", "-q")
old, new = "before\nname.txt", "after\tname.txt"
(repo / old).write_text("unchanged contents\n")
git(repo, "add", "--", old)
tree = git(repo, "write-tree").decode().strip()
os.rename(repo / old, repo / new)
git(repo, "add", "-A")
raw = git(repo, "diff", "--cached", "--name-status", "-z", "-M", tree, "--")
rows = parse(raw)
assert rows == [(b"R100", os.fsencode(old), os.fsencode(new))]
assert parse(b"M\0plain\0") == [(b"M", b"plain", None)]
for broken in [b"R100\0one\0", b"M\0name"]:
try:
parse(broken)
except ValueError:
pass
else:
raise AssertionError("truncation accepted")
print(rows)
print("rename and truncation checks passed; no commits created")
Run and expected output
python3 renames.py
[(b'R100', b'before\nname.txt', b'after\tname.txt')]
rename and truncation checks passed; no commits created
Understand the comparison
The first staged file is written into a tree object with git write-tree. That tree becomes the explicit baseline. After the filesystem rename and restaging, the cached diff compares the index against that baseline. This avoids creating a commit merely to demonstrate rename detection.
The -M option requests rename detection. Since the fixture preserves the entire content, Git reports R100. A status beginning with R or C consumes two path fields; ordinary modifications consume one. Paths remain bytes throughout parsing so decoding assumptions cannot corrupt them.
Edge cases and troubleshooting
Rename detection is a comparison result, not a permanent record of a filesystem rename operation. Substantially edited content may appear as a deletion and addition depending on similarity thresholds and detection limits. Do not make downstream correctness depend on every move being recognized as a rename.
The parser rejects missing terminal NUL bytes and missing fields. It is designed for this Git command’s output, not as a general validator for arbitrary status protocols. The copy branch shares the two-path parsing rule, but this fixture does not exercise actual Git copy detection.
Use argument lists rather than shell command strings when passing unusual filenames. A shell pipeline that stores NUL-delimited data in a variable can lose the separators before your parser sees them. For readable displays, use escaped representations as this program does; keep the original bytes for later filesystem operations.
References and related tutorials
See the official git diff manual and diff options reference. Continue with Git tutorials.