Fundamentals of Git
Contents
Explore some essential aspects of the version control tool Git.
Concept
Initially, as a newcomer, I confused Git with GitHub (a platform), not realizing Git is fundamentally a local tool. Some refer to it as a version control tool, a file system, or even a database with key-value pairs.
To harness its capabilities, it’s crucial to understand the primary command:
|
|
This command creates a .git folder in your working directory, housing all information of your local repository. If deleted, your directory loses its Git repository status.
Diving into the .git folder, let’s explore its contents, focusing mainly on the objects folder that stores commit objects, tree objects (directories), and blob objects (file contents).
|
|
Folders in objects are named using the first two characters of the 40-character SHA-1 hash of a Git object. All Git objects, including blobs, trees, and commits, are uniquely identified by a 40-character hexadecimal string.
For instance, under folder 02, there’s a file:
|
|
This file is a commit object representing a snapshot of your project. ‘Tree’ refers to the project structure, which can be viewed by decompressing:
|
|
The ‘parent’ tag indicates the preceding commit. A common query: How can I determine if a document is a blob, tree, or commit?
|
|
So `git cat-file` is a really useful command if you want to dig the rabbit hole of your project version history. Flag `-p` means pretty print and `-t` shows object type.
Fours Areas
Understanding the four key areas - working directory, staging area, local repository, and remote repository- is crucial.
`git add` moves changes to the staging area. `git commit` then commits these changes from staging to the local repository (located in the .git folder).
Committing creates a snapshot of your project, encompassing file contents, directory trees, and metadata like time and committer. It yields a commit object linking to your latest commit.
Each commit acts like a node pointing to its predecessor.
Branches and Head
Different branches in Git means different pointers to versions. The image below shows a project with two branches(main and sub).
Creating a new branch is akin to creating a new pointer. When committing across multiple branches, how does Git know which branch to commit to? Here, the HEAD pointer comes into play.
HEAD typically points to the latest commit on the current branch but can be redirected to earlier commits if needed.
Conclusion
While many tutorials offer Git commands, truly understanding Git requires diving beneath the surface. A deeper comprehension of its inner workings can be invaluable in navigating complex scenarios.
Author Jeffery@slc
LastMod 2023-11-08