Compare commits

...

2 Commits

Author SHA1 Message Date
David Doblas Jiménez 2556bde16f Add types to objects 2024-02-15 20:20:00 +01:00
David Doblas Jiménez 36f6f88990 Add change 06 instructions 2024-02-15 20:18:45 +01:00
3 changed files with 31 additions and 6 deletions

17
how_to/Change_06.md Normal file
View File

@ -0,0 +1,17 @@
- data: Add types to objects
As we will soon see, there will be different logical types of objects that are
used in different contexts (even though, from the Object Database's point of
view, they are just all bytes). In order to lower the chance of using an object
in the wrong context we're going to add a type tag for each object.
The type is just a string that's going to be prepended to the start of the file,
followed by a null byte. When reading the file later we'll extract the type and
verify that it's indeed the expected type.
The default type is going to be `blob`, since by default an object is a
collection of bytes with no further semantic meaning.
We can also pass `expected=None` to `get_object()` if we don't want to verify
the type. This is useful for the `cat-file` CLI command which is a debug command
used for printing all objects.

View File

@ -43,4 +43,4 @@ def hash_object(args):
def cat_file(args):
sys.stdout.flush()
sys.stdout.buffer.write(data.get_object(args.object))
sys.stdout.buffer.write(data.get_object(args.object), expected=None)

View File

@ -10,13 +10,21 @@ def init():
Path.mkdir(f"{GIT_DIR}/objects")
def hash_object(data):
oid = hashlib.sha1(data).hexdigest()
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(data)
out.write(obj)
return oid
def get_object(oid):
def get_object(oid, expected="blob"):
with open(f"{GIT_DIR}/objects/{oid}", "rb") as f:
return f.read()
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