Digital Qazaqstan · Engineering Labs

Build Git from Objects

What you will build

Create a Git object store that writes blobs, trees and commits and can clone a small repository.

Before you start

For developers who use Git and can work with files, compression and hashing.

Programme directory

Starter projects

Learning path

Project labs

  1. Store a blob
  2. Trees and commits
  3. Clone and verify

Project brief

Store a blob

Worked example and independent check

For three bytes abc, Git hashes the prefix blob 3, a zero byte, then abc. Compare your digest with git hash-object on a file containing exactly those bytes. Repeat after adding one newline.

Implementation stages

  1. GG4 · In this stage, you'll implement the git init command. You'll initialize a git repository by creating a .git directory and some files inside it.Full original stage (English)
  2. IC4 · In this stage, you'll read a blob from your git repository by fetching its contents from the .git/objects directory. You'll do this using the first of multiple "plumbing" commands we'll encounter in this challenge: git cat-file.
    Code and test examples

    Compare these source examples with your implementation. Commands and reference output are shown in their original notation.

    $ mkdir /tmp/test_dir && cd /tmp/test_dir
    $ /path/to/your_program.sh init
    $ echo "hello world" > test.txt # The tester will use a random string, not "hello world"
    $ git hash-object -w test.txt
    3b18e512dba79e4c8300dd08aeb37f8e728b8dad
    $ /path/to/your_program.sh cat-file -p 3b18e512dba79e4c8300dd08aeb37f8e728b8dad
    hello world
    Full original stage (English)
  3. JT4 · In the previous stage, we learnt how to read a blob. In this stage, we'll persist a blob by implementing the git hash-object command.
    Code and test examples

    Compare these source examples with your implementation. Commands and reference output are shown in their original notation.

    $ mkdir test_dir && cd test_dir
    $ /path/to/your_program.sh init
    $ echo "hello world" > test.txt
    $ ./your_program.sh hash-object -w test.txt
    3b18e512dba79e4c8300dd08aeb37f8e728b8dad
    Full original stage (English)

SynQ discussion

Show SynQ the input, your prediction and what actually happened. Ask which intermediate value to inspect first.

Learning path

Trees and commits

Worked example and independent check

Put the same file content under two names. Expect one blob ID and two distinct tree entries. Change only a filename and inspect which IDs change before creating a commit.

Implementation stages

  1. KP1 · Now that we've learnt how to read/write blobs, let's move onto our next Git object: the tree. In this stage, you'll read a tree object from storage by implementing the git ls-tree command.
    Code and test examples

    Compare these source examples with your implementation. Commands and reference output are shown in their original notation.

    $ mkdir test_dir && cd test_dir
    $ /path/to/your_program.sh init
    $ /path/to/your_program.sh ls-tree --name-only <tree_sha>
    your_repo/
      - file1
      - dir1/
        - file_in_dir_1
        - file_in_dir_2
      - dir2/
        - file_in_dir_3
    dir1
    dir2
    file1
    Full original stage (English)
  2. FE4 · In this stage, you'll write a tree to git storage by implementing the git write-tree command. To keep things simple, we won't implement an index, we'll just assume that all changes in the worktree are staged.
    Code and test examples

    Compare these source examples with your implementation. Commands and reference output are shown in their original notation.

    $ mkdir test_dir && cd test_dir
    $ /path/to/your_program.sh init
    $ echo "hello world" > test_file_1.txt
    $ mkdir test_dir_1
    $ echo "hello world" > test_dir_1/test_file_2.txt
    $ mkdir test_dir_2
    $ echo "hello world" > test_dir_2/test_file_3.txt
    $ /path/to/your_program.sh write-tree
    4b825dc642cb6eb9a060e54bf8d69288fbee4904
    Full original stage (English)
  3. JM9 · Let's move on to the last git object we'll be dealing with in this challenge: the commit. In this stage, you'll create a commit by implementing the git commit-tree command.
    Code and test examples

    Compare these source examples with your implementation. Commands and reference output are shown in their original notation.

    $ ./your_program.sh commit-tree <tree_sha> -p <commit_sha> -m <message>
    Full original stage (English)

