0% found this document useful (0 votes)
16 views32 pages

GIT - According to Syllabus

The document provides an overview of Version Control Systems (VCS), focusing on Git as a popular distributed version control system. It covers the basics of version control, installation of Git, basic commands, and advanced operations such as branching, merging, and collaboration. Additionally, it discusses various workflows for managing projects effectively with Git.

Uploaded by

dimpalrajput511
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views32 pages

GIT - According to Syllabus

The document provides an overview of Version Control Systems (VCS), focusing on Git as a popular distributed version control system. It covers the basics of version control, installation of Git, basic commands, and advanced operations such as branching, merging, and collaboration. Additionally, it discusses various workflows for managing projects effectively with Git.

Uploaded by

dimpalrajput511
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

GIT

Version Control Made Simple, Collaboration Made Powerful


- Krishnan

Introduction to Version Control and GIT Basics


1. Version Control Systems

Version Control Systems (VCS) are essential tools in software development and project management, allowing
multiple contributors to work together on a project while keeping track of changes, avoiding conflicts, and maintaining
a detailed history of modifications.

Version Control

Version control is the practice of tracking changes to files (code, documents, etc.) in a systematic way. It helps in
managing multiple versions of a file, keeping a detailed history of who made changes, what changes were made, and
when.

Types of Version Control Systems

1. Centralized Version Control (CVCS):


o A central server holds the code, and all changes must be
committed to this server (e.g., SVN).
o Advantages: Simple and straightforward for small
teams.
o Disadvantages: If the server fails, access to the project
is lost, and offline work is limited.

2. Distributed Version Control (DVCS):


o Every developer has a full copy of the repository also in
the cloud repository (e.g., Git).
o Advantages: Offline work possible, no central point of
failure, easier collaboration.
o Disadvantages: Slightly more complex setup, larger initial
clone due to full history.

https://orion021.github.io/krishnan_t/ 1 | 😁 👻 ✌️ 😎
GIT – Version Control Made Simple Collaboration Made Powerful

Benefits of Version Control

• Collaboration: Developers can work independently on different parts of the project and merge changes
without overwriting each other's work.
• Backup and Recovery: Since every change is saved, it's easy to recover previous versions or undo mistakes.
• Tracking Project History: Detailed logs of changes (commits) are stored, providing insights into what changed,
why, and by whom, making it easier to track the evolution of a project.
• Code Conflict Resolution: When multiple people work on the same files, version control helps merge their
changes, minimizing conflicts and reducing the risk of lost work.
• Branching and Experimentation: Developers can create isolated branches for new features or experiments,
keeping the main project stable until changes are ready to be merged.

Popular Version Control Systems

Git: A distributed version control system, Git is the most widely used VCS due to its flexibility, speed, and support
for branching and merging. It allows each developer to have a local repository with the full project history.

SVN (Subversion): A centralized version control system, SVN stores all changes on a central server. It’s still used in
some organizations but lacks the flexibility and offline capabilities of Git.

Mercurial: Similar to Git in its distributed model, Mercurial is known for being simple and user-friendly but is less
widely adopted.

2. Getting Started with Git

Installing Git

• Windows:

1. Visit the official Git website. Download the Windows installer.

2. Run the installer and follow the prompts, accepting the default settings for most users. You’ll also be
prompted to install Git Bash, which provides a command-line interface for executing Git commands.

• macOS:

Make sure you have homebrew installed in the Mac Device. To install Git using Homebrew by run the
following command in the Terminal:

brew install git

• Linux:

Most Linux distributions come with Git available in their package managers. Use the following command
based on your distribution:

▪ For Ubuntu/Debian: sudo apt install git

▪ For Fedora: sudo dnf install git

▪ For Arch Linux: sudo pacman -S git

https://orion021.github.io/krishnan_t/ 2 | 😁 👻 ✌️ 😎
GIT – Version Control Made Simple Collaboration Made Powerful

After installing Git, to verify whether GIT installed or not execute the below command in Terminal or bash window.
This will display the version of git we have installed

git --version

It’s essential to configure it with your user information. To do that execute commands in the terminal:

git config --global user.name "YourName"


git config --global user.email "[email protected]"

to verify configurations, we can run the below commands:

git config --list

This command displays your current configuration settings.

3. Basic Git Commands

Initializing Repositories

Git manages project versions through repositories. To create a new repository, follow these steps:

1. Navigate to Your Project Directory: Open your terminal and change to your project folder using the cd
command. For example:

cd path/to/your/project

2. Initialize the Repository: Run the command:

git init

This command creates a hidden .git directory within your project folder. This directory contains all the metadata
and history for your project.

3. Checking the Repository Status: After initializing, you can check the status of your repository using:

git status

This command shows the current state of the repository, indicating any untracked or modified files. If you see
"No commits yet," it means you haven't added any files to your repository yet.

4. Understanding the .git Directory: The .git directory is crucial for Git's functionality. It contains:

o Objects: Store the actual data (blobs for file content, trees for directories).

o Refs: Keep track of branches and tags.

o HEAD: Points to the current branch or commit.

https://orion021.github.io/krishnan_t/ 3 | 😁 👻 ✌️ 😎
GIT – Version Control Made Simple Collaboration Made Powerful

4. Basic Git Operations

Cloning Repositories

Cloning is the process of creating a local copy of a remote repository. This is useful when you want to contribute
to an existing project or access its files.

1. Find the Repository URL: Go to the repository page on GitHub and locate the HTTPS or SSH URL.

2. Clone the Repository:


git clone https://github.com/username/repository.git

This command creates a directory named after the repository and copies all files and the entire history into it.

3. Navigate into the Cloned Directory: Once cloned, change into the newly created directory:

cd repository

4. Explore the Cloned Repository:

git log or git log --oneline or git log --graph

This command displays the commit history, including commit hashes, authors, dates, and messages. So whenever
it is needed to see the history of the repository use any of the above commands.

Making Changes and Adding Files(Staging)

