Git: Compute a commit id

Compute exactly the id Git gives a commit.

What to build

A program that builds a commit object from its fields and prints its id.

Requirements

  • The object text is the tree line, the parent lines in order, the author and committer lines, an empty line and the message lines, each followed by a newline.
  • Print the 40-digit commit id.

Input

Line 1: the tree id. Line 2: p, then p parent ids. Then the author (NAME <EMAIL> TIMESTAMP ZONE) and the committer. Then m and m message lines.

Output

One line.

Constraints

p ≤ 8; m ≤ 50.

Example

Input:

4b825dc642cb6eb9a060e54bf8d69288fbee4904
0
Ada <ada@example.com> 1700000000 +0000
Ada <ada@example.com> 1700000000 +0000
1
First commit

Output:

2c623d019401c86e05e6f585ee783b71d4992287

Why it works

A commit's id is a hash of its full text, so it changes if anything changes: the snapshot, the parents, the people, the dates or the message.

Examples

Example 1 · Input
4b825dc642cb6eb9a060e54bf8d69288fbee4904
0
Ada <ada@example.com> 1700000000 +0000
Ada <ada@example.com> 1700000000 +0000
1
First commit
Expected output
2c623d019401c86e05e6f585ee783b71d4992287
Example 2 · Input
4b825dc642cb6eb9a060e54bf8d69288fbee4904
1
1111111111111111111111111111111111111111
Bob <bob@example.com> 1700003600 +0100
Bob <bob@example.com> 1700003600 +0100
1
Second commit
Expected output
8adc98c37fe8f03bb3f34f15969d7c267a162b98

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Build the text: `tree T`, one `parent P` line per parent, `author …`, `committer …`, a blank line, then the message lines, every line ending with a newline.

Hint 2

Hash b"commit " + the length in bytes + b"\0" + the text.

Solution

Show one correct solution (try it yourself first)
import hashlib

tree = input().strip()
parents = [input().strip() for _ in range(int(input()))]
author = input().strip()
committer = input().strip()
message = [input() for _ in range(int(input()))]
text = f"tree {tree}\n" + "".join(f"parent {p}\n" for p in parents)
text += f"author {author}\ncommitter {committer}\n\n" + "".join(line + "\n" for line in message)
data = text.encode()
print(hashlib.sha1(b"commit " + str(len(data)).encode() + b"\0" + data).hexdigest())

Lesson: Inside Git: trees and commits →