SynQ discussion

Show SynQ the input, your prediction and what actually happened. Ask which intermediate value to inspect first.

Learning path

Clone and verify

Worked example and independent check

Use your own small repository as the source. Clone it into a clean directory and compare both the checked-out bytes and the tree ID. A tree comparison will catch filename changes that a content-only comparison misses.

Implementation stages

  1. MG6 · This is the last stage of the challenge, and probably the hardest! In this stage, you'll clone a public repository from GitHub. To do this, you'll use one of Git's Transfer protocols.Full original stage (English)

SynQ discussion

Show SynQ the input, your prediction and what actually happened. Ask which intermediate value to inspect first.

Learning path

Project brief

Project brief

Create a repository containing notes.txt and a nested file, write a tree and a commit, then clone your own small test repository into a clean directory.

Acceptance criteria

Compare blob and tree IDs with Git. Verify the commit points at the intended tree and that cloned files match their original bytes.

Explain your result

Why can two different filenames share one blob ID?

Project rubric

There are four checks, worth one point each. The project is complete when all four are evidenced. Save the source, run commands and observations together.

  1. Runs from a clean project with the documented command.
  2. Matches the expected reference result below.
  3. A second input and one boundary case have recorded expected and actual results.
  4. Explains the design decision below using a trace, intermediate value or measured observation.

Check your understanding

How many distinct blob IDs result from storing abc under two different filenames, with identical bytes?

  1. 1
  2. 2
  3. 3
Reveal the answer

1. Filenames belong in tree entries. The blob hashes the header and content bytes.

Sources and licences

Course adaptation and teaching notes by Digital Qazaqstan. Original project material by CodeCrafters.

git

MIT License

Copyright (c) 2022 CodeCrafters

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Как работает Git

Что вы создадите

Создайте хранилище объектов Git, которое записывает блобы, деревья и коммиты и умеет клонировать небольшой репозиторий.

Перед началом

Для тех, кто использует Git и умеет работать с файлами, сжатием и хешами.

Каталог программы

Стартовые проекты

Учебный маршрут

Практические модули

  1. Хранение блоба
  2. Деревья и коммиты
  3. Клонирование и сверка

Итоговое задание

Хранение блоба

Разбор примера и самостоятельная проверка

Для abc Git хеширует префикс blob 3, нулевой байт и abc. Сравните ID с git hash-object файла, содержащего ровно эти байты. Добавьте один перевод строки и повторите.

Этапы реализации

  1. GG4 · Создайте .git/objects, .git/refs и HEAD со ссылкой на ветвь.Исходное описание этапа (английский)
  2. IC4 · Найдите сжатый blob по ID, распакуйте и отделите заголовок до нулевого байта.
    Примеры кода и проверок

    Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.

    $ mkdir /tmp/test_dir && cd /tmp/test_dir
    $ /path/to/your_program.sh init
    $ echo "hello world" > test.txt # The tester will use a random string, not "hello world"
    $ git hash-object -w test.txt
    3b18e512dba79e4c8300dd08aeb37f8e728b8dad
    $ /path/to/your_program.sh cat-file -p 3b18e512dba79e4c8300dd08aeb37f8e728b8dad
    hello world
    Исходное описание этапа (английский)
  3. JT4 · Соберите blob из заголовка и содержимого. Хешируйте полные несжатые байты и запишите сжатый объект.
    Примеры кода и проверок

    Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.

    $ mkdir test_dir && cd test_dir
    $ /path/to/your_program.sh init
    $ echo "hello world" > test.txt
    $ ./your_program.sh hash-object -w test.txt
    3b18e512dba79e4c8300dd08aeb37f8e728b8dad
    Исходное описание этапа (английский)

Вопрос для SynQ

