Git
Notes |#Notes on Git:
Git is a distributed version control system that allows
multiple developers to work on the same project without
interfering with each other’s progress. It is widely used in
software development and helps track changes, collaborate
effectively, and manage code across various environments.
Below is a comprehensive guide covering all major aspects of
Git, from the basics to advanced features.
1, Introduction to Git
Version Control: Git tracks changes made to files, allowing
you to revert back to previous versions or track changes over
time.
| Distributed System: Unlike centralized version control
||_systems, Git allows each user to have a full copy of the
repository, including its history, on their local machine.
Branching and Merging: Git excels at allowing developers to
work on separate features in parallel using branches, then
later merge their changes.
2. Basic Git WorkflowThe general workflow of Git involves the following steps:
1, Clone: Create a copy of a remote repository locally.
2. Edit: Make changes to files locally.
3. Stage: Select the changes to be included in the next
commit.
4, Commit: Save a snapshot of your changes with a
descriptive message.
S. Push: Upload the changes to a remote repository.
6. Pull: Fetch and merge changes from a remote repository
to your local repository.
3. Common Git Commands
Here are some frequently used Git commands:
3.) Starting a New Repositorygit init: Initializes a new Git repository in the current
directory.
git clone : Creates a local copy of a remote
repository.
3.2 Viewing Repository Status
git status: Displays the status of the working directory and
staging area.
git log: Shows the commit history, including commit
messages, authors, and dates.
git diff: Shows the differences between the working directory
and the staging area, or between two commits.
| 33 Staging and Committing Changes
git add : Stages a specific file for commit.
git add .: Stages all modified files in the current directory
and subdirectories.
git commit -m "message": Commits the staged changes with
a message describing the changes.
git commit -a -m "message": Commits all changes totracked files directly without staging.
3.9 Working with Branches
git branch; Lists all branches in the repository, highlighting
the current branch,
git branch : Creates a new branch.
git checkout : Switches to an existing
branch.
git checkout -b : Creates a new branch and
switches to it.
git merge : Merges changes from the
specified branch into the current branch.
git branch -d ; Deletes a branch that has
already been merged.
3.5 Working with Remote Repositories
git remote -v: Shows the URLs of remote repositories.
git push : Pushes changes to the remote
repository.git pull : Fetches and merges changes
from the remote repository.
git fetch : Downloads changes from a remote
repository without merging them.
git push origin --delete : Deletes a branch
from the remote repository.
4, Branches and Merging
Branching allows you to create separate versions of the code
to work on different features without disturbing the main
codebase.
Creating a branch: git branch
|| Switching between branches: git checkout
|| Merging: Once the work on a branch is done, it can be
merged back into the main branch (often called master or
main) using git merge .
Fast-forward merge: If the branch being merged is ahead of
the current branch and doesn’t have any conflicting changes,
a fast-forward merge happens.
Conflict resolution: If two branches have changes to the
same line in a file, a merge conflict will occur, Git will markthe conflicts in the file, and manual intervention is required
to resolve them.
S. Handling Merge Conflicts
Merge conflicts occur when changes made in different
branches cannot be automatically merged by Git. Here’s how
to resolve them:
1, Identify the conflict: After attempting a merge, Git will
mark the files with conflicts and stop the merge process.
2. Edit the conflicted files: Open the conflicting files and
look for the markers (e.g., <<<<<<<, >>>>>>>),
then resolve the conflict by editing the file.
3. Stage the resolved files: After resolving the conflicts,
stage the files using git add .
4. Commit the merge: Finalize the merge by committing it
using git commit.
6. Git CollaborationWhen working with multiple developers, Git offers tools to
synchronize changes across different machines:
Forking: Forking creates a personal copy of someone else's
repository. You can freely make changes to this copy and
later propose these changes to the original project via pull
requests.
Pull Requests (PR): After making changes to a forked
repository, a pull request is created to propose merging your
changes into the main repository.
Issues and Labels: Git platforms like GitHub and GitLab
allow users to create issues for tracking bugs or tasks, and
labels to categorize them.
Rebase: Instead of merging branches, rebasing allows you to
move or combine a sequence of commits to a new base
commit. It’s a cleaner alternative to merging in some
workflows.
7. Advanced Git Features
7.1 Git Rebase
Rebase is often used to maintain a cleaner project history by
moving the base of your branch to a newer commit. It
applies your branch’s changes on top of another branch.Basic rebase: git rebase re-applies your changes on
top of the specified branch.
Interactive rebase: git rebase -i allows you to
interactively edit the commit history, such as reordering,
sguashing, or editing commits.
7.2 Stashing Changes
Git stash is useful when you need to switch branches but
want to keep your uncommitted changes:
git stash: Stashes changes that are not yet committed.
git stash pop: Applies and removes the most recent stash.
git stash list: Lists all stashes.
git stash apply: Applies a stash without removing it from the
stash list.
7.3 Tagging
Git tags are used to mark specific points in history as
important, such as release versions.
Creating a tag: git tag Listing tags: git tag
Pushing tags to remote: git push origin
7.4 Git Submodules
Submodules allow you to include and manage external
repositories as part of your project. They are useful when you
want to embed a separate project into your own repository.
Adding a submodule: git submodule add
Cloning a repository with submodules: git clone --recurse-
submodules
|| 8. Best Practices in Git
Commit early and often: Small, frequent commits are easier
to manage than large, infrequent ones.
Write meaningful commit messages: Each commit should
have a message explaining why the change was made.
Keep commits focused: A commit should ideally do one
thing. If it includes unrelated changes, split it into separate
commits.| Rebase before merging: When working with feature branches,
it’s good practice to rebase before merging to keep the
project history linear and clean.
|| Sync regularly with the main branch: Frequently pull the
latest changes from the main branch to avoid conflicts later.
Use branches for features: Always create a new branch for
each feature or bug fix.
| 9. Git is a powerful and flexible tool that helps teams
|| collaborate on projects and manage changes efficiently. By
understanding its basic and advanced features, you can
streamline your workflow and improve collaboration. The use
of branching, merging, and rebasing, along with features like
|| tags, stashing, and submodules, enables teams to manage
code effectively across different environments. The power of
| Git lies not just in its basic functionality but in how it
enables distributed teams to collaborate and maintain high-
| quality codebases.
| 10. Git Internals
|| To understand Git better, it's essential to dive into how it
|| works behind the scenes. Git's internal structure is a critical
|| aspect that makes it efficient for handling large projects and
distributed workHows.
10.1 Git Directory StructureGit uses a specific directory structure to store the
repository's information. This structure is located in the git
folder, which is created when you initialize a Git repository.
git/lobjects: Stores all the content in the repository as
"objects." Each object represents a piece of data, such as a
commit, tree (directory), or file. Git uses a hashing
algorithm CSHA-I) to name and store these objects.
Commits: A commit object contains the commit data,
including the author, date, commit message, and the tree
object (which represents the directory structure).
Trees: A tree object stores the structure of the directory,
with pointers to blobs Cfile contents) and other tree objects.
Blobs: A blob object stores the file content itself.
| git/refs: Contains references to the branches, tags, and
other Git objects.
refs/heads/: Stores references for branches.
refs/tags/: Stores references for tags.
refs/remotes/: Stores references for remote branches.10.2 Git Object Database
Git's object database stores all the data and historical
information in the repository. This allows Git to be a fast,
distributed, and lightweight version control system. The
objects include:
| Commit Objects: Each commit stores a snapshot of the
project at a specific point in time.
Tree Objects: Tree objects are used to represent directory
structures, and they point to other tree objects or file blobs.
Blob Objects: Blobs are the raw content of files, which are
stored in the object database.
| 10.3 Commit Hash
| Each commit is identified by a unigue SHA-I hash, typically
| displayed as a 40-character string. This hash is generated
| based on the content of the commit (including the tree,
message, and author), Git uses this hash to track the
commit history and verify data integrity.
Il, Advanced Git Workflows
As teams grow and projects become more complex, advanced
Git workflows become crucial for maintaining consistency and
collaboration. Below are some common workflows andstrategies for working with Git at scale.
I) Feature Branch Workflow
The feature branch workflow encourages the creation of a
new branch for each feature, bug fix, or improvement. This
isolates new work from the main branch typically main or
master) until the feature is completed.
Steps:
1, Create a new branch: git checkout -b .
2. Work on your feature and commit changes regularly.
3. Once the feature is complete, rebase or merge with the
main branch,
4. Open a pull request to merge the feature branch into the
main branch,
S. After review and approval, merge and delete the feature
branch.This workflow keeps the main branch clean and allows
features to be developed independently.
|| 11.2 Gitflow Workflow
The Gitflow workflow is a branching model that defines strict
roles for different branches. It involves multiple primary
branches and auxiliary branches to manage releases, hotfixes,
and features.
Branches:
master: Contains the production-ready code. This branch
should always be stable.
develop: The integration branch where all features are
||_merged and tested before being released.
feature/"; Feature branches are created from develop and
| merged back into develop after completion.
|| release/": When the code in develop is ready for a release, a
release branch is created, This branch allows for last-minute
fixes before merging into master and develop.
hotfix/"; Hotfix branches are created from master to quickly
address issues in production, Once fixed, they are merged
back into both master and develop.Gitflow is useful for managing complex release cycles and
large teams with multiple ongoing developments.
1.3 Forking Workflow
The forking workflow is often used in open-source projects or
any situation where contributors don't have write access to
the main repository. It allows contributors to create their
own copies (forks) of the project, make changes, and then
propose those changes via pull requests.
Steps:
1, Fork the repository on GitHub Cor another Git hosting
platform).
2. Clone your forked repository locally: git clone .
3. Create a new branch for your feature: git checkout -b
.
4. Commit your changes and push to your forked repository:
git push origin .
S. Open a pull request to propose your changes to the
original repository.This workflow is commonly used in open-source software
development, where the maintainers of a repository review
and merge contributions from the community.
12, Git Hooks
| Git hooks are scripts that can be triggered by certain Git
actions, such as committing, pushing, or merging. They can
be used to automate tasks, enforce policies, or run tests
before performing certain actions.
| 12.1 Common Git Hooks
pre-commit: Triggered before a commit is created, Used for
tasks such as linting code or checking for formatting issues.
commit-msg: Triggered after the commit message is entered
but before the commit is finalized. Used to enforce commit
||_message conventions.
| pre-push: Triggered before a push operation. It can be used
to run tests or ensure that code is properly built.
post-merge: Triggered after a merge. It can be used to
perform actions like notifying stakeholders or running cleanup
scripts.
Git hooks are stored in the .git/hooks/ directory and can be
customized to suit the needs of your workflow.13. Git on Large Projects
As projects scale in size and the number of developers grows,
managing Git repositories becomes increasingly important.
Here are some tips for handling large projects efficiently:
13) Shallow Cloning
If you don’t need the full history of a repository and only
need the latest state of the project, you can perform a
shallow clone.
Shallow clone: git clone --depth | creates a
clone of the repository but with only the most recent
commit, significantly reducing the size of the repository.
13,2 Submodules for Large Repositories
| When working with large projects that contain multiple
separate repositories, Git submodules allow you to embed
repositories inside one main project.
Adding a submodule: git submodule add
Updating submodules: git submodule update --init --recursive
13.3 Git LFS (Large File Storage)Git LFS is a tool used for handling large files Csuch as
images, videos, and datasets) that are not suitable for Git's
standard storage system.
Install Git LFS: git Ifs install
Track a file type: git Ifs track "* psd"
Add and commit files: git add , git commit -m "Add
large file"
14, Security and Access Control in Git
When managing sensitive code and collaborating with a
team, security is paramount. Here are some methods to
manage access control and security in Git repositories.
| 14.1 SSH Keys
SSH keys are a secure way to authenticate with remote
repositories (especially GitHub or GitLab) without needing to
enter a password every time you interact with the repository.
Generating SSH key: ssh-keygen -t rsa -b 4096 -C
"gour_email@example.com"
Adding SSH key to GitHub: Copy the public key
(~/.sshlid_rsa.pub) and add it to your GitHub account under
"SSH and GPG keys."19.2 Access Control with Git Hosting Services
|| Platforms like GitHub, GitLab, and Bitbucket provide built-in
access control features to manage who can read and write to
repositories.
Teams and Permissions: Assign different permission levels
admin, write, read) to users or teams within the repository.
|| Private Repositories: Make repositories private to restrict
access to authorized users only.
|| 1S. Git is an essential tool for modern software development,
|| providing robust version control capabilities, enabling
collaboration, and allowing for effective management of both
small and large codebases. Understanding how Git works
| internally and utilizing advanced workHows and features
|| ensures that your development process remains efficient,
|| scalable, and secure, Mastery of Git is crucial for any
|| developer, whether you're working alone on a project or as
part of a large team.
|| 16. Git GUI Tools
| While the command line is powerful, many developers prefer
graphical user interfaces (GUIs) for working with Git. GUIs
make it easier to visualize your repository and commit history
and provide simpler access to some of Git's complex features.
Below are some of the most popular Git GUI tools:16.1 GitHub Desktop
GitHub Desktop is a user-friendly GUI that integrates
seamlessly with GitHub repositories. It simplifies the process
of cloning, branching, committing, and pushing changes, Key
features include:
Visual interface: View your commit history and changes
between commits.
Simplified branching and merging: Easily create branches and
merge changes without dealing with the command line.
Pull request management: View and manage pull requests
from a GUI.
16.2 SourceTree
| SourceTree is a popular Git GUI for Windows and macOS, It
|| supports Git, Mercurial, and other version control systems,
and has the following features:
Graphical commit history: Visualize your commit history,
branches, and merges.
Git-How support: Built-in support for GitFlow workflow.
Submodule support: Handle Git submodules through a simple
interface.16.3 GitKraken
GitKraken is another powerful Git GUI tool that is available
cross-platform (Windows, macOS, and Linux). It’s known for
its beautiful interface and easy-to-use functionality.
Intuitive interface: The interface is designed to make
complex Git operations more understandable, such as
branching, merging, and rebasing.
Cross-platform support: Available on Windows, macOS, and
Linux.
Integration with GitHub and GitLab: It can easily integrate
with your GitHub or GitLab repositories to manage pull
requests and issues.
|| 16.4 TortoiseGit
| TortoiseGit is a Windows-based Git GUI that integrates
directly into the Windows Explorer interface. It’s great for
users who prefer using the file explorer for version control.
Explorer Integration: Right-click on files in Windows Explorer
to perform Git operations.
Commit history and log viewer: View the commit history and
details of individual commits in a graphical interface.Configurable: Highly customizable, allowing you to adjust the
interface and features.
17, Git Best Practices
To ensure smooth and efficient use of Git, it’s important to
follow certain best practices. These help avoid common
pitfalls like messy commit histories, merge conflicts, and
unnecessary bloat in the repository.
17.1 Write Clear Commit Messages
Clear commit messages are essential for understanding the
history of the project. Follow these guidelines:
Use present tense: Commit messages should describe what
the commit does, not what it did. Example: "Fix bug in login
|| form" instead of "Fixed bug in login form."
|| Be concise but descriptive: A short description (S0
characters or less) followed by a detailed explanation if
necessary.
Use the imperative mood: "Add feature" rather than "Added
feature."
17.2 Commit Often, But With MeaningFrequent commits make it easier to track changes and
isolate bugs. However, make sure each commit has a clear
purpose, Don’t commit changes that are incomplete or
|| unrelated to the task at hand.
Small, logical commits: Instead of one large commit with
unrelated changes, commit logical chunks that focus on a
single task.
Atomic commits: Each commit should represent a single,
logical change. This makes it easier to understand the
history of changes and revert when necessary.
17.3 Avoid Committing Sensitive Data
|| Never commit sensitive data like passwords, API keys, or
private files to a Git repository. If such data gets committed
| accidentally:
|| Use .gitignore: This file tells Git which files and directories to
ignore. For example, add “env to gitignore to prevent
environment files from being tracked.
Remove sensitive data: If sensitive data is committed by
mistake, you can use tools like git filter-branch or BFG
Repo-Cleaner to scrub the sensitive data from the Git
history.17.4 Rebase for Clean History
Rebasing helps keep a clean, linear commit history by
integrating changes from one branch into another without
creating unnecessary merge commits.
Rebase instead of merge: Use git rebase when incorporating
changes from another branch, especially for feature
branches.
Rebase interactively: git rebase -i allows you to rewrite
history by editing, squashing, or dropping commits.
17.5 Use Tags for Releases
Git tags allow you to mark specific commits as important,
typically used to mark release points (e.g., vl.0.0). Tags are
|| similar to branches but are immutable and don't change over
time.
| Create a tag: git tag vl.0.0
Push tags to the remote: git push origin v1.0.0
13. Git Troubleshooting
Even with best practices, sometimes Git can be tricky, Below
are common Git problems and how to solve them.18.1 Merge Conflicts
Merge conflicts happen when Git can’t automatically
combine changes made in different branches. It occurs when
two branches modify the same line of a file or when one
branch deletes a file that another branch modified.
Resolve conflicts manually: Git marks the conflicts in the
fles with <<<<<<<, == =, and >>>>>>>. Edit the file
to resolve the conflicts and remove these markers.
Use a merge tool: Tools like meld, kdiff3, or Beyond Compare
can be used to visually merge files and resolve conflicts.
18.2 Detached HEAD State
The "detached HEAD" state occurs when you checkout a
commit instead of a branch, This means you're no longer on
a branch, and any new commits won't be associated with a
branch.
Fix by creating a branch: To get out of the detached HEAD
state, create a new branch with git checkout -b .
18.3 Lost Commits
Sometimes, commits can be lost if you accidentally reset orcheckout a branch in a way that discards changes.
Use reflog to recover lost commits: Git keeps track of
changes to the HEAD reference in the reflog. You can use
git reflog to find the commit hash and restore it.
18.4 Stashing Changes
If you need to switch branches but have uncommitted
changes, you can stash them temporarily.
Stash changes: git stash will store your changes in a safe
place.
Apply stashed changes: git stash apply will bring back your
stashed changes.
| List stashes: git stash list shows all stashes in your
repository.
19, Git for Continuous Integration/Continuous Deployment
(Ci/CD)
Git is integral to modern C1/CD workflows, enabling
automated testing, building, and deployment processes. Git-
based CI/CD tools like Jenkins, Travis Cl, and GitLab Cl
allow you to automate testing and deployment based on code
changes in your Git repository.19.1 Automated Testing
Using Cl tools, you can automatically run unit tests,
integration tests, and linting every time you push code to
the repository. This ensures that bugs are caught early.
|| 19.2 Automated Deployment
Once code is tested and merged, Git can trigger deployments
to staging or production environments. For example, you can
set up a Cl pipeline to deploy a web application to AWS,
Heroku, or another cloud platform every time code is merged
into the main branch.
| 20. Git is a powerful tool for version control and
collaboration, but its complexity can sometimes be
overwhelming. By understanding Git’s internal mechanisms,
| using best practices, and adopting advanced workflows, you
|_can significantly improve your development process. Whether
you're working alone or in a large team, mastering Git
| ensures that you can efficiently manage your codebase,
|| collaborate effectively, and maintain a clean and stable
project history. With the right tools and strategies, Git
becomes a cornerstone for modern software development.
$0 most important Git commands and concepts :
|| 1. Initialize a Git repositoryCommana: git init
Initializes a new Git repository in the current directory.
2. Clone a repository
Commana: git clone
Clones an existing remote repository to your local machine.
3, Check the current status of the repository
Command: git status
Displays the state of the working directory and staging area.
4. Add files to the staging area
Command: git add
Stages changes in files for commit.
S. Commit changes
Command: git commit -m ""