63 lines
2.1 KiB
Markdown
63 lines
2.1 KiB
Markdown
- write-tree: Write tree objects
|
|
|
|
Now comes the fun part, where we turn a collection of separate files into a
|
|
single object that represents a directory.
|
|
|
|
|
|
The idea is that we will create one additional object that collects all the data
|
|
necessary to store a complete directory. For example, if we have a directory
|
|
with two files:
|
|
```
|
|
$ ls
|
|
cats.txt dogs.txt
|
|
```
|
|
|
|
And we want to save the directory, we will first put the individual files into
|
|
the object database:
|
|
```
|
|
$ ugit hash-object cats.txt
|
|
91a7b14a584645c7b995100223e65f8a5a33b707
|
|
$ ugit hash-object dogs.txt
|
|
fa958e0dd2203e9ad56853a3f51e5945dad317a4
|
|
```
|
|
|
|
Then we will create a "tree" object that has the content of:
|
|
```
|
|
91a7b14a584645c7b995100223e65f8a5a33b707 cats.txt
|
|
fa958e0dd2203e9ad56853a3f51e5945dad317a4 dogs.txt
|
|
```
|
|
|
|
And we will put this tree object into the object database as well. Then the OID
|
|
of the tree object will actually represent the entire directory! Why? Because we
|
|
can first retrieve the tree object by its OID, then see all the files it
|
|
contains (their names and OIDs) and then read all the OIDs of the files to get
|
|
their actual content.
|
|
|
|
What if our directory contains other directories? We'll just create tree objects
|
|
for them as well and we'll allow one tree object to point to another:
|
|
```
|
|
$ ls
|
|
cats.txt dogs.txt other/
|
|
$ ls other/
|
|
shoes.jpg
|
|
```
|
|
|
|
The root tree object will look like this:
|
|
```
|
|
blob 91a7b14a584645c7b995100223e65f8a5a33b707 cats.txt
|
|
blob fa958e0dd2203e9ad56853a3f51e5945dad317a4 dogs.txt
|
|
tree 53891a3c27b17e0f8fd96c058f968d19e340428d other
|
|
```
|
|
|
|
Note that we added a type to each entry so that we know if it's a file or a
|
|
directory. The tree that represents the "other" directory (OID 53891a3c27b17e0f8fd96c058f968d19e340428d) looks like:
|
|
```
|
|
blob 0aa186b09fd81e8cf449ba10eee6aff9711cc1ac shoes.jpg
|
|
```
|
|
We can think about this structure as a tree you know from Computer Science where
|
|
each entries' OID as a pointer to either another tree or to a file (leaf node).
|
|
|
|
Note that we actually save the tree objects with type "tree" in
|
|
`data.hash_object()` since we don't want the trees to be confused with regular
|
|
files.
|