Покажите SynQ входные данные, ваш прогноз и фактический результат. Спросите, какое промежуточное значение проверить первым.

Учебный маршрут

Деревья и коммиты

Разбор примера и самостоятельная проверка

Запишите одинаковое содержимое под двумя именами. Ожидайте один ID блоба и две записи дерева. Измените только имя и проверьте, какие ID изменились, затем создайте коммит.

Этапы реализации

  1. KP1 · Прочтите дерево как последовательность записей: режим, имя и 20-байтовый ID.
    Примеры кода и проверок

    Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.

    $ mkdir test_dir && cd test_dir
    $ /path/to/your_program.sh init
    $ /path/to/your_program.sh ls-tree --name-only <tree_sha>
    your_repo/
      - file1
      - dir1/
        - file_in_dir_1
        - file_in_dir_2
      - dir2/
        - file_in_dir_3
    dir1
    dir2
    file1
    Исходное описание этапа (английский)
  2. FE4 · Рекурсивно запишите дерево каталога в порядке Git. Сохраните блобы, вложенные деревья и корневой ID.
    Примеры кода и проверок

    Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.

    $ mkdir test_dir && cd test_dir
    $ /path/to/your_program.sh init
    $ echo "hello world" > test_file_1.txt
    $ mkdir test_dir_1
    $ echo "hello world" > test_dir_1/test_file_2.txt
    $ mkdir test_dir_2
    $ echo "hello world" > test_dir_2/test_file_3.txt
    $ /path/to/your_program.sh write-tree
    4b825dc642cb6eb9a060e54bf8d69288fbee4904
    Исходное описание этапа (английский)
  3. JM9 · Запишите commit со ссылкой на дерево, необязательным родителем, автором, временем и сообщением.
    Примеры кода и проверок

    Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.

    $ ./your_program.sh commit-tree <tree_sha> -p <commit_sha> -m <message>
    Исходное описание этапа (английский)

Вопрос для SynQ

Покажите SynQ входные данные, ваш прогноз и фактический результат. Спросите, какое промежуточное значение проверить первым.

Учебный маршрут

Клонирование и сверка

Разбор примера и самостоятельная проверка

Клонируйте свой небольшой репозиторий в пустую папку. Сравните байты файлов и ID дерева. Сравнение дерева обнаружит переименование, которое пропустит проверка одного содержимого.

Этапы реализации

  1. MG6 · Клонируйте свой тестовый репозиторий и восстановите файлы из дерева выбранного коммита.Исходное описание этапа (английский)

Вопрос для SynQ

Покажите SynQ входные данные, ваш прогноз и фактический результат. Спросите, какое промежуточное значение проверить первым.

Учебный маршрут

Итоговое задание

Итоговое задание

Создайте репозиторий с notes.txt и вложенным файлом, запишите дерево и коммит, затем клонируйте свой тестовый репозиторий в пустой каталог.

Критерии проверки

Сравните ID блоба и дерева с Git. Убедитесь, что коммит ссылается на нужное дерево, а байты клонированных файлов совпадают с исходными.

Объясните результат

Почему у файлов с разными именами может быть одинаковый ID блоба?

Оценивание проекта

Четыре критерия дают по одному баллу. Для завершения проекта подтвердите все четыре. Сохраните вместе исходники, команды запуска и результаты.

  1. Запускается из чистой копии проекта по указанной команде.
  2. Даёт эталонный результат, указанный в критериях.
  3. Для второго входа и одного граничного случая записаны ожидаемые и фактические значения.
  4. Проектное решение ниже объяснено с опорой на трассировку, промежуточное значение или измерение.

Проверьте себя

Сколько разных ID блоба получится для двух файлов с разными именами и одинаковыми байтами abc?

  1. 1
  2. 2
  3. 3
Показать ответ

1. Имена хранятся в записях дерева. Хеш блоба зависит от заголовка и байтов содержимого.

Источники и лицензии

