DIY_GIT_in_Python/ugit/data.py

42 lines
895 B
Python

from pathlib import Path
import hashlib
GIT_DIR = ".ugit"
def init():
Path.mkdir(GIT_DIR)
Path.mkdir(f"{GIT_DIR}/objects")
def update_ref(ref, oid):
with open(f"{GIT_DIR}/{ref}", "w") as f:
f.write(oid)
def get_ref(ref):
if Path.is_file(f"{GIT_DIR}/{ref}"):
with open(f"{GIT_DIR}/HEAD") as f:
return f.read().strip()
def hash_object(data, type_="blob"):
obj = type_.encode() + b"\x00" + data
oid = hashlib.sha1(obj).hexdigest()
with open(f"{GIT_DIR}/objects/{oid}", "wb") as out:
out.write(obj)
return oid
def get_object(oid, expected="blob"):
with open(f"{GIT_DIR}/objects/{oid}", "rb") as f:
obj = f.read()
type_, _, content = obj.partition(b"\x00")
type_ = type_.decode()
if expected is not None:
assert type_ == expected, f"Expected {expected}, got {type_}"
return content