DIY_GIT_in_Python/ugit/data.py

45 lines
974 B
Python
Raw Normal View History

2024-02-10 19:09:11 +01:00
from pathlib import Path
2024-02-12 19:35:14 +01:00
import hashlib
2024-02-10 19:09:11 +01:00
GIT_DIR = ".ugit"
def init():
Path.mkdir(GIT_DIR)
2024-02-12 19:35:14 +01:00
Path.mkdir(f"{GIT_DIR}/objects")
2024-04-12 17:19:14 +02:00
def update_ref(ref, oid):
2024-04-17 19:33:54 +02:00
ref_path = f"{GIT_DIR}/{ref}"
Path.mkdir(ref_path, exist_ok=True)
with open(ref_path, "w") as f:
2024-03-13 19:38:35 +01:00
f.write(oid)
2024-04-12 17:19:14 +02:00
def get_ref(ref):
2024-04-17 19:33:54 +02:00
ref_path = f"{GIT_DIR}/{ref}"
if Path.is_file(ref_path):
with open(ref_path) as f:
2024-03-18 19:01:53 +01:00
return f.read().strip()
2024-02-15 20:20:00 +01:00
def hash_object(data, type_="blob"):
obj = type_.encode() + b"\x00" + data
oid = hashlib.sha1(obj).hexdigest()
2024-02-12 19:35:14 +01:00
with open(f"{GIT_DIR}/objects/{oid}", "wb") as out:
2024-02-15 20:20:00 +01:00
out.write(obj)
2024-02-12 19:35:14 +01:00
return oid
2024-02-14 20:24:33 +01:00
2024-02-15 20:20:00 +01:00
def get_object(oid, expected="blob"):
2024-02-14 20:24:33 +01:00
with open(f"{GIT_DIR}/objects/{oid}", "rb") as f:
2024-02-15 20:20:00 +01:00
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