Mastering Git: Version Control Made Easy

Mastering Git: Version Control Made Easy

Git is a distributed version control system widely used for tracking changes in source code during software development.

Flow of Git

git init -

The git init cod create a new repository. It can be used to convert an folder to a empty git repo.

  • Git Operations with VS Code

  1. Create a Folder

On your laptop, create a folder for your project.

  1. Open the Folder in VS Code

Launch Visual Studio Code and open the newly created folder.

  1. Clone the Repository

Open the terminal in VS code

Use below command

git clone ‹url>

Replace ‹ur 1 > with the URL of your remote repository.

  1. Modify the Files

Make the required changes to the files in your project.

  1. Check the File Status

In the terminal, type:

git status

You will see your modified files listed in red, indicating they are not staged.

  1. Stage the Changes

Stage all the modified files using:

git add .

Run git status again to confirm.

The modified files will now appear in green, meaning they are in the staging area.

  1. Commit the Changes

Save your changes to the local repository with a commit message:

git commit -m "commit changes"

  1. Push the Changes to Remote Repository

Use the following command to send the changes to the remote repository:

git push ‹url>

Replace ‹url > with the URL of your remote repository.

  1. Verify the Changes

Go to your remote repository and verify that the changes have been successfully reflected.

  • Git Operations with VS Code

  1. Create EC2 instance and connect

  2. Install Git:Ensure Git is installed on your EC2 instance.

apt install git -y

git --version

  1. Clone the Repository:

Clone your remote repository to the EC2 server or navigate to the directory containing your existing Git repository

git clone https://github.com/ygminds73/shellscripts.git

  1. cd shellscripts/ Scriptll.sh

  2. ls

  3. vim -> change -> !wq:

  4. git status

  1. Stage Changes:

Add the modified or new files to the staging area.

git add scriptl.sh

git add .

  1. Commands to Set Username and Email

• Global Configuration: Applies to all repositories on your machine.

git config --global user.email "vaishalijogdande@gmail.com"

git config --global user.name“vaishalijogdande”

  1. Verifying the Configuration

You can check your global or local configuration with:

git config --global --list

git config --get user.email -> vaishalijogdande@gmail.com

git config --get user.name -> vaishalijogdande

  1. Commit Changes:

Commit the staged changes with a meaningful message.

git commit -m "changes in script 1"

git status

  1. Push Changes:

Push the committed changes to the remote repository.

  1. git push https://github.com/vaishalijogdande/shellscripts.git

  2. User name and password

  1. Replace Your Password with the Token:

GitHub no longer supports password authentication for Git operations. Use the token as your password.

  • When you push or pull:

  • Use your GitHub username as the username.

  • Use the generated token as the password.

Create Token on GitHub

Generate a Personal Access Token(PAT):

  1. Log in to your GitHub account.

  2. Navigate to Settings > Developer Settings > Personal Access Tokens > Tokens (classic).

  3. Click Generate new token > Generate new token (classic).

  4. Select the scopes required (e.g., repo for repository access).

  5. Click Generate token and copy the token (it will not be shown again).

Click yes on all boxes and generate token

  1. git push https://github.com/vaishalijogdande/shellscripts.git

  2. Give GitHub user name and token as password

  1. Verify Push:

Confirm the changes in your remote repository using the Git hosting service’s interface.

Git Branching Strategy -

  1. We are not allowing any developer to do directly changes into main/master branch.

  2. Developers/DevOps has to create a feature branch while changing/adding new code.

  3. After done with the changes in the feature branch developer/DevOps has to merge his/her code changes in master/main branch.

  4. We are following 4-eye principle while merging code changes.

    Someone need to approve merge request

  5. We have to add Incident Id(INC ID), Request ID(REQ ID ) or Change ID while creating a feature branch and merge request ex. (INC0902324, REQ092348, CHG009823, STORY-6865)

    Create new branch for each incident

  6. In case of Azure, you have to add work item to the branch and create pull request.

  7. When you create new branch, main branch contents will copy in new branch

How to Create and Merge a Branch on GitHub:

  1. Clone the Repository

