This is implemented in trailer.c and borrows a large amount of logic from Git core to ensure compatibility.