After modifying files or creating new ones, you need to stage them before committing. Staging files prepares them
for a commit.

1. Stage Individual Files: To add a specific file to the staging area, use:
git add filename

2. Stage All Changes: To stage all modified and new files, use:

git add . or: git add -A

This stages all changes, including deletions.

3. Check Staged Files: This command what is the current status of repository you cloned to local directory(folder).

git status

Committing Changes

Committing saves your changes to the local repository with a descriptive message.

1. Create a Commit: After staging your files, create a commit with a message describing the changes:

git commit -m "Your commit message here"

It’s good practice to write concise, informative commit messages.

2. Amending a Commit: If you need to modify the last commit (e.g., to add missed changes), use:
git commit --amend

This opens an editor to modify the commit message or include additional changes staged before running the
command.

https://orion021.github.io/krishnan_t/ 4 | 😁 👻 ✌️ 😎
GIT – Version Control Made Simple Collaboration Made Powerful

5. Git Help and Documentation

Using Git Help

Getting Help: Git includes a robust help system. You can access help for any command with:

git help <command>

For example, to get help on the commit command:

git help commit

Understanding Config Files

Git stores configuration settings at three different levels, allowing developers to customize Git's behaviour on a
global, system, or repository-specific level. Understanding and managing these configuration files is key to optimizing
your workflow.

Basically, all the user credentials are stored within the .gitconfig file in the user folder.

• Git Configuration Levels:

o System-Level Configuration (/etc/gitconfig): Settings that affect all users on a machine. Requires
superuser privileges to modify.

o Global-Level Configuration (~/.gitconfig or ~/.config/git/config): Settings that apply to the user across all
repositories. This is the most commonly modified config file.

o Local-Level Configuration (<repo>/.git/config): Settings that only apply to a specific Git repository. Local
settings override global ones.

• Editing Git Config Files:

o You can view or edit these configuration files manually or through the Git command-line interface. To view
or modify your global configuration, you can run:

git config --global –edit

o This opens the global configuration file in your default text editor, where you can add or change settings.
Once if changes made close the file everything will be saved.

https://orion021.github.io/krishnan_t/ 5 | 😁 👻 ✌️ 😎
GIT – Version Control Made Simple Collaboration Made Powerful

GIT Advanced Operations and Collaboration


1. Branching and Merging

Git's branching and merging allow developers to work independently on features, bug fixes, or experiments
without affecting the main project. This ensures changes can be developed, tested, and reviewed before being merged
into the main codebase.

Managing Branches

A branch in Git represents an independent line of development. The default branch created when you initialize a
repository is typically called main (or master in older Git versions). Branches allow you to isolate work, making it easier to
test and develop new features or fixes without impacting the main code.

Key Concepts:

Creating a Branch: To create a new branch, you use git branch <branch-name>. For example, to create a branch
called feature-xyz, you'd run:

git branch feature-xyz

To immediately switch to the new branch after creating it, use:

git checkout -b feature-xyz or git switch -c feature-xyz

Listing and Viewing Branches: To see a list of all branches in your repository, use:

git branch

• The current branch you are working on will have an asterisk (*) next to it.

• You can also list remote branches with:


git branch -a

Switching Between Branches: To move between branches, use the git checkout or git switch commands:

git checkout feature-xyz or git switch feature-xyz

Deleting Branches: Once you are done with all the work , you can delete it:

git branch -d feature-xyz