The first step is to clone the repository to your local machine.

git clone https://github.com/vaishalijogdande/shellscripts.git

This will create a local copy of the repository, allowing you to make changes to it.

  1. Create a New Branch

Next, you’ll need to create a new branch for the changes you want to implement. To create a new branch and switch to it, use the following command:

git checkout -b INC0902328

git branch -> to get list of branches

git switch main -> to switch to main branch

Here, INC0902328 is the name of the new branch. Naming your branch descriptively helps keep track of the changes you’re working on, especially for bug fixes, features, or tasks.

  1. Check the Status of Your Branch

git status

This command will show you the current state of the branch, including any changes that are yet to be staged or committed.

  1. Stage Your Changes

Once you’ve made your changes to the files, you need to stage them for commit. This can be done by using:

git add .

The . adds all modified files. You can also specify individual files if you prefer to commit only certain changes.

  1. Commit Your Changes

After staging the changes, commit them with a meaningful message that describes the changes you’ve made. This is crucial for future reference and understanding the purpose of each commit.

git commit -m "Fixing issue related with INC0902328"

  1. Check the Status Again

It’s a good practice to verify the status again before pushing your changes to the remote repository.

git status

This ensures that everything is committed and ready to be pushed.

  1. Push Your Changes to GitHub

Now that you have committed your changes, it’s time to push them to GitHub.

git push https://github.com/vaishalijogdande/shellscripts.git

This will upload your branch and its changes to the GitHub repository.

  1. Create a Pull Request on GitHub

    Once your branch is pushed to GitHub, the next step is to create a Pull Request (PR). A Pull Request allows others to review your changes before they are merged into the main branch.

To do this:

1. Go to your repository on GitHub.

2. You’ll see a notification about the branch you just pushed. Click the “Compare & pull request” button.

3. Add a title and description for your pull request, explaining what the changes are about.

4. Click on “Create pull request.”

  1. Merge the Pull Request

Once the pull request is reviewed and approved, you can merge it into the main branch. Typically, the person responsible for maintaining the repository will handle the merging process, but if you have permission, you can merge it yourself.

To merge the pull request:

1. Navigate to the pull request page.

2. Click on the “Merge pull request” button.

3. Confirm the merge, and the changes will be incorporated into the main branch.

  • Merge conflict

The main branch started with the following content:

  1. echo "We are trying this practical from linux EC2"

  2. echo "We are from batch-25 and learning git/GitHub"

  3. echo "We are learning Branching"

  4. Developer 1’s Contribution

Developer 1 created a new branch called branch-1 and made the following addition:

  1. echo "We are trying this practical from linux EC2"

  2. echo "We are from batch-25 and learning git/GitHub"

  3. echo "We are learning Branching"

  4. echo "I am learning Git"

This update added a 4th line: echo "I am learning Git".

  • Developer 2’s Contribution

Meanwhile, Developer 2 worked on the main branch and added a new 4th line:

  1. echo "We are trying this practical from linux EC2"

  2. echo "We are from batch-25 and learning git/GitHub"

  3. echo "We are learning Branching"

  4. echo "I am learning DevOps"

Developer 2 merged their changes into the main branch, and the updated main branch looked like this:

  1. echo "We are trying this practical from linux EC2"

  2. echo "We are from batch-25 and learning git/GitHub"

  3. echo "We are learning Branching"

  4. echo "I am learning DevOps"

    • The Conflict

When Developer 1 tried to merge their branch (branch-1) into the updated main branch, a conflict arose because both Developer 1 and Developer 2 had modified the same section of the code—the 4th line. Git could not automatically determine which change to keep:

• Developer 1’s addition: echo "I am learning Git"

• Developer 2’s addition: echo "I am learning DevOps"

  • Resolving the Conflict

To resolve this, the team had to manually edit the conflicting file, choosing the appropriate changes or combining both updates:

  1. echo "We are trying this practical from linux EC2"

  2. echo "We are from batch-25 and learning git/GitHub"

  3. echo "We are learning Branching"

  4. echo "I am learning Git and DevOps

Merge Strategies in Git-

