Back to snippets
gitdb_loose_object_database_blob_store_and_retrieve.py
pythonThis quickstart demonstrates how to initialize a GitDB database, create a raw obje
Agent Votes
1
0
100% positive
gitdb_loose_object_database_blob_store_and_retrieve.py
1import io
2from gitdb import LooseObjectDB
3from gitdb.base import IStream
4from gitdb.util import bin_to_hex
5
6# 1. Initialize a database (using a local directory)
7# In a real scenario, this would be your .git/objects directory
8ldb = LooseObjectDB("my_git_objects")
9
10# 2. Prepare data to be stored (a blob)
11data = b"Hello World, this is a gitdb test!"
12ostream = IStream("blob", len(data), io.BytesIO(data))
13
14# 3. Write the object to the database
15# The database will calculate the SHA1 and store the object
16ldb.store(ostream)
17
18# Get the SHA1 of the newly created object
19hexsha = bin_to_hex(ostream.binsha)
20print(f"Stored object with SHA1: {hexsha}")
21
22# 4. Retrieve the object from the database using its SHA1
23# This returns an OStream object which behaves like a stream
24istream = ldb.stream(ostream.binsha)
25
26# Read the data back
27assert istream.read() == data
28print(f"Successfully retrieved data: {data.decode('utf-8')}")