Git: Read a commit object

Read the fields of a raw commit object.

What to build

A program that prints a summary of a commit object.

Requirements

  • Print tree: ID, parents: N, author: NAME, date: YYYY-MM-DD HH:MM:SS UTC (the author's timestamp in UTC) and subject: FIRST MESSAGE LINE.
  • Add (merge commit) after the parent count when there are two or more parents, and (first commit) when there are none.

Input

Line 1: n. Then the n lines of the commit object.

Output

Five lines.

Constraints

n ≤ 200.

Example

Input:

5
tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904
author Ada <ada@example.com> 1700000000 +0000
committer Ada <ada@example.com> 1700000000 +0000

First commit

Output:

tree: 4b825dc642cb6eb9a060e54bf8d69288fbee4904
parents: 0 (first commit)
author: Ada
date: 2023-11-14 22:13:20 UTC
subject: First commit

Why it works

A commit object is plain text with one field per line, so splitting at the blank line and reading each field gives its meaning.

Examples

Example 1 · Input
5
tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904
author Ada <ada@example.com> 1700000000 +0000
committer Ada <ada@example.com> 1700000000 +0000

First commit
Expected output
tree: 4b825dc642cb6eb9a060e54bf8d69288fbee4904
parents: 0 (first commit)
author: Ada
date: 2023-11-14 22:13:20 UTC
subject: First commit
Example 2 · Input
8
tree 18eb80fbbbf9160491c007668d5298f1e86cd40a
parent 2c623d019401c86e05e6f585ee783b71d4992287
parent 8adc98c37fe8f03bb3f34f15969d7c267a162b98
author Ada <ada@example.com> 1700007200 +0000
committer Ada <ada@example.com> 1700007200 +0000

Merge branch feature

Expected output
tree: 18eb80fbbbf9160491c007668d5298f1e86cd40a
parents: 2 (merge commit)
author: Ada
date: 2023-11-15 00:13:20 UTC
subject: Merge branch feature

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

Hints

Hint 1

Header lines come before the first blank line; the message comes after it.

Hint 2

An author line is `author NAME <EMAIL> TIMESTAMP ZONE`; use datetime.fromtimestamp(t, timezone.utc) for the date.

Solution

Show one correct solution (try it yourself first)
from datetime import datetime, timezone

lines = [input() for _ in range(int(input()))]
blank = lines.index("")
headers, message = lines[:blank], lines[blank + 1:]
tree = next(line.split()[1] for line in headers if line.startswith("tree "))
parents = sum(1 for line in headers if line.startswith("parent "))
author = next(line for line in headers if line.startswith("author "))
name = author[len("author "):author.index(" <")]
stamp = int(author.split()[-2])
note = " (merge commit)" if parents >= 2 else " (first commit)" if parents == 0 else ""
print(f"tree: {tree}")
print(f"parents: {parents}{note}")
print(f"author: {name}")
print(f"date: {datetime.fromtimestamp(stamp, timezone.utc):%Y-%m-%d %H:%M:%S} UTC")
print(f"subject: {message[0] if message else ''}")

Lesson: Inside Git: trees and commits →