Учебная адаптация и пояснения Digital Qazaqstan. Исходные практикумы подготовлены CodeCrafters.

git

MIT License

Copyright (c) 2022 CodeCrafters

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Git ішкі құрылымы

Жоба нәтижесі

Blob, tree және commit нысандарын жазатын, шағын репозиторийді клондай алатын Git қоймасын жасаңыз.

Бастамас бұрын

Git пайдаланатын, файл, сығу және хештеумен жұмыс істей алатын әзірлеушілерге арналған.

Бағдарлама каталогы

Бастапқы жобалар

Оқу жолы

Тәжірибелік модульдер

  1. Blob нысанын сақтау
  2. Ағаштар мен коммиттер
  3. Клондау және тексеру

Қорытынды тапсырма

Blob нысанын сақтау

Мысал және өзіндік тексеру

abc үшін Git алдымен blob 3 префиксін, нөл байтты, кейін abc байттарын хештейді. Нәтижені осы үш байттық файлға git hash-object беретін ID-мен салыстырыңыз. Жол соңын қосып, қайталаңыз.

Іске асыру кезеңдері

  1. GG4 · .git/objects және .git/refs бумаларын, тармаққа сілтейтін HEAD файлын жасаңыз.Кезеңнің толық түпнұсқасы (ағылшын тілінде)
  2. IC4 · Сығылған blob нысанын ID бойынша тауып, ашыңыз да, нөл байтқа дейінгі тақырыбын бөліңіз.
    Код пен тексеру мысалдары

    Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.

    $ mkdir /tmp/test_dir && cd /tmp/test_dir
    $ /path/to/your_program.sh init
    $ echo "hello world" > test.txt # The tester will use a random string, not "hello world"
    $ git hash-object -w test.txt
    3b18e512dba79e4c8300dd08aeb37f8e728b8dad
    $ /path/to/your_program.sh cat-file -p 3b18e512dba79e4c8300dd08aeb37f8e728b8dad
    hello world
    Кезеңнің толық түпнұсқасы (ағылшын тілінде)
  3. JT4 · Blob тақырыбы мен мазмұнын біріктіріңіз. Сығылмаған толық байттарды хештеп, сығылған нысанды сақтаңыз.
    Код пен тексеру мысалдары

    Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.

    $ mkdir test_dir && cd test_dir
    $ /path/to/your_program.sh init
    $ echo "hello world" > test.txt
    $ ./your_program.sh hash-object -w test.txt
    3b18e512dba79e4c8300dd08aeb37f8e728b8dad
    Кезеңнің толық түпнұсқасы (ағылшын тілінде)

SynQ-ға сұрақ

SynQ-ға кіріс деректі, өз болжамыңызды және нақты нәтижені көрсетіңіз. Алдымен қай аралық мәнді тексеру керегін сұраңыз.

Оқу жолы

Ағаштар мен коммиттер

Мысал және өзіндік тексеру

Бір мазмұнды екі атаумен сақтаңыз. Бір blob ID-і және ағашта екі жазба болуы тиіс. Тек атауды өзгертіп, қай ID өзгергенін тексеріңіз де, коммит құрыңыз.