Merge in Git allows you to join two or more development work created using git branch into a single branch

  1. Recursive-

$git merge -s recursive branch1 branch2

Git will select recursive as a default strategy when pulling or merging branches. The recursive strategy can detect and manage merges that involve renames, but it cannot use detected copies.

  1. Resolve-

$git merge -s resolve branch1 branch2

The resolve strategy uses a 3-way merge for resolving branches and can resolve only two HEADs using a 3-way merge algorithm. It is safe and fast and detects criss-cross merge ambiguities in detail.

  1. Octopus

$git merge-s octopus branch1 branch2 branch3 branchN

When two or more branches are passed, the octopus strategy is engaged, by default. Octopus refuses if the merge has conflicts that need manual resolution. The basic use of Octopus is to bundle feature branch HEADs that have similarities.

  1. Ours-

$git merge -s ours branch1 branch2 branchN

Our strategy resolves multiple branches, but the result is always that of the current branch HEAD. It ignores all changes from all other branches very effectively. It is intended to be used to replace an old history of side branches.

  1. Subtree-

$git merge -s subtree branchA branchB

The subtree strategy is the modified version of the recursive strategy. For example, we merge A and B trees. When corresponding to a subtree of A, B is first modified to reflect the tree structure of A. The modification can be done to the shared ancestor tree of A and B.

Important terms

Q. Explain Git clone Vs Git pull Vs Git Fork Vs git fetch Vs git Push

Git Clone

• Makes a full copy of a remote repository to your local computer.

• Use it when starting to work on a project for the first time.

Git Pull

• Updates your local repository and working files with the latest changes from the remote repository.

• Git Pull = Git Fetch + Git Merge.

• Use it to sync your work with the remote repository.

Git Fetch

  • Downloads changes from the remote repository but doesn’t update your working files.

  • Use it to see if there are updates in the remote repository without affecting your current work.

  • It will tell you that remote repository has some changes that you don’t have in your local repository

  • Git fetch cmd fetches all the changes from the remote repo to the local repo without bringing the changes into the working directory.

Difference between Git Pull and Git Fetch:

• Git Fetch: Only downloads the changes (doesn’t apply them).

• Git Pull: Downloads and applies the changes to your working files.

Git Fork

• Creates your own copy of a repository on platforms like GitHub.

• Use it to contribute to someone else’s project while keeping your work separate.

Git Push

• Sends your committed changes from your local repository to the remote repository.

• Use it to share your updates with others.

Git stash

git stash is a Git command that temporarily saves your changes (both staged and unstaged) without committing them.

This allows you to switch branches or perform other tasks without losing your work.

Later, you can reapply (or “pop”) the stashed changes back into your working directory.

If you are working on some changes and requirement get changed or your manager asked you to work on another task.

- Then you can temp hold your changes into git stash.

# git stash

# git stash apply

#git stash list

#git stash show

Key Commands:

git stash: Saves your changes and resets the working directory.

git stash list: Lists all stashed changes.

git stash apply: Applies the most recent stash (or a specific one) to your working directory.

git stash pop: Applies and removes the most recent stash from the list.

git stash drop: Removes a specific stash from the list.

git stash clear: Clears all stashes.

Practical Example:

1. You’re working on feature-branch and have some uncommitted changes:

git status

# Output: You have modified files that are not yet staged for commit.

2. You need to switch to main to handle an urgent fix. You don’t want to commit the changes yet. Save them with:

git stash

3. Switch to main branch:

git checkout main

4. Work on main and make the necessary changes, then commit.

5. Switch back to feature-branch:

git checkout feature-branch

6. Reapply the stashed changes:

git stash pop

7. Continue working on feature-branch, now with your previous changes re-applied.

Git Rebase

Rebasing is the process to reapply commits on the top of another base trip.

It is used to apply a sequence of commit.

Alternative to merge.

Linear process of merging.

Git Merge (Left Side of the Diagram)

• Think of master as the main road and branch-1 as a side road.

• When you do a merge, Git joins the two roads together at a new point (a merge commit) without changing the path of either road.

In the diagram:

• branch-1 (C → D → E) stays separate.