This deletes the branch locally (if it's fully merged with another branch). To force-delete an unmerged branch, use

git branch -D feature-xyz

Renaming Branches: To rename the current branch, use:

git branch -m new-branch-name

Renaming Other Branch: To rename the other branch, use:

git branch -m oldBranchName newBranchName

https://orion021.github.io/krishnan_t/ 6 | 😁 👻 ✌️ 😎
GIT – Version Control Made Simple Collaboration Made Powerful

2. Managing Repositories

Managing Remote Repositories

A remote repository is hosted on platforms like GitHub, GitLab, or Bitbucket. It allows multiple developers
to collaborate by pushing and pulling changes.

You can add a remote repository to your local repo by using:

git remote add <remote-name> <remote-URL>

Example:

git remote add origin https://github.com/username/repo.git

You can view the list of remote repositories associated with your project using:

git remote -v

This will display the fetch and push URLs for each remote.

Collaborating via repositories (push, pull, fetch)

Collaboration in Git revolves around syncing changes between local and remote repositories. The most
common Git commands used for collaboration are push, pull, and fetch.

git push (Uploading Changes to the Remote Repository) : After making changes locally, you can upload your
changes to the remote repository using git push.

git push <remote-name> <branch-name>

Example:
git push origin main

This pushes your commits in the main branch to the origin remote (e.g., GitHub).

git pull (Downloading and Merging Changes from the Remote): To download changes from the remote repository
and merge them into your local branch, use git pull:

git pull <remote-name> <branch-name>

Example:
git pull origin main

This fetches the latest changes from the remote origin and merges them into your local main branch.

git fetch (Downloading Changes without Merging): git fetch only downloads changes from the remote repository
but does not automatically merge them into your working branch. You can inspect the changes first and merge
them manually if needed.

git fetch <remote-name>

Example:

git fetch origin

After fetching, you can view the new changes (commits) and decide whether to merge them.

https://orion021.github.io/krishnan_t/ 7 | 😁 👻 ✌️ 😎
GIT – Version Control Made Simple Collaboration Made Powerful

3. Merging Branches(Combining Branches)

Once if all the work is done in the branches we created, we can combine it to the main or master branch.

In order merge one branch to another we can use the below command,

git merge feature-xyz

Based on the current status of repository git will perform Fast-Forward Merges or Three-Way Merge.

Types of Branching:

Fast-Forward Merges:

• This is the simplest type of merge.


• It happens when your current branch hasn't changed since you created your new branch.
• In this case, Git just moves the branch pointer forward, like flipping a page in a book. No new merge commit
is created because the changes are directly added to the current branch.
• In this case, no extra commits are created because the branch history is linear.

Example:
• You create a new branch, make some changes, and then merge it back to the main branch.
• If no one else has changed the main branch, Git can "fast-forward" the main branch to include your changes
without creating extra commits.

Three-Way Merges:

• This type of merge happens when both your branch and the main branch have new changes since you
branched off.
• Git compares three versions of the code: your branch, the main branch, and the point where both branches
started (the common ancestor).
• It combines the changes from both branches into one new commit, called a merge commit

Example:
• You and your friend both make changes in different branches.
• When you try to merge your branch back into the main branch, Git creates a new merge commit to combine
the changes from both of you.

Merge Conflicts:

• Conflicts occur when Git cannot automatically combine changes from two branches because the same file or
line was changed in incompatible ways in both branches.

• Git will mark the conflict and stop the merge process. You’ll need to resolve the conflicts manually by editing
the files and then committing the resolution.

https://orion021.github.io/krishnan_t/ 8 | 😁 👻 ✌️ 😎
GIT – Version Control Made Simple Collaboration Made Powerful

4. Git Workflows

1. Centralized Workflow

In the Centralized Workflow, a single central repository serves as the authority where all developers commit
their changes. It mimics the workflow used by older version control systems like SVN, where there is only one main
branch, often called the main or master branch, and all developers work directly on this branch.

How it Works:

• Developers clone the central repository.

• They make changes in their local environment.

• Once changes are ready, they push them directly to the central repository.

• There's no branching involved unless absolutely necessary, and all changes are committed directly to the main
branch.

Advantages: Disadvantages:

• Simple and easy to understand. • Hard to scale for large teams. Lacks flexibility for
feature isolation
• Ideal for small teams or single-developer
projects. • Higher risk of conflicts since all changes are
directly on the same branch.

2. Feature Branch Workflow

In this workflow, each new feature or bug fix is developed in its own isolated branch. Once the feature is
complete, the branch is merged back into the main branch (often the main or develop branch).

How it Works:

• Developers create a new branch for each feature (git checkout -b feature-branch).

• They work on the feature in isolation.

• Once the feature is complete, it is merged into the main branch using a pull request or a direct merge.

• The feature branch is then deleted.

Advantages: Disadvantages:

• Isolates work, reducing the risk of conflicts. • Requires more branch management.

• Encourages clean and organized commit • Continuous testing and integration are needed
histories. to ensure compatibility of different branches
when merged.
• Suitable for teams working on multiple features
simultaneously.

https://orion021.github.io/krishnan_t/ 9 | 😁 👻 ✌️ 😎
GIT – Version Control Made Simple Collaboration Made Powerful

3. Gitflow Workflow

Gitflow is a structured branching model introduced by Vincent Driessen. It is designed for projects with
scheduled releases and a defined structure for how work progresses through different stages.

How it Works:

• The repository has two long-lived branches: main (or master) for production-ready code and develop for ongoing
development.

• Developers create feature branches from develop for new work.

• Once features are complete, they are merged back into develop.

• When preparing for a release, a release branch is created from develop to prepare the code for production.

• Once the release is stable, it is merged into both main and develop.

• For urgent fixes, a hotfix branch is created from main and merged back into both main and develop after the fix.

Advantages: Disadvantages:

• Provides a structured and clear release process. • Can be complex for small teams or projects with
• Isolates different stages of development, making continuous delivery.
it easier to manage production releases and
• Requires careful branch management to avoid
ongoing development.
confusion.

4. Forking Workflow

Popular in open-source projects, where external contributors do not have direct access to the main repository.
Instead, they fork the repository, make changes in their copy, and submit a pull request to merge their changes.

How it Works:

• A developer forks the original repository, creating a personal copy under their account.

• They make changes in their fork, typically using feature branches.

• Once changes are complete, they push them to their fork and create a pull request to the original repository.

• Project maintainers review and merge pull requests into the main project.

Advantages: Disadvantages:

• Maintains strict control over the main repository. • Higher overhead for maintainers to review and
merge pull requests.
• Ideal for large-scale, open-source projects where
multiple contributors are involved. • Contributors need to keep their forks in sync with
the original repository.

https://orion021.github.io/krishnan_t/ 10 | 😁 👻 ✌️ 😎
GIT – Version Control Made Simple Collaboration Made Powerful

GIT Internals and Troubleshooting

Git is a version control system that uses a distributed architecture. Instead of maintaining centralized records of
changes, each developer has a local repository with a full history of the project, which is achieved through Git's internal
object model. The core of Git's version control is based on objects that are stored in a repository.

Each object in Git is immutable—once created, it cannot be changed. This ensures data integrity and ensures
that all changes are recorded transparently, with no risk of overwriting previous versions.

All of these objects are stored in the .git/objects directory of your repository, where each object is stored as
a file named according to the first two characters of the hash, followed by the remaining 38 characters.

1. Git Object Model: The Backbone of Git

Git is fundamentally a content-addressable filesystem where every piece of data is stored as an object. These
objects are immutable and uniquely identified by a SHA-1 hash.

What is a SHA-1 Hash?

• A SHA-1 hash is a 40-character hexadecimal string derived from the content of an object.

• Even a single change in the object (e.g., adding a space in a file) will generate an entirely new hash.

Example:

Hello, World! ------> Hash: 0a0a9f2a6772942557ab5355d76af442f8f65e01

Hello, World!! ------> Hash: 5c9c921d4a6ab4603d1640180892a15af46bf873

https://orion021.github.io/krishnan_t/ 11 | 😁 👻 ✌️ 😎
GIT – Version Control Made Simple Collaboration Made Powerful

2. Types of Git Objects

Git objects are the basic data structure for everything in the Git system. There are four types of objects called
Blob, Tree, Commit and Tag.

a. Blob Object: Storing File Contents

The Blob (Binary Large Object) represents the contents of a file in Git. It is the raw data of the file, without any file
name or directory structure. Git does not track metadata such as the filename or the directory of a file in a Blob—only
the file's content.

How it Works:

o When you add a file to Git using git add, Git stores the file's content as a Blob object in the .git/objects
directory.

o The content of the Blob object is hashed using the SHA-1 algorithm to generate a unique identifier for the
object. The object is saved as a file in the .git/objects directory. If a file hasn't changed, Git will reuse
the existing Blob object to save space.

Example:

o You have a file called hello.txt with the following content:

Hello, World!

o Git will create a Blob object, hashing the file's contents to generate a SHA-1 identifier (e.g., 7f8d4a4b76...),
and store it in the .git/objects/7f/8d4a4b76... file.

Command to View Blob:

git cat-file -p <blob-hash>

b. Tree Object: Representing Directory Structure

A Tree object in Git represents a directory structure. It acts like a "container" that groups files (Blobs) and other
subdirectories (Trees) together. Each Tree object stores the names and permissions of the files it contains, along with
the hashes of the Blobs and Trees it points to.

How it Works:

o A Tree object points to one or more Blobs (for files) or other Trees (for subdirectories).

o The structure of the directory is maintained by referencing all files and directories under that directory.
If you commit your project, Git creates a Tree object to represent the state of the project at that point.

Example: Let's say your project directory looks like this:

my_project/
├── hello.txt
└── src/
└── main.py
o The root directory my_project/ is represented by a Tree object. This Tree contains:

▪ A reference to the hello.txt file (which is a Blob object).

▪ A reference to another Tree object for the src/ subdirectory.

o The src/ directory itself will be represented by another Tree object, which will point to the main.py file (a
Blob object).
https://orion021.github.io/krishnan_t/ 12 | 😁 👻 ✌️ 😎
GIT – Version Control Made Simple Collaboration Made Powerful

Command to View Tree:

git cat-file -p <tree-hash>

c. Commit Object: Representing a Snapshot of Your Project

A Commit object in Git represents a snapshot of your entire project at a specific point in time. It records the state of
the project by referencing a Tree object (which represents the directory structure), along with metadata such as the
commit message, author, timestamp, and parent commits.

How it Works:

o Each commit contains a reference to a single Tree object, which is essentially the state of the repository
at the time of the commit.

o Git also records the author's information (name, email) and the commit message.

o Commits are linked to each other via parent commits, forming a linked list of changes (a commit
history). Every commit stores a pointer to its parent, and the root commit has no parent.

Example: Let's say you made a commit with the message "Initial commit". Git will create a Commit object that
contains:

o The Tree object representing the structure of your project at that point.

o The parent commit is null because it's the first commit.

o The author's information: "Your Name [email protected]"

o The commit message: "Initial commit".

Command to View Commit:

git cat-file commit <commit-hash>

d. Tag Object: Marking Important Commits

A Tag object is used to label a specific commit, often to mark a significant milestone, like a version release (e.g.,
v1.0, v2.0). There are two types of tags:

o Lightweight Tag: Essentially a pointer to a specific commit (like a branch reference).

o Annotated Tag: A full object that includes the tagger's name, email, date, and an optional message, and
can be signed.

How it Works:

o Tags are pointers to a specific commit. While tags don't change over time, they provide a meaningful
label to refer to specific commits.

o Annotated tags are recommended as they include metadata and can be signed with a GPG key for
security and verification.

Example: You want to mark a version release, say v1.0. You would create an annotated tag:

git tag -a v1.0 -m "Release version 1.0"

Command to View Tag: git show <tag-name>

https://orion021.github.io/krishnan_t/ 13 | 😁 👻 ✌️ 😎
GIT – Version Control Made Simple Collaboration Made Powerful

3. Git Storage Mechanisms

Git's storage system is optimized for efficiency and performance. It uses a combination of loose objects and
packfiles to manage the storage of Git objects.

a. Loose Objects

Loose objects are individual Git objects (Blobs, Trees, Commits, Tags) stored as separate files in the .git/objects
directory. Each object is stored as a file named using the first two characters of its SHA-1 hash followed by the remaining
38 characters.

b. Packfiles

Packfiles are a mechanism used by Git to compress and store multiple objects together to save space and improve
performance. When a repository grows large, Git automatically packs objects into packfiles, which can store thousands
of objects in a single file.

Why use Packfiles?

o To save disk space and optimize performance by reducing redundant copies of the same object.

o To speed up Git operations such as cloning and fetching.

4. Troubleshooting Git Issues

Git provides several powerful commands to help you recover from common problems.

a. Undoing Changes with git reset

git reset is used to move the current branch pointer to a specific commit.

o Soft Reset (--soft): Moves the branch pointer but keeps changes in the staging area.

o Mixed Reset (--mixed): Moves the branch pointer and unstages changes.

o Hard Reset (--hard): Resets the branch pointer and discards all changes in the working directory and
staging area.

Example: To undo the last commit and keep changes in the working directory:

git reset --soft HEAD~1

b. Undoing Changes with git revert

git revert creates a new commit that undoes the changes of a previous commit. Unlike reset, which rewrites history,
revert preserves the commit history and is safe to use on shared branches.

Example: To undo a specific commit:

git revert <commit-hash>

https://orion021.github.io/krishnan_t/ 14 | 😁 👻 ✌️ 😎
GIT – Version Control Made Simple Collaboration Made Powerful

c. Stashing Changes with git stash

Git Stashing is a useful feature for temporarily saving your uncommitted changes in your working directory and
staging area. This is particularly helpful when you need to switch branches or perform other tasks without committing
the changes. Here's how to use Git Stash in a series of steps:

Stashing Changes

To stash your current changes (both staged and unstaged), use the following command:

git stash

This command does the following:

• Stashes both staged and unstaged changes.

• Restores the working directory to the state of the last commit, so you can work on something else.

If you want to stash only staged changes, you can use:

git stash -k # or --keep-index

And if you want to stash only unstaged changes, use:


git stash -p # or --patch

You can also add a message to describe the stash for later reference:
git stash save "Message describing the stash"

Viewing Stashes

After stashing changes, you might want to see the list of all stashes you've made. To list all stashes:
git stash list

This will show a list of stashes, with the most recent one listed first, like below:

stash@{0}: WIP on feature/login: abcdefg Commit message


stash@{1}: WIP on develop: 1234567 Another commit message

Applying Stashed Changes

To apply the most recent stash, use: git stash apply

This applies the changes from the most recent stash to your working directory but does not remove it from the
stash list.

If you want to apply a specific stash from the list, use:

git stash apply stash@{n}

Where n is the stash index you want to apply (e.g., stash@{1}).

https://orion021.github.io/krishnan_t/ 15 | 😁 👻 ✌️ 😎
GIT – Version Control Made Simple Collaboration Made Powerful

Removing Stashes After Applying

Once you've applied the stash and are happy with the changes, you might want to remove it from the stash list.
To do that, use:

git stash drop stash@{n}

For example, to remove stash@{0}:

git stash drop stash@{0}

Alternatively, if you want to apply and remove the most recent stash in one step, use:

git stash pop

This will apply the most recent stash and remove it from the list.

Inspecting the Stash

To view the contents of a specific stash, use:

git stash show stash@{n}

For more detailed information (showing the actual diff), add the -p or --patch flag:

git stash show -p stash@{n}

Clearing All Stashes

If you no longer need any stashes and want to remove them all, use:

git stash clear

5. Git Hooks: Automating Tasks

Git hooks are scripts that Git executes before or after certain Git commands (such as commit, push, merge, etc.).
These hooks allow you to automate various tasks like running tests, formatting code, or enforcing project standards,
making Git a powerful tool for automating workflows in your development process.

Git hooks are located in the .git/hooks/ directory of your Git repository. By default, the .git/hooks/
directory contains sample scripts with .sample extensions, which you can modify or replace to suit your needs.

Types of GIT Hooks:

pre-commit:

Triggered before a commit is created.

Common use: Running linters, checking for formatting errors, or running tests before committing.

commit-msg:

Triggered after the commit message is entered but before the commit is finalized.

Common use: Validating commit message format (e.g., ensuring a specific style or structure).

post-commit:

Triggered after the commit is made.

Common use: Sending notifications or running tasks like documentation updates after a commit.

https://orion021.github.io/krishnan_t/ 16 | 😁 👻 ✌️ 😎
GIT – Version Control Made Simple Collaboration Made Powerful

pre-push:

Triggered before pushing changes to a remote repository.

Common use: Running tests or checks to ensure the code is ready to be pushed.

post-push:

Triggered after a push to a remote repository.

Common use: Deploying changes or updating CI/CD pipelines after a successful push.

post-merge:

Triggered after a merge has been completed.

Common use: Cleaning up merge artifacts or notifying teams after a successful merge.

6. Writing Meaningful Commit Messages

Writing clear, concise, and informative commit messages is essential for maintaining a clean and understandable
project history. A good commit message makes it easier for team members (and your future self) to understand what
changes were made and why.

Key Elements of a Good Commit Message:

1. Title (Subject Line):

o Keep it concise (under 50 characters).

o Use imperative mood (e.g., "Fix bug" instead of "Fixed bug").

o It should describe what the commit does, not how it’s done.

Example:

Fix issue with login form validation.

2. Body (Optional):

o Explain why the change was made and provide additional context if needed.

o Keep it less characters as possible per line for readability.

o Mention any relevant details such as bug numbers, related issues, or tests.

Example:

Fix issue with login form validation


- Corrected regex pattern for email validation.
- Added unit tests for invalid email handling.

https://orion021.github.io/krishnan_t/ 17 | 😁 👻 ✌️ 😎
GIT – Version Control Made Simple Collaboration Made Powerful

GIT and Continuous Integration/Deployment

Continuous Integration (CI)

Continuous Integration (CI) is a software development practice that encourages frequent integration of code
changes into a shared repository. Rather than waiting for large batches of changes to be merged, developers integrate
their code multiple times a day. This approach ensures that problems are detected early, and allows for faster and
smoother collaboration.

Key Practices of CI:

Automated Testing: Each integration is automatically tested to ensure that the new code doesn't break the
existing functionality.

Early Detection: By frequently committing changes, teams can spot and resolve integration issues earlier.

Faster Code Delivery: CI ensures that code is always in a deployable state, enabling faster delivery and frequent
releases.

Continuous Deployment (CD)

Continuous Deployment (CD) extends CI by automating the release process. In a CD pipeline, code that passes CI
checks (such as tests and validation) is automatically deployed to staging or production environments. This allows for
rapid and consistent deployment without manual intervention.

Key Benefits of CD:

Faster Releases: Every change that passes testing is deployed, meaning production updates happen frequently.

Reduced Manual Errors: By automating deployment, CD eliminates human error during the release process.

Consistent Deployment: Automation ensures that every environment (e.g., dev, staging, production) gets the
same deployment process, leading to fewer environment-specific issues.

https://orion021.github.io/krishnan_t/ 18 | 😁 👻 ✌️ 😎
GIT – Version Control Made Simple Collaboration Made Powerful

CI/CD Pipeline Overview:

• Code Commit: A developer commits changes to a version control system (e.g., GitHub).

• CI Process: Code is fetched, compiled, and tested (automated testing, linting, etc.).

• CD Process: If the code passes all tests, it's automatically deployed to a testing/staging environment, and
potentially to production.

This process ensures that software can be deployed in a rapid, reliable, and repeatable way, which is crucial in
modern DevOps practices.

2. GitHub Actions for CI/CD

GitHub Actions is an integrated automation tool that allows you to define workflows directly within GitHub
repositories. These workflows are composed of jobs that execute a sequence of steps. These jobs can automate tasks
like building, testing, and deploying your code to various environments.

Key Concepts in GitHub Actions:

o Workflows: Defined in YAML files (located in .github/workflows/). Workflows are triggered by events
(e.g., a push to the repository, a pull request, or a scheduled event).

o Jobs: Each workflow contains one or more jobs. A job is a collection of steps that run on a specific
runner (virtual machine or container).

o Steps: Each step in a job performs a single action, such as checking out code, installing dependencies, or
running tests.

o Runners: Runners are servers that execute the jobs. GitHub provides hosted runners with predefined
environments, but you can also create custom, self-hosted runners if you need more control over the
environment.

How Workflows and Jobs Work:

Triggers: A workflow is initiated by a trigger, such as a push to a branch or a pull_request event. For example:
on:
push:
branches:
- main

https://orion021.github.io/krishnan_t/ 19 | 😁 👻 ✌️ 😎
GIT – Version Control Made Simple Collaboration Made Powerful

Job Execution: Jobs within a workflow can run in parallel or sequentially. Each job can contain multiple steps.

o Jobs can be conditionally executed, such as:

jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v2
- name: Run tests
run: npm test

Runners: The job is executed on a runner, which GitHub provides or you can host yourself. Common runners
include ubuntu-latest, windows-latest, and macos-latest.

Example Workflow:

name: Node.js CI Pipeline

on:
push:
branches:
- main

jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Check out repository code
uses: actions/checkout@v2
- name: Set up Node.js
uses: actions/setup-node@v2
with:
node-version: '14'
- name: Install dependencies
run: npm install
- name: Run tests
run: npm test

3. Setting Up CI Pipelines

To set up a CI pipeline in GitHub Actions, you need to define a .yml configuration file in the .github/workflows
directory. This file specifies how the pipeline behaves—when it runs, what steps it takes, and what jobs are involved.

Step-by-Step Breakdown:

1. Create a Workflow File:

o The configuration file is written in YAML format.

o This file should be placed in the .github/workflows/ directory of your GitHub repository.

o Example path: .github/workflows/ci.yml

https://orion021.github.io/krishnan_t/ 20 | 😁 👻 ✌️ 😎
GIT – Version Control Made Simple Collaboration Made Powerful

2. Define the Workflow:

o Name: Give the workflow a descriptive name.

o Triggers: Set the trigger events for the workflow. Common triggers include push, pull_request, and
schedule.

o Example:

name: Node.js CI Workflow

on:
push:
branches:
- main
pull_request:
branches:
- main

3. Define Jobs:

o Each job can run on a different virtual machine or container.

o Jobs can run in parallel or sequentially (depending on dependencies).

o Example of a single job:

jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Install Node.js dependencies
run: npm install
- name: Run Tests
run: npm test

4. Use Conditional Execution:

o You can define conditions to control whether a job or step runs based on certain criteria.
o Example: Only deploy if tests pass:
jobs:
deploy:
if: success() # Deploy only if the previous jobs were successful
runs-on: ubuntu-latest
steps:
- name: Deploy to server
run: ./deploy.sh

https://orion021.github.io/krishnan_t/ 21 | 😁 👻 ✌️ 😎
GIT – Version Control Made Simple Collaboration Made Powerful

4. Deployment Strategies

Once the CI pipeline has successfully run, the next step is to deploy the code. This process can be automated as
part of your CD pipeline. Deploying automatically ensures that the latest stable version of your code is always running in
your environment.

Steps to Set Up Deployment:

1. Add Deployment Jobs:

o After running tests in the CI pipeline, you can add a deployment job that pushes the code to a staging or
production server.

2. Environment-Specific Deployment:

o You may have different environments, such as development, staging, and production.

o You can create separate jobs for each environment and conditionally deploy based on branch names or
tags.

3. Rollback and Failures:

o You can implement rollback strategies if something goes wrong during deployment. For example, you
might revert to a previous version of the code in case of failure.

5. Monitoring and Reporting

Once your CI/CD pipeline is set up, it is crucial to monitor its execution and ensure that it is performing as
expected.

Monitoring Tools:

• GitHub Actions Dashboard: This provides an overview of all workflows and their statuses. You can view logs for
each job and each step, making it easy to debug any failures.

• Logs: Every job and step generates logs, which you can access from the GitHub Actions interface. These logs
show detailed information on what went wrong and where the process failed.

• Status Badges: You can add status badges to your project’s README file to show whether the pipeline passes or
fails.

Notifications:

• You can integrate Slack or email notifications to alert your team about the status of a workflow. For example,
you can configure GitHub Actions to send a message to a Slack channel when a build or deployment fails or
succeeds.

Example: Slack Notification:


- name: Send Slack Notification
uses: slackapi/slack-github-action@v1
with:
channel-id: 'YOUR_CHANNEL_ID'
slack-token: ${{ secrets.SLACK_TOKEN }}
text: 'Deployment successful! 🚀'

https://orion021.github.io/krishnan_t/ 22 | 😁 👻 ✌️ 😎
GIT – Version Control Made Simple Collaboration Made Powerful

Benefits of CI/CD

• Improved Code Quality: Automated testing on every code change means potential bugs are identified and fixed
before they make it into the main branch. This regular checking helps keep code stable and high-quality.

• Faster Releases: Automating the build, test, and release process speeds up the entire pipeline, allowing teams to
quickly get new features, bug fixes, and updates to users.

• Enhanced Collaboration: By pushing small, frequent updates, developers avoid “merge hell” and maintain
smooth workflows. Developers see the latest code changes from each other almost immediately, reducing
conflicts.

• Reduced Risks: Small updates are easier to test, monitor, and roll back if needed. Releasing updates in smaller,
manageable chunks means there’s less chance of something going wrong.

CI/CD Tools

• Jenkins: An open-source automation server, highly customizable with plugins for different languages, tools, and
stages in the CI/CD pipeline. Jenkins can be integrated into various stages of the pipeline, from code integration
to deployment.

• GitLab CI/CD: Built into GitLab repositories, it allows developers to define pipelines within their GitLab projects.
This is great for projects already on GitLab because everything can be configured in one place.

• CircleCI: Known for seamless integration with GitHub, CircleCI runs CI/CD processes in the cloud, enabling fast
builds and supporting parallel executions.

• GitHub Actions: GitHub’s native CI/CD tool allows defining workflows directly in the repository, integrating well
with other GitHub features like issues and pull requests. It’s ideal for projects already hosted on GitHub.

Ways to release software:

o Blue-Green Deployment:

▪ There are two identical versions of the production environment, named “blue” and “green.”
Users are directed to one (say, blue), while the other (green) is updated.

▪ Once the update is ready, the traffic is switched to the green environment. If anything goes
wrong, the switch can revert to the blue environment, minimizing downtime.

o Canary Releases:

▪ A new version is initially released to a small subset of users to monitor for issues. If everything
works well, it’s then gradually rolled out to more users.

▪ This strategy helps identify any unforeseen problems with real user feedback in a controlled way.

o Rolling Deployments:

▪ This approach gradually replaces instances of the old version with the new one. This method
minimizes downtime because only a few instances are replaced at a time, keeping most of the
service running.

o Feature Toggles:

▪ Feature toggles (or feature flags) allow developers to hide incomplete or experimental features
from users. Features are deployed in a disabled state and can be turned on gradually when
they’re ready.

https://orion021.github.io/krishnan_t/ 23 | 😁 👻 ✌️ 😎
GIT – Version Control Made Simple Collaboration Made Powerful

6. Case Studies and Best Practices

Examples of CI/CD Success:

o Netflix: Netflix has a sophisticated CI/CD system that allows them to deploy new updates to users multiple
times a day. They use canary releases to test changes on a small scale before releasing them widely.

o Amazon: Amazon deploys thousands of updates daily across its platforms. They use a CI/CD approach that
emphasizes automated testing, rollback capabilities, and monitoring.

Best Practices for CI/CD Pipelines:

o Automate Everything: Automated testing, building, and deployment reduce the risk of human error and
speed up the pipeline. Aim to automate every stage of the pipeline.

o Build Once, Deploy Everywhere: Once code is built and packaged, reuse that same build in all environments
(testing, staging, production) to avoid inconsistencies.

o Test Continuously: Implement unit tests, integration tests, and possibly UI tests at each stage to ensure code
quality and functionality.

o Monitor and Set Alerts: After deploying to production, use monitoring tools to track performance, usage,
and errors. Alerts can notify the team if there’s an issue, helping to catch problems quickly.

o Regularly Review Pipelines: Keep the pipeline efficient by removing unused steps, updating dependencies,
and optimizing processes. This helps maintain fast, reliable releases.

https://orion021.github.io/krishnan_t/ 24 | 😁 👻 ✌️ 😎
GIT – Version Control Made Simple Collaboration Made Powerful

GitHub/GitLab Mastery
Github:

GitHub is a cloud-based platform designed for developers to collaborate on software projects, host(store) source
code, and manage version control using Git. GitHub provides a user-friendly interface and a variety of tools to facilitate
collaborative development, making it one of the most popular platforms for open-source and private projects.

GitHub Features:

Repositories:

Repositories are storage spaces for projects, containing files, commit history,
branches, and configuration files.

Key Features:

Commits: Each change to the repository is saved as a commit, which acts as


a snapshot of the repository at a given point in time.

History: Track all changes and revert to previous versions if needed.

Files and Folders: Organize code, documentation, and resources.

Types of Repositories:

Public Repositories: Open to the public and ideal for open-source projects.

Private Repositories: Restricted access; only authorized users can view or contribute.

Special Files:

.gitignore: Specifies files and directories Git should ignore.

LICENSE: Defines the legal permissions and restrictions for repository usage.

README.md: The introductory file displayed on the repository’s main page.

Issues:

A built-in task and bug tracking system, which has


features like the following

• Create issues for new tasks, bugs, or


enhancements.

• Use labels (e.g., bug, enhancement, help


wanted) to categorize and prioritize.

• Assign issues to collaborators to define


responsibilities.

• Link issues to milestones to track progress toward project goals.

• Use Markdown to format issue descriptions with headers, lists, and code snippets.

• Reference commits or pull requests using # (e.g., #42 references issue/pull request 42).

https://orion021.github.io/krishnan_t/ 25 | 😁 👻 ✌️ 😎
GIT – Version Control Made Simple Collaboration Made Powerful

Pull Requests (PRs):

Mechanism for proposing and reviewing changes before merging into the main branch.

Workflow:

• Create a feature branch.

• Push changes to the branch.

• Open a pull request from the feature branch to the main branch.

• Collaborators review, discuss, and approve or request changes.

• Merge the pull request after approval.

Enhancements:

• Request multiple reviewers to ensure quality.

• Use draft PRs for work in progress.

• Enable branch protection rules to enforce mandatory reviews or CI checks before merging.

Forks:

Making a copy of a repository which is owned in a different account


to our account.

Use Cases:

• Experiment with changes without affecting the original


project.

• Contribute to open-source projects by making changes to


the fork and submitting pull requests to the original
repository.

https://orion021.github.io/krishnan_t/ 26 | 😁 👻 ✌️ 😎
GIT – Version Control Made Simple Collaboration Made Powerful

Branches:

Allows isolated development for features or fixes.

Common Branching Strategies:

• Feature Branches: For new features (e.g., feature/login-page).

• Bugfix Branches: For resolving issues (e.g., bugfix/fix-login-error).

• Release Branches: For preparing a version for deployment.

• Hotfix: Making immediate bugfixes to resolve issues.

Best Practices:

• Name branches descriptively (e.g., feature/add-authentication).

• Regularly merge main into feature branches to stay up to date.

GitHub Pages:

A free hosting service for static websites which is


created using only HTML, CSS and JavaScript.

Setup:

• Go to the repository’s settings and enable


GitHub Pages.

• Use the default main branch or a specific folder


like docs/.

Use Cases:

• Host documentation, project pages, or portfolios.

• Use Jekyll for automatic site generation and theming.

https://orion021.github.io/krishnan_t/ 27 | 😁 👻 ✌️ 😎
GIT – Version Control Made Simple Collaboration Made Powerful

Managing Teams:

Collaborators:

Individuals with access to a private repository, which allows them do


contributions for the project.

Permission Levels:

• Read: Can view and clone the repository.

• Write: Can push commits and manage issues/pull requests.

• Admin: Full control over repository settings and management.

GitHub Organizations:

Manage repositories, permissions, and teams for groups or companies.

Features:

• Centralize repository ownership under an organization account.

• Manage billing and security settings for all repositories.

• Use organization-level policies to enforce standards.

Teams:

Subgroups within an organization to organize and manage members.

Features:

• Assign repositories to teams with specific permissions.

• Use team mentions (e.g., @team-name) for notifications.

• Create nested teams for granular roles (e.g., frontend and backend teams).

2. Advanced GitHub Features: Actions, Packages, Documentation

GitHub Actions:

A CI/CD solution integrated with GitHub for automating tasks.

Use Cases:

o Automate testing and deployment.

o Lint code for style and quality checks.

o Build and publish packages or containers.

Workflow Anatomy:

Events:

o Specify triggers like push, pull_request, schedule, or manual.

o Example: Automatically run tests on every push to the main branch.

https://orion021.github.io/krishnan_t/ 28 | 😁 👻 ✌️ 😎
GIT – Version Control Made Simple Collaboration Made Powerful

Jobs:

o A set of steps executed in an isolated environment.

o Specify the environment (e.g., ubuntu-latest, macOS-latest).

Steps:

o Individual tasks in a job, such as installing dependencies or running commands.

YAML Workflow Example:

name: Node.js CI
on:
push:
branches:
- main
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: 16
- name: Install dependencies
run: npm install
- name: Run tests
run: npm test

Secrets in Actions:

• Store sensitive information (e.g., API keys) in the repository or organization settings.

• Access secrets using secrets.<SECRET_NAME> in workflows.

GitHub Packages:

A package hosting service for managing dependencies.

• Supported Formats: npm, Docker, Maven, NuGet, RubyGems, etc.

Using GitHub Packages:

Publishing:

o Authenticate using a personal access token.

o Push packages to the GitHub Packages registry.

Accessing Packages:

o Install packages using package managers like npm install or docker pull.

Private Packages:

o Restrict access to specific repositories or teams.

https://orion021.github.io/krishnan_t/ 29 | 😁 👻 ✌️ 😎
GIT – Version Control Made Simple Collaboration Made Powerful

GitHub Documentation:

README:

Provide an overview of the project.

Best Practices:

o Include sections like "About," "Installation," "Usage," and "Contributing."

o Use visuals (e.g., screenshots, diagrams) to enhance clarity.

o Add badges for build status, license, and version.

GitHub Wiki:

A space for in-depth project documentation.

Features:

o Create multiple pages for organizing content.

o Use Markdown for consistent formatting.

o Track changes to wiki pages with version history.

Markdown’s - https://www.markdownguide.org/basic-syntax/

https://orion021.github.io/krishnan_t/ 30 | 😁 👻 ✌️ 😎
GIT – Version Control Made Simple Collaboration Made Powerful

What is the primary purpose of GitHub/GitLab?


Code hosting and version control

How can you manage team permissions in GitHub/GitLab?


By creating teams and assigning roles

In GitHub/GitLab, what does the term "commit" refer to?


A change or set of changes made to the codebase

What is the primary function of GitHub Pages?


To create and host static websites directly from a repository

Which feature in GitLab is used to manage and publish packages?


Package Registry

In GitHub, what is a "package"?


A bundle of code or libraries that can be shared

Which feature in GitLab helps protect important branches?


Protected Branches.

What is the purpose of GitHub/GitLab Milestones?


To set goals and track issues or pull requests associated with a project.

What is the primary use of GitLab CI/CD?


Automating the software development process, including builds, tests, and deployments

How can you find open-source projects to contribute to?


By searching GitHub and GitLab with specific labels like "good first issue"

What does the term "maintainer" refer to in an open-source project?


A person responsible for overseeing the project and managing contributions

What is a "good first issue" label?


A label for issues that are considered beginner-friendly and suitable for new contributors

Which feature allows multiple people to work on a GitHub/GitLab repository simultaneously?


Branches

Which of the following is NOT a feature of GitHub/GitLab?


Document editing

Which GitHub feature allows users to assign tasks and track progress?
Issues

Which GitHub feature is used for code review?


Pull Requests.

How can you suggest a change to an open-source project in GitHub/GitLab?


By opening a pull request, forking the repository, or creating an issue (All of the above).

What is a "merge conflict"?


When changes in two branches overlap and cannot be automatically merged.

What are GitHub Actions used for?


Automating workflows and tasks within a repository

How can you document your project effectively on GitHub?


By using the Wiki feature, README file, and GitHub Pages

https://orion021.github.io/krishnan_t/ 31 | 😁 👻 ✌️ 😎
GIT – Version Control Made Simple Collaboration Made Powerful

What does the term "workflow" refer to in the context of GitHub Actions?
A series of automated steps to perform tasks like building, testing, and deploying code

Which of the following GitHub features helps teams organize their work?
Issues and Projects

What is a common method for tracking changes and contributions in an open-source project?
Using pull requests to propose changes

What is a "fork" in GitHub/GitLab?


A duplicate of a repository under a different account.

What does the "pull" operation in Git refer to?


Downloading changes from a remote repository.

What is the purpose of a pipeline in GitLab CI/CD?


To automate processes like building, testing, and deploying code.

What is the default configuration file for GitLab CI/CD?


.gitlab-ci.yml.

Which GitHub feature helps ensure code contributions meet specific standards?
Required Reviews.

How can sensitive data like API keys be securely managed in GitHub/GitLab CI/CD pipelines?
By storing them in environment variables or secrets.

https://orion021.github.io/krishnan_t/ 32 | 😁 👻 ✌️ 😎

You might also like