Іске асыру кезеңдері

  1. KP1 · Ағашты режим, атау және 20 байттық ID бар жазбалар тізбегі ретінде оқыңыз.
    Код пен тексеру мысалдары

    Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.

    $ mkdir test_dir && cd test_dir
    $ /path/to/your_program.sh init
    $ /path/to/your_program.sh ls-tree --name-only <tree_sha>
    your_repo/
      - file1
      - dir1/
        - file_in_dir_1
        - file_in_dir_2
      - dir2/
        - file_in_dir_3
    dir1
    dir2
    file1
    Кезеңнің толық түпнұсқасы (ағылшын тілінде)
  2. FE4 · Бума ағашын Git ретімен рекурсивті жазыңыз. Blob нысандарын, ішкі ағаштарды және түбір ID-ін сақтаңыз.
    Код пен тексеру мысалдары

    Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.

    $ mkdir test_dir && cd test_dir
    $ /path/to/your_program.sh init
    $ echo "hello world" > test_file_1.txt
    $ mkdir test_dir_1
    $ echo "hello world" > test_dir_1/test_file_2.txt
    $ mkdir test_dir_2
    $ echo "hello world" > test_dir_2/test_file_3.txt
    $ /path/to/your_program.sh write-tree
    4b825dc642cb6eb9a060e54bf8d69288fbee4904
    Кезеңнің толық түпнұсқасы (ағылшын тілінде)
  3. JM9 · Ағаш сілтемесі, қажет болса ата-анасы, авторы, уақыты және хабары бар commit жазыңыз.
    Код пен тексеру мысалдары

    Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.

    $ ./your_program.sh commit-tree <tree_sha> -p <commit_sha> -m <message>
    Кезеңнің толық түпнұсқасы (ағылшын тілінде)

SynQ-ға сұрақ

SynQ-ға кіріс деректі, өз болжамыңызды және нақты нәтижені көрсетіңіз. Алдымен қай аралық мәнді тексеру керегін сұраңыз.

Оқу жолы

Клондау және тексеру

Мысал және өзіндік тексеру

Өз шағын репозиторийіңізді бос бумаға клондаңыз. Файл байттары мен ағаш ID-ін салыстырыңыз. Тек мазмұнды тексергенде байқалмайтын атау айырмасын ағаш көрсетеді.

Іске асыру кезеңдері

  1. MG6 · Өз сынақ репозиторийіңізді клондап, таңдалған коммит ағашынан файлдарды қалпына келтіріңіз.Кезеңнің толық түпнұсқасы (ағылшын тілінде)

SynQ-ға сұрақ

SynQ-ға кіріс деректі, өз болжамыңызды және нақты нәтижені көрсетіңіз. Алдымен қай аралық мәнді тексеру керегін сұраңыз.

Оқу жолы

Қорытынды тапсырма

Қорытынды тапсырма

notes.txt және ішкі бумадағы файлы бар репозиторий құрыңыз. Ағаш пен коммит жазып, өзіңіздің сынақ репозиторийіңізді бос бумаға клондаңыз.

Қабылдау шарттары

Blob және tree ID-лерін Git-пен салыстырыңыз. Коммиттің дұрыс ағашқа сілтеуін және клондалған файл байттарының түпнұсқамен бірдей екенін тексеріңіз.

Нәтижені түсіндіріңіз

Атауы бөлек екі файлдың blob ID-і неліктен бірдей болуы мүмкін?

Жобаны бағалау

Төрт өлшемнің әрқайсысы бір ұпай береді. Жобаны аяқтау үшін төртеуін де дәлелдеңіз. Кодты, іске қосу командаларын және нәтижелерді бірге сақтаңыз.

  1. Құжатталған команда арқылы жобаның таза көшірмесінен іске қосылады.
  2. Төмендегі шартта көрсетілген эталон нәтижені береді.
  3. Екінші кіріс пен бір шекаралық жағдай үшін күтілетін және нақты нәтиже жазылған.
  4. Төмендегі жобалық шешім орындалу ізіне, аралық мәнге не өлшеуге сүйеніп түсіндірілген.

Өзіңізді тексеріңіз

Байттары бірдей abc мазмұны екі түрлі атаумен сақталса, неше бөлек blob ID шығады?

  1. 1
  2. 2
  3. 3
Жауапты көрсету

1. Атаулар ағаш жазбаларында сақталады. Blob хеші тақырып пен мазмұн байттарына тәуелді.

Дереккөздер мен лицензиялар

Оқу материалын бейімдеп, түсіндірмелерді дайындаған Digital Qazaqstan. Бастапқы практикумдардың авторы CodeCrafters.

git

MIT License

Copyright (c) 2022 CodeCrafters

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.