• master (A → B → F → G → H) keeps its own path.

• A merge commit connects them, keeping both branch histories intact.

commit -1 aбcb406

commit -2 6839ab5

commit -3 f7907d8

commit - alee51d -> It is combination of three commits i.e., H

Git Rebase (Right Side of the Diagram)

• Imagine you lift the side road (branch-1) and put it directly on top of the main road (master).

• Git replays the commits from branch-1 (C → D → E) as if they were created after master’s latest commit (A → B → F → G).

It will generate three individual commits for C, D , E

In the diagram:

• The commits C, D, and E become C', D', and E' to show their new position on the main road.

• it’s a single straight road.

Cherry Pick -

Cherry-picking in Git stands for applying specific commit from one branch to another branch.

In case you made a mistake and committed a change into the wrong branch, but do not want to merge the whole branch. You can pick specific commit and merge it.

Scenario:

• You are on the main branch.

• A useful commit exists in the feature branch that you want to apply to the main branch without merging the entire branch.

Steps:

1. Switch to the branch where you want the commit applied:

git checkout main

2. Find the commit hash:

• Switch to the feature branch and find the commit hash of the commit you want to cherry-pick:

git log

• Example output:

commit abc1234

Author: User

Date: Jan 11, 2025

Message: Add new feature

3. Switch back to the target branch (main):

git checkout main

4. Cherry-pick the commit:

git cherry-pick abc1234

• Git will apply the changes from the commit abc1234 to the main branch.

5. Verify the changes:

git log

• You will see the commit added to your main branch.

Hot-fix -

A hot-fix in software development refers to a quick, typically urgent fix to a bug or issue in a production environment.

A critical bug is discovered in a production application that prevents users from logging in. To quickly resolve this, a hot-fix is created, tested briefly, and deployed directly to production to restore functionality while preventing further disruption.

Git Reset

git reset is a powerful Git command used to undo changes in your working directory and staging area.

It can be used to move the current branch pointer to a previous commit, and depending on the options you use, it can affect your working directory, the staging area, or both.

  1. Soft - uncommit

  2. Mixed - uncommit + unstage

  3. Hard - uncommit + unstage + Code will be remove; from working directory

Git revert

git revert is used to create a new commit that undoes the changes made by a previous commit.

Unlike git reset, which modifies the commit history, git revert is a safe way to undo changes because it preserves the history by creating a new commit that reverses the changes.

Syntax:

git revert <commit>

Key Points:

• Does not delete history: git revert creates a new commit to undo the changes made by a previous commit, instead of removing the commit like git reset.

• Useful for public branches: Since it doesn’t modify the commit history, it’s ideal for undoing changes in a shared or public branch (e.g., main or master).

• Reverts a single commit: By default, it reverts a single commit, but it can also be used to revert multiple commits.

Git Tag

A Git tag is a way to mark a specific point in your project’s history, like a version or milestone.

Tags are useful for marking important commits (such as releases or version numbers) without changing or affecting the commit history.

Tags preserve the commit history because they are simply references to specific commits — they don’t alter or delete any part of the project history.

Git Hooks

Git hooks are scripts that Git executes before or after events such as commit, push, and pull. These scripts allow you to customize and automate certain tasks in your Git workflow.

Git hooks are stored in the git/hooks directory of your Git repository.

ex pre-commit, pre-push, post-push

Where are Git Hooks?

Git hooks are stored in the .git/hooks/ directory in your project. By default, this folder contains example scripts (with .sample at the end).

You can edit or create these scripts to fit your needs.

.gitignore

. gitignore is a file that tells Git which files or directories to ignore and not track in your project.

It’s useful for excluding files that don’t need to be part of your Git repository, such as temporary files, build files, and sensitive information.

Why Use .gitignore?

When you create a Git repository, it will track all files in the project. However, you often don’t want Git to track certain files, like:

• Temporary files generated by your text editor (e.g., .vscode/).

• Build files (e.g., .class, .exe).

• Configuration files containing sensitive information (e.g., .env).

• Log files (e.g., *.log).

The .gitignore file helps prevent these files from being added to your repository.