This guide provides a walkthrough of a basic git
workflow and attempts to describe what is happening under the hood as commands are run.
- We can create a new git repository using
git init
which creates a hidden directory called.git/
- The
init
process fills.git/
with a special file calledHEAD
that contains the name of the branch or the commit we're on - If the contents of the
HEAD
file is the name of a branch, then we can look in.git/refs/heads/<branchname>
e.g..git/refs/heads/main
to figure out the specificcommit
the branch is on: e.g.ba012fe642b796af4e5735a7e6c83e4e90f9e62b
- When we first start out,
HEAD
is likely themain
branch which maps to anil
(non-existant) commit
- We can stage files to be committed to a checkpoint by using the command:
git add
and then commit them usinggit commit -"message"
. - When a commit is created, 3 types of data objects are created under the hood and stored within
.git/objects
:
blobs
of data representing changes to our files (additions, deletions)trees
that show the state of the- a
commit
object that has aparent
commit, a hashid
, and a pointer to atree
object which describes the state of the project and contains a mapping of of what files and directories exist, where, and what changes were made to them (blobs
)
- After a commit is made, the
./git/refs
directory is updated so the branch inHEAD
points to the correct newcommit
git log
can be used to see the chain of prior commits andgit reflog
may be used to see a history of recent actions that have been run using git.- The
git reset --soft
command can be used to reset git back-in-time to a previous a commit while retaining all the staged file changes that were involved in the original commit.
- This is useful if you checked in a file you didn't mean to and want to go back to a previous commit with all your progress, make changes, and then re-commit.
git commit --ammend
may be used to overwrite the last commit with new changes or a new messagegit reset --hard
will cleanly reset your branch back to a specific commit and not bring any of your staged files with it
- If you make a mistake and do a
--hard
reset to a past commit, your newer commits will no longer appear ingit log
and so it can be difficult to recorer. - The history in
git reflog
can be used to help yougit reset
back to the right commit containing your precious files
The anatomy of a commit
Commit: <HASH ID>
- reference to its `PARENT` (previous commit)
- reference to its `TREE` database (phonebook) of files and folders related to this commit, e.g.:
blob1 readme.txt
blob2 file.txt
subdirectory (tree)