Tuesday, March 26, 2024

Git and GitHub



Git and GitHub Introduction:

Setup

These commands are used to set your Git username and email. This information will be attached to the commits you make.


git config --global user.name “jai M" # Sets your global username for Git

git config --global user.email "email@gmail.com" # Sets your global email for Git


Start a Project

These commands initialize a new Git repository or clone an existing one from a URL (like a GitHub repository).


git init my_project # Creates a new local Git repository in the folder "my_project"

git clone https://github.com/user/repo.git # Clones the repository from GitHub to your local machine


Make a Change

These commands are used to stage changes and commit them to your repository.


git add file.txt # Stages a specific file

git add . # Stages all changes in the current directory

git commit -m "Initial commit" # Commits the staged files with a message

git commit -am "Update file.txt" # Adds and commits all changes in tracked files with a message



Undoing Things
These commands are used to undo changes.

mv old_filename new_filename # Renames a file outside of Git
git mv old_filename new_filename # Renames a file and stages the change
git rm unwanted_file.txt # Removes a file and stages the removal
git rm --cached cached_file.txt # Unstages a file without deleting it from the filesystem
git checkout 12345abc -- file.txt # Restores a file to a specific commit state
git revert 12345abc # Creates a new commit that undoes changes from a specific commit

Review your Repo
These commands give you information about your repository.

git status # Shows the status of changes as untracked, modified, or staged
git log --oneline # Shows a compressed log of commits
git diff # Shows the differences not yet staged
git diff 12345abc 67890def # Shows the differences between two commit


Stashing
Stashing temporarily shelves changes you've made to your working directory so you can work on something else.

git stash # Saves your modifications and temporarily reverts the repo to the last commit
git stash save "work in progress" # Stashes with a message
git stash -p # Stashes interactively, allowing you to select parts of files to stash
git stash list # Lists all stashes
git stash pop stash@{2} # Applies the third latest stash and removes it from the stash list
git stash apply stash@{1} # Applies the second latest stash but doesn't remove it from the list
git stash drop stash@{1} # Deletes the second latest stash
git stash clear # Removes all stashed entries


Synchronizing
These commands sync your local repository with a remote repository, like the one on GitHub.

Commands for Interview
# Initializes a new Git repository
git init
# Example: Initialize a repository in the current directory
git init .

# Clones a repository into a new directory
git clone <repository_url>
# Example: Clone the repository into a specific folder
git clone https://github.com/example/repo.git

# Adds files to the staging area
git add <file_or_directory>
# Example: Add all files in the current directory
git add .

# Commits the staged changes to the repository
git commit -m "Commit message"
# Example: Commit with a message
git commit -m "Initial commit"

# Pulls changes from the remote repository and updates the current branch
git pull <remote> <branch>
# Example: Pull changes from the origin's master branch
git pull origin master

# Pushes commits to the remote repository
git push <remote> <branch>
# Example: Push commits to the origin's master branch
git push origin master

# Displays the status of files in the working directory and staging area
git status
# Example: Check the status
git status

# Shows the commit history
git log
# Example: Show the last two commits
git log -n 2

# Creates a new branch
git branch <branch_name>
# Example: Create a new branch called 'feature'
git branch feature

# Switches to another branch
git checkout <branch_name>
# Example: Switch to the 'master' branch
git checkout master

# Merges a branch into the current branch
git merge <branch_name>
# Example: Merge 'feature' branch into the current branch
git merge feature

# Fetches changes from the remote repository but doesn't merge them
git fetch <remote>
# Example: Fetch changes from the origin
git fetch origin

# Shows changes between commits, commit and working tree, etc.
git diff
# Example: Show changes not yet staged
git diff

# Reverts changes by creating a new commit
git revert <commit>
# Example: Revert the last commit
git revert HEAD

# Resets the staging area and working directory to match a commit
git reset <commit>
# Example: Reset to a specific commit, discarding all changes
git reset --hard <commit_hash>

# Shows a list of all branches, both local and remote
git branch -a
# Example: List all branches
git branch -a

# Deletes a branch
git branch -d <branch_name>
# Example: Delete the 'feature' branch
git branch -d feature

# Stashes changes in a dirty working directory
git stash
# Example: Stash changes
git stash

# Apply stashed changes back to the working directory
git stash apply
# Example: Apply the last stashed changes
git stash apply


Advanced Level Interview Questions for GitHub:

# Applies the changes introduced by some existing commits
git cherry-pick <commit_hash>
# Example: Cherry-pick a specific commit
git cherry-pick 4a5b6c7d

# Rebase the current branch onto <base>
git rebase <base>
# Example: Rebase the current branch onto master
git rebase master

# Interactively rebase current branch
git rebase -i <base>
# Example: Start an interactive rebase for the last 3 commits
git rebase -i HEAD~3

# Amend the most recent commit message
git commit --amend -m "New commit message"
# Example: Amend the message of the most recent commit
git commit --amend -m "Corrected commit message"

# Show various types of objects (blobs, trees, tags, and commits)
git show <object>
# Example: Show information about a commit
git show 1a2b3c4d

# Create, list, delete or verify a signed tag
git tag -a <tag_name> -m "Tag message"
# Example: Create an annotated tag
git tag -a v1.0 -m "Release version 1.0"

# Push a tag to remote
git push <remote> <tag>
# Example: Push a tag to the origin remote
git push origin v1.0

# Create a new working directory from a repository (worktree)
git worktree add <path> <branch>
# Example: Create a new worktree for the 'feature' branch
git worktree add ../feature-worktree feature

# Squash multiple commits into one
# Note: This is typically done during an interactive rebase
git rebase -i HEAD~<number_of_commits>
# Example: Squash the last 3 commits into one
git rebase -i HEAD~3

