Compare commits

...

2 Commits

Author SHA1 Message Date
David Doblas Jiménez a010615cf2 Print hashed objects 2024-02-14 20:24:33 +01:00
David Doblas Jiménez 9634544d68 Add change 05 instructions 2024-02-14 20:23:44 +01:00
3 changed files with 41 additions and 1 deletions

24
how_to/Change_05.md Normal file
View File

@ -0,0 +1,24 @@
- cat-file: Print hashed objects
This command is the "opposite" of `hash-object`: it can print an object by its
OID. Its implementation just reads the file at ".ugit/objects/{OID}".
The names `hash-object` and `cat-file` aren't the clearest of names, but they
are the names that Git uses so we'll stick to them for consistency.
We can now try the full cycle:
```
$ cd /tmp/new
$ ugit init
Initialized empty ugit repository in /tmp/new/.ugit
$ echo some file > bla
$ ugit hash-object bla
0e08b5e8c10abc3e455b75286ba4a1fbd56e18a5
$ ugit cat-file 0e08b5e8c10abc3e455b75286ba4a1fbd56e18a5
some file
```
Note that the name of the file (bla) wasn't preserved as part of this process,
because, again, the object database is just about storing bytes for later
retrieval and it doesn't care which filename the bytes came from.

View File

@ -1,6 +1,8 @@
import argparse
from pathlib import Path
import argparse
import sys
from . import data
@ -18,6 +20,10 @@ def parse_args():
init_parser = commands.add_parser("init")
init_parser.set_defaults(func=init)
cat_file_parser = commands.add_parser("cat-file")
cat_file_parser.set_defaults(func=cat_file)
cat_file_parser.add_argument("object")
hash_object_parser = commands.add_parser("hash-object")
hash_object_parser.set_defaults(func=hash_object)
hash_object_parser.add_argument("file")
@ -33,3 +39,8 @@ def init(args):
def hash_object(args):
with open(args.file, "rb") as f:
print(data.hash_object(f.read()))
def cat_file(args):
sys.stdout.flush()
sys.stdout.buffer.write(data.get_object(args.object))

View File

@ -15,3 +15,8 @@ def hash_object(data):
with open(f"{GIT_DIR}/objects/{oid}", "wb") as out:
out.write(data)
return oid
def get_object(oid):
with open(f"{GIT_DIR}/objects/{oid}", "rb") as f:
return f.read()