Compute exactly the id that git hash-object prints.
What to build
A program that computes the Git blob id of a text file.
Requirements
- The file consists of the given lines, each ending with a newline. Encode it as UTF-8.
- Print the 40-digit hexadecimal object id.
Input
Line 1: n. Then the n lines of the file.
Output
One line.
Constraints
n ≤ 1,000.
Example
Input:
1
hello
Output:
ce013625030ba8dba906f756967f9e9ca394464a
Why it works
Git names every file version by hashing a small header with the content, so the same content gives the same id everywhere.
Examples
Example 1 · Input
1 hello
Expected output
ce013625030ba8dba906f756967f9e9ca394464a
Example 2 · Input
2 line one line two
Expected output
e5c5c5583f49a34e86ce622b59363df99e09d4c6
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
The content is the lines joined with newline characters, each line followed by a newline; no lines means an empty file.
Hint 2
Hash b"blob " + the length in bytes + b"\0" + the content with hashlib.sha1.
Solution
Show one correct solution (try it yourself first)
import hashlib lines = [input() for _ in range(int(input()))] data = "".join(line + "\n" for line in lines).encode() print(hashlib.sha1(b"blob " + str(len(data)).encode() + b"\0" + data).hexdigest())