# Bisect to find the commit that introduced a bug
git bisect start
git bisect bad                 # Mark the current version as bad
git bisect good <commit_hash>  # Mark a known good state
# Git will then automatically checkout commits between good and bad
# and you tell Git if the current state is good or bad until it finds the culprit

# Reset author of the last commit after changing global config
git commit --amend --reset-author
# Example: Reset the author of the most recent commit
git commit --amend --reset-author

# Push the current branch and set the remote as upstream
git push -u <remote> <branch>
# Example: Push the current branch to origin and set it to track the upstream branch
git push -u origin feature

# Show the graph of commits in the terminal
git log --graph --oneline --all
# Example: Visualize the history of all branches
git log --graph --oneline --all

# Clean untracked files from the working tree
git clean -f
# Example: Remove all untracked files
git clean -f

# Update submodules
git submodule update --init --recursive
# Example: Initialize and update all submodules and their submodules
git submodule update --init --recursive


Git reset
The git reset command is a complex and versatile tool for undoing changes. It has three primary forms of invocation. These forms correspond to command line arguments --soft, --mixed, --hard. The three arguments each correspond to Git's three internal state management mechanism's, The Commit Tree (HEAD), The Staging Index, and The Working Directory.

Git rm
A common question when getting started with Git is "How do I tell Git not to track a file (or files) any more?" The git rm command is used to remove files from a Git repository. It can be thought of as the inverse of the git add command.

Git rebase
Rebasing is the process of moving or combining a sequence of commits to a new base commit. Rebasing is most useful and easily visualized in the context of a feature branching workflow.

git cherry-pick
git cherry-pick is a powerful command that enables arbitrary Git commits to be picked by reference and appended to the current working HEAD. Cherry picking is the act of picking a commit from a branch and applying it to another. git cherry-pick can be useful for undoing changes. For example, say a commit is accidently made to the wrong branch. You can switch to the correct branch and cherry-pick the commit to where it should belong.

Bug hotfixes
When a bug is discovered it is important to deliver a fix to end users as quickly as possible. For an example scenario,say a developer has started work on a new feature. During that new feature development they identify a pre-existing bug. The developer creates an explicit commit patching this bug. This new patch commit can be cherry-picked directly to the main branch to fix the bug before it effects more users.

WorkFlow if GitHub:



Git Flow: Develop and Main Branches
Two Main Branches:

Main Branch (main): This is where the official release history is kept. It's clean and production-ready.
Develop Branch (develop): This is for integrating features and preparing them for the next release. It's where developers merge feature branches and test everything together.

Setting Up:
Create the develop Branch:
One developer needs to make an initial develop branch from main.
They do this with two simple commands:

git branch develop
git push -u origin develop

This pushes the new develop branch to the central repository.

Clone and Track develop:
Other team members now clone the main repository and set up a tracking branch for develop.
This means they will pull from and push to develop on the central repository.


Feature branches:
Step 1: Set Up Your Main Branches
First, you have two main branches: main and develop.
main is what the world sees and should be stable.
develop is where all the integration happens.

Step 2: Start Your Feature
Think of each feature as a new project. You want to keep it separate until it's ready.
You start a new feature off the develop branch, not main.

Step 3: Create a Feature Branch
To begin work on a new feature, switch to the develop branch:
git checkout develop; Now create a branch just for your feature:
git checkout -b feature_branch
This makes a new branch called feature_branch based on develop.

Step 4: Do Your Magic
Work on your feature using normal Git commands. Add your files (git add .), make your commits (git commit -m "Your message"), and so on.

Step 5: Finish Up
Once your feature is shiny and complete, you merge it back into develop.
No direct interaction with the main branch happens here.

Step 6: Merge When Ready
After you’ve finished developing your feature, it’s time to merge it back into develop.
This prepares your feature to be part of the next release.


Release branches
Main Branch:
This is the production branch which contains the production-ready code. All releases are merged into this branch.

Develop Branch:
This branch serves as an integration branch for features. It is always ahead of or at the same level as the main branch in terms of commits.

Feature Branches:
These are branched off from the develop branch. Each feature branch is meant for a specific feature or fix. Developers work independently on their feature branches without affecting the main or develop branches.

Release Branches:
When it's time to prepare a new release, a release branch is forked off the develop branch. This branch will contain the code that is about to be released. It allows for last-minute dotting of i's and crossing of t’s.

Hotfix Branches:
These branches are used to quickly patch releases on the main branch. A hotfix branch is created from the main branch, and once the fix is complete, it is merged back into both main and develop.


Hotfix branches
Maintenance or “hotfix” branches are used to quickly patch production releases. Hotfix branches are a lot like release branches and feature branches except they're based on main instead of develop. This is the only branch that should fork directly off of main. As soon as the fix is complete, it should be merged into both main and develop (or the current release branch), and main should be tagged with an updated version number.

Some key takeaways to know about Gitflow are:
The workflow is great for a release-based software workflow.
Gitflow offers a dedicated channel for hotfixes to production.
The overall flow of Gitflow is:

1. A develop branch is created from main
2. A release branch is created from develop
3. Feature branches are created from develop
4. When a feature is complete it is merged into the develop branch
5. When the release branch is done it is merged into develop and main
6. If an issue in main is detected a hotfix branch is created from main
7. Once the hotfix is complete it is merged to both develop and main

Thank You For Reading, Please post your comments for improvements.

No comments:

Post a Comment

Bash Scripting Interview Question and Answers

 Getting Familiar with Bash: Q: What is the role of Bash in a Linux environment?  A: Bash is a command interpreter, or shell. It provides a ...