Git & GitHub
Masterclass

The complete guide for college students — from zero to professional developer workflow.

🐙 Git 🐱 GitHub 🌿 Branching 🤝 Collaboration 💻 VS Code 🔧 Command Line
🔥
SECTION 01

The Problem in Development

Imagine you and three college friends are building a final-year project together:

👨‍💻
Rahul
Frontend Dev
👩‍💻
Priya
Backend Dev
👨‍💻
Arjun
Database Dev
👩‍💼
Anaya
Project Lead

❌ Problem 1 — Lost Work

Rahul finishes the login page on Day 1. On Day 2 he adds changes with a bug. The original working version is gone forever.

❌ Problem 2 — File Name Chaos

To avoid losing work, the team starts creating files like:

project.zip  →  project_v2.zip  →  project_FINAL.zip  →  project_FINAL_use_THIS_one.zip

❌ Problem 3 — Collaboration Nightmare

All four email their app.py. Anaya now has four files with the same name. Who has what? Who overwrote whose work?

❌ Problem 4 — No History, No Accountability

A feature breaks two weeks later. Who broke it? When? Why? No way to find out.

❌ Problem 5 — No Backup

Arjun's laptop crashes. All his database code is gone. The project is stuck for days.

✅ The Solution: Version Control System (VCS)

A VCS automatically tracks every change made to every file — who changed it, when, why — and lets you go back to any earlier version without ever renaming a file. It also enables seamless team collaboration.

📂
SECTION 02

Version Control System — What, Why, Types

What is a Version Control System?

A VCS is software that records every change made to a set of files over time so you can recall specific versions later. Think of it as a time machine for your code.

Why Use VCS?

⏱ Complete History

See every change, who made it, and why.

🧪 Experiment Safely

Try new ideas without breaking working code.

👥 Team Collaboration

Multiple people work simultaneously without conflicts.

🔄 Undo Mistakes

Roll back any change in seconds.

☁️ Backup

Code is safe even if your laptop crashes.

💼 Career Value

Every tech company expects you to know VCS.

Three Types of VCS

🗄️ Local VCS Old

Tracks changes on your computer only. Example: RCS (1980s).

📖 Like a personal diary that only you can read — and only if your house doesn't burn down.

Problem: If your hard drive fails, everything is lost.

🏢 Centralized VCS Older

One server holds all versions. Teams check out files from it. Examples: CVS, SVN.

📖 Like one library book the whole class shares — if the library closes, nobody can work.

Problem: Single point of failure. Server down = everyone stuck.

🌐 Distributed VCS — The Modern Way Industry Standard

Every developer has a complete copy of the entire project history on their own machine. Examples: Git, Mercurial.

📖 Like everyone having their own full photocopy of the entire book — if one person loses theirs, 9 others still have it.

Benefit: Works offline, no single point of failure, fast, collaborative.

Popular Distributed VCS Tools

ToolCreatorBest Known ForStill Used?
GitLinus Torvalds (2005)Linux kernel; now universal✓ Dominant
Mercurial (Hg)Matt MackallSimpler syntax than GitRare
FossilD. Richard HippBuilt-in bug tracker + wikiNiche
BazaarCanonical (Ubuntu)Beginner-friendly designMostly gone
PerforcePerforce SoftwareLarge binaries, game devEnterprise
BitKeeperBitMover Inc.Used for Linux before GitReplaced
DarcsDavid RoundyUnique patch-based modelVery rare
Azure GitMicrosoftGit + Azure DevOps pipelinesEnterprise
🐙
SECTION 03

What is Git and GitHub?

🔧 Git — The Tool on Your Computer

Git is a version control software that lives on your laptop. It tracks every change to your files locally — completely offline.

📖 Like your personal notebook: you write drafts, keep every version, and can flip back to any page.

🐱 GitHub — The Website in the Cloud

GitHub (github.com) is an online platform where you store your Git projects. It's like Google Drive, but built specifically for code and team collaboration.

📖 Like a cloud locker where your team can all read, comment on, and contribute to the same notebook.

💡 Key Insight — Git vs GitHub

You can use Git without GitHub (just tracking files locally). But you cannot use GitHub without Git — GitHub runs on top of Git. They are complementary tools.

What is a Local Repository?

A local repository (local repo) is the .git folder Git creates inside your project on your own laptop. It stores your entire commit history, branches, and snapshots — all on your machine.

📖 Analogy

Your local repo is like your personal diary with every draft you ever wrote — stored in your room, accessible anytime even without internet.

What is a Remote Repository?

A remote repository (remote repo) is a copy of your project stored on a server — like GitHub, GitLab, or Bitbucket. It's the shared "source of truth" your team all syncs with.

📖 Analogy

The remote repo is like a shared Google Doc that everyone on the team can view, contribute to, and sync from — but it only shows what you've explicitly uploaded (git push).

Local vs Remote — Side by Side

FeatureLocal RepositoryRemote Repository (GitHub)
Where it livesYour laptop (.git folder)GitHub's servers (cloud)
Internet needed?No — works offlineYes
Who can see it?Only youPublic or private (you choose)
If laptop crashes…Code is goneSafe in the cloud
Team collaboration?NoYes — everyone syncs here
How to syncgit push to send upgit pull / clone to get

How Git and GitHub Work Together

Team Workflow Diagram
Rahul's Laptop           GitHub.com (Remote)          Priya's Laptop
(Local Git Repo)         (Shared Cloud Repo)          (Local Git Repo)
      |                          |                           |
      |──── git push ───────────►|                           |
      |                          |◄──── git push ────────────|
      |◄─── git pull ────────────|                           |
      |                          |────── git clone ─────────►|
      |                          |                           |
  [Commits on your              [Everyone's commits        [Full copy of
   machine only]                 sync here]                 project here]

What Files Does Git Create?

When you run git init, Git creates a hidden .git folder. Never edit this manually — Git manages it automatically.

your-project/
├── src/
│   └── main.py          ← Your actual code
├── README.md
└── .git/                ← Git's database (hands off! 🚫)
    ├── objects/         ← Every version of every file (as snapshots)
    ├── refs/            ← Pointers to branches and tags
    ├── HEAD             ← Which branch you're on right now
    ├── config           ← Local repository settings
    ├── COMMIT_EDITMSG   ← Your last commit message
    └── hooks/           ← Optional scripts that run on Git events

What Should (and Shouldn't) Go in Git?

✅ Include in Git❌ Never Include
Source code (.py, .js, .java, .html)Passwords, API keys, .env files
README.md and documentationnode_modules/, venv/, .vscode/
Configuration files (non-secret)Compiled/built files (__pycache__, .o, dist/)
Database schemas (structure, not data)Large binary files (videos, raw datasets)
Tests and test dataIDE-specific settings (.idea/)
⚙️
SECTION 04

Git Setup — Windows / Mac / Linux

Step 1 — Install Git on Your Machine

🪟 Windows

  1. Go to git-scm.com
  2. Click "Download for Windows"
  3. Run the installer (click Next for all options)
  4. You now have Git Bash — your terminal

🍎 macOS

  1. Open Terminal (Spotlight → type Terminal)
  2. Run: git --version
  3. Usually pre-installed! If not, macOS will prompt you
  4. Or install via Homebrew: brew install git

🐧 Linux

  1. Ubuntu/Debian: sudo apt install git
  2. Fedora: sudo dnf install git
  3. Arch: sudo pacman -S git
  4. Done!

Step 2 — Basic CMD to Verify & Configure Git

Terminal — Git Setup
# Check Git is installed correctly
$ git --version
git version 2.43.0

# Tell Git who you are (one-time setup — use your real name & email)
$ git config --global user.name "Rahul Kumar"
$ git config --global user.email "rahul@example.com"

# Set VS Code as your default editor
$ git config --global core.editor "code --wait"

# Verify all settings
$ git config --list
user.name=Rahul Kumar
user.email=rahul@example.com
core.editor=code --wait

⚠️ Email Must Match Your GitHub Account

When you create a GitHub account, use the exact same email you set here. This is how GitHub links your commits to your profile and shows green contribution dots on your profile page.

Step 3 — Create a GitHub Account

1

Go to github.com

Click "Sign up" — it's free.

2

Choose a Professional Username

Use your real name if possible: rahul-kumar or rahulkumar. Recruiters will see this in your portfolio URL: github.com/rahul-kumar

3

Verify Your Email

GitHub sends a confirmation email — click the link inside it.

4

Set Up Your Profile

Add a photo, bio, and your college. A complete profile looks professional to recruiters.

Step 4 — Create a Git Profile README on GitHub

🌟 GitHub Profile README — Your Developer Business Card

GitHub has a special secret repo: create a repo with your exact username as the repo name. The README.md inside it shows up on your GitHub profile page for everyone to see!

1

Create a new repo named after yourself

Go to GitHub → New Repository → Name it rahul-kumar (your username) → Check ✅ "Add a README file" → Create.

2

Edit the README.md

Write about yourself: your skills, projects, college, and contact. This is shown on your public profile!

3

Commit the changes

Click "Commit changes" on GitHub. Visit your profile — your README is live! 🎉

🚀
SECTION 05

Ways to Manage & Upload Repos to GitHub

There are two main approaches to get your code onto GitHub — choose based on whether you start on GitHub or on your local machine.

🅰️ Method 1 — Remote First (Create on GitHub, Clone Locally)

When to use: You're starting a brand-new project. Most beginner-friendly.

Flow: Create repo on GitHub → Copy the URL → Clone it to your laptop → Start coding.

🅱️ Method 2 — Local First (Create Locally, Push to GitHub)

When to use: You already have a folder with code on your laptop and want to put it on GitHub.

Flow: git init locally → Create empty repo on GitHub → Connect them → Push.

Method 1 — Create Remote Repo First, Then Clone

1

Create a repo on GitHub

Go to GitHub → click + → New Repository → give it a name → check ✅ "Add a README file" → click Create Repository.

2

Copy the repo URL

Click the green Code button → Copy the HTTPS or SSH URL.

3

Clone it to your laptop

This downloads the entire repo to your machine, already connected to GitHub.

Method 1 — Clone from GitHub
# Navigate to where you want the project folder
$ cd Desktop

# Clone the repo — this creates a folder with all the files
$ git clone https://github.com/rahul-kumar/my-project.git
Cloning into 'my-project'...
remote: Enumerating objects: 3, done.
✓ Done! Folder 'my-project' created.

$ cd my-project
# You're inside! Start coding. The remote is already connected.

✅ Why This Method is Easier for Beginners

The repo is automatically connected to GitHub — no need to run git remote add origin. Just clone and start coding!

Method 2 — Create Local Repo First, Push to GitHub

1

Create a project folder locally

mkdir my-project then cd my-project

2

Initialize Git

git init — Git now tracks this folder.

3

Make your first commit

Add a file, stage it, commit it.

4

Create an empty repo on GitHub

Go to GitHub → New Repository → do NOT check README → Create.

5

Connect local to GitHub and push

Run the commands GitHub shows you on screen.

Method 2 — Local First, Push to GitHub
# Create folder and initialize Git
$ mkdir my-project && cd my-project
$ git init
Initialized empty Git repository in .git/

# Create first file and commit
$ echo "# My Project" > README.md
$ git add README.md
$ git commit -m "Initial commit: add README"
[main (root-commit) a1b2c3d] Initial commit

# Connect your local repo to the GitHub repo you just created
$ git remote add origin https://github.com/rahul-kumar/my-project.git

# Verify connection
$ git remote -v
origin https://github.com/rahul-kumar/my-project.git (fetch)
origin https://github.com/rahul-kumar/my-project.git (push)

# Push to GitHub for the first time
$ git push -u origin main
Branch 'main' set up to track remote branch 'main' from 'origin'.
✓ Your code is now on GitHub!

Git CMD vs VS Code GitHub Setup

🖥️ Command Line Git

You type Git commands in a terminal (Git Bash on Windows, Terminal on Mac/Linux). Full control, works anywhere, essential skill for all developers.

Best for: All developers — must learn this.

🔷 VS Code Built-in GitHub

VS Code has a built-in Source Control panel (the branch icon on the left sidebar). You can stage, commit, and push with mouse clicks — no terminal needed.

Best for: Beginners who want a visual approach alongside learning CLI.

🔷 How to Use VS Code for Git

1. Open your project folder in VS Code.
2. Click the Source Control icon (branch icon) in the left sidebar.
3. Make changes to files — they appear in the "Changes" list automatically.
4. Click + next to a file to stage it (same as git add).
5. Type a message in the box at the top and click ✓ Commit.
6. Click the ⋯ menu → Push (same as git push).

💻
SECTION 06

Basic Commands — Terminal & Git

Terminal Navigation Commands

CommandWhat it DoesExample
pwdPrint Working Directory — shows your current locationpwd/home/rahul/Desktop
lsList files and folders in current directoryls
ls -laList all files including hidden ones (like .git)ls -la
cdChange Directory — navigate into a foldercd Desktop
cd ..Go up one level (parent folder)cd ..
mkdirMake a new directory/foldermkdir my-project
echoPrint text or write text to a fileecho "Hello" > hello.txt
sudoRun a command with admin/superuser privilegessudo apt install git
touchCreate an empty filetouch .gitkeep
catShow contents of a file in the terminalcat README.md

Core Git Commands — Daily Use

Essential Git Commands
# ─── START A PROJECT ───────────────────────────
$ git init
Initialized empty Git repository in .git/

# ─── CHECK STATUS ──────────────────────────────
$ git status
On branch main
Untracked files: login.py, styles.css

# ─── STAGE FILES ───────────────────────────────
$ git add login.py # Stage one specific file
$ git add . # Stage ALL changed files
$ git add *.css # Stage all CSS files

# ─── COMMIT (SAVE A SNAPSHOT) ──────────────────
$ git commit -m "Add login page with validation"
[main a1b2c3d] Add login page with validation
2 files changed, 47 insertions(+)

# ─── PUSH TO GITHUB ────────────────────────────
$ git push origin main # Upload commits to GitHub
To https://github.com/rahul-kumar/my-project.git
a1b2c3d..9e8f7g6 main → main

# ─── CLONE A REPO ──────────────────────────────
$ git clone https://github.com/username/repo.git
Cloning into 'repo'...

The Three Stages of Git — Most Important Concept!

📊 Working Directory → Staging Area → Repository
  ┌──────────────────┐    git add     ┌──────────────────┐   git commit   ┌──────────────────┐
  │  Working Directory│ ─────────────► │   Staging Area   │ ──────────────►│  Repository (.git)│
  │  (Your files)    │                │  (Prepared zone) │                │  (Permanent save) │
  │                  │                │                  │                │                  │
  │  You freely edit │                │ You choose which │                │ Git saves snapshot│
  │  files here      │                │ changes to save  │                │ forever here      │
  └──────────────────┘                └──────────────────┘                └──────────────────┘
         ↑                                                                        │
         └──────────────────────── git restore ←────────────────────────────────┘
                                    (undo changes)

📖 Analogy — The Post Office

Working Directory = Your desk where you write letters.
Staging Area = The envelope — you choose which letters to put inside.
Commit (Repository) = Sealing and posting the envelope — it's sent and saved permanently.

📄
SECTION 07

Git Special Files

1. .gitignore — Tell Git What to Skip

📖 Analogy — Packing a Suitcase

You're packing for a trip. You want your clothes — but NOT your household trash or private diary. .gitignore is a checklist you give Git that says: "Do NOT pack these items."

Create a file called .gitignore in your project root:

.gitignore — Example File
# Secret files — NEVER push these to GitHub!
.env
secrets.txt
config/database.yml

# Dependency folders (can be reinstalled anytime)
node_modules/
venv/
.venv/

# Compiled/generated files
__pycache__/
*.pyc
dist/
build/

# IDE settings
.vscode/
.idea/
*.DS_Store # Mac junk file

💡 Pro Tip: gitignore.io

Go to gitignore.io — type your language/framework (e.g. "Python", "Node", "React") and it generates the perfect .gitignore for you automatically!

2. .gitattributes — Consistent Formatting Across Machines

📖 Analogy — Writing Style Guide

Imagine two people writing a book together — one uses Windows (which adds a special invisible character at the end of every line) and one uses Mac. The code looks different even when it's the same. .gitattributes is a rule book that forces every computer to format files the same way.

# .gitattributes — Place in your project root

# Auto-detect text files and handle line endings
* text=auto

# Force all code files to use Linux/Mac line endings (LF)
*.js   text eol=lf
*.html text eol=lf
*.css  text eol=lf
*.py   text eol=lf
*.json text eol=lf

# Tell Git these are binary — don't try to merge them as text
*.png  binary
*.jpg  binary
*.gif  binary
*.zip  binary
*.pdf  binary

3. .gitkeep — Keep Empty Folders in Git

📖 Analogy — The Rock in the Box

Git is like a mail carrier that only delivers boxes with something inside. If you give Git an empty folder, it ignores it. .gitkeep is a tiny empty file (a "rock") you put inside an empty folder so Git will track and carry it.

.gitkeep — How to Use
# You have an uploads/ folder that should exist but is empty
$ mkdir -p public/uploads
$ touch public/uploads/.gitkeep

# Now git will track the folder even though it's empty
$ git add public/uploads/.gitkeep
$ git commit -m "Keep uploads folder structure in repo"
[main 7f3d2a1] Keep uploads folder structure in repo
my-project/
├── public/
│   └── uploads/
│       └── .gitkeep    ← This tiny blank file forces Git to track the folder
├── src/
│   └── main.py
└── README.md
🔁
SECTION 08

How to Work with Git — Daily Workflow

The Standard Developer Loop

✏️ Edit Files
📦 git add
💾 git commit
☁️ git push
🔄 Repeat
Complete Daily Workflow
# ── STEP 1: Start of day — get latest changes from team ──
$ git pull origin main
Already up to date.

# ── STEP 2: Edit your files in VS Code ──────────────────
# (open editor, write code, save files)

# ── STEP 3: Check what changed ──────────────────────────
$ git status
On branch main
Modified: login.py
Untracked: dashboard.html

# ── STEP 4: Stage your changes ──────────────────────────
$ git add .

# ── STEP 5: Commit with a clear message ─────────────────
$ git commit -m "Add login page validation and fix redirect bug"
[main 9f8e7d6] Add login page validation and fix redirect bug

# ── STEP 6: Push to GitHub ───────────────────────────────
$ git push origin main
To github.com:rahul-kumar/my-project.git
main → main ✓

How to Work Together with Git (Team Rules)

✅ Rule 1 — Never Push Directly to Main

The main branch should always be working, tested code. Always create a feature branch, work there, and only merge after review.

✅ Rule 2 — Always Pull Before You Start

Run git pull origin main every morning before writing a single line. This prevents conflicts with your teammates' work.

✅ Rule 3 — Commit Frequently, With Clear Messages

Commit every 30–60 minutes. Don't wait until the end of the day. More commits = finer history = easier debugging.

❌ Bad: "fixed stuff"    ✅ Good: "Fix null pointer when login form is submitted with empty password"

✅ Rule 4 — One Feature = One Branch = One Pull Request

Keep each branch focused. Don't mix login changes and dashboard changes in the same branch. Small, focused branches are easier to review and merge.

🌿
SECTION 09

Git Branch Commands

📖 What is a Branch?

A branch is a parallel version of your project. Think of it like a parallel universe — you can experiment in your universe without affecting the main one. When your experiment works, you merge it back.

📖 Like a book draft — you write a new chapter on separate paper. If you like it, you paste it in. If you hate it, you throw the paper away — the original book is untouched.

Branching Visualization
  main:              A ──── B ──── C ──────────────── G (merge)
                                   \                  /
  feature-login:                    D ──── E ──── F
                                   (Rahul works here safely)

Branch Commands

Git Branch Commands
# ── LIST BRANCHES ──────────────────────────────────────
$ git branch
* main ← * means you're currently on this branch
feature-login

$ git branch -a # Show ALL branches including remote
* main
feature-login
remotes/origin/main
remotes/origin/feature-login

# ── CREATE A NEW BRANCH ────────────────────────────────
$ git branch feature-dashboard # Creates branch, stays on current
$ git checkout -b feature-payment # Creates AND switches to new branch
$ git switch -c feature-api # Modern way to create + switch

# ── SWITCH BETWEEN BRANCHES ────────────────────────────
$ git checkout main # Old way — still works
$ git switch main # New, cleaner way (Git 2.23+)

# ── DELETE A BRANCH ────────────────────────────────────
$ git branch -d feature-login # Safe delete (only if merged)
$ git branch -D feature-login # Force delete even if not merged
$ git push origin --delete feature-login # Delete from GitHub too

git checkout vs git switch — What's the Difference?

CommandWhat It DoesWhen to Use
git checkout branch-nameSwitch to an existing branch (old syntax)Works in all Git versions
git checkout -b new-branchCreate AND switch to new branch (old syntax)Very common in tutorials
git switch branch-nameSwitch to existing branch (new, cleaner syntax)Git 2.23+ preferred
git switch -c new-branchCreate AND switch to new branch (new syntax)Modern way — recommended

💡 Tip

Both git checkout and git switch work. Many online tutorials still use checkout — learn both but prefer switch for new projects as it's clearer and less confusing.

🔗
SECTION 10

Intermediate Git Commands

git remote — Managing Connections

git remote
# View your remote connections
$ git remote -v
origin https://github.com/rahul-kumar/project.git (fetch)
origin https://github.com/rahul-kumar/project.git (push)

# Add a new remote (connect to GitHub)
$ git remote add origin https://github.com/username/repo.git

# Change the remote URL (e.g. if you renamed the repo on GitHub)
$ git remote set-url origin https://github.com/username/new-name.git

# Remove a remote connection
$ git remote remove origin

git pull — Fetch + Merge in One Step

📖 What git pull Does

git pull does TWO things in one command: (1) fetch — downloads new commits from GitHub, and (2) merge — integrates those commits into your current branch. It's the shortcut you use every morning.

git pull
# Download + merge latest changes from main branch
$ git pull origin main
remote: Enumerating objects: 5, done.
Updating a1b2c3d..9e8f7g6
Fast-forward: login.py | 3 +++

# If you're on main already, shortcut:
$ git pull

git fetch — Download Without Merging

📖 git fetch vs git pull

git fetch downloads new commits from GitHub but does NOT merge them into your code. It lets you see what changed before you decide to integrate it. Think of it as "look before you leap".

📖 fetch = downloading a package at your door. pull = opening it and unpacking immediately.

git fetch vs git pull
# Download changes but don't apply them yet
$ git fetch origin
From github.com:rahul-kumar/project
a1b2c3d..9e8f7g6 main → origin/main

# Review what changed
$ git log main..origin/main --oneline
9e8f7g6 Add payment API endpoint (Priya)

# Now merge when you're ready
$ git merge origin/main

git merge — Combine Branches

git merge
# Switch to main first
$ git checkout main

# Merge Rahul's feature branch into main
$ git merge feature-dashboard
Updating a1b2c3d..9e8f7g6
Fast-forward
dashboard.html | 45 +++++++++

# If there's a conflict Git will tell you:
CONFLICT (content): Merge conflict in config.py
Automatic merge failed; fix conflicts then commit.

# Open config.py, find conflict markers, fix them, then:
$ git add config.py
$ git commit -m "Resolve merge conflict in config.py"

⚠️ What a Merge Conflict Looks Like

When two people edit the same line, Git shows both versions and asks you to decide:

<<<<<<< HEAD (your version)
DATABASE_HOST = "localhost"
=======
DATABASE_HOST = "production-server"
>>>>>>> feature-api (their version)

Delete the conflict markers (<<<, ===, >>>) and keep the correct line. Then git add and git commit.

🧠
SECTION 11

Advanced Git Commands

git log — View History

git log — See Your Project History
# Simple one-line history
$ git log --oneline
9e8f7g6 Add payment API
a1b2c3d Add login page
7f3d2a1 Initial commit

# Visual graph showing branches and merges
$ git log --oneline --graph --all
* 9e8f7g6 (HEAD → main) Merge feature-login
|\
| * 5h4i3j2 (feature-login) Add login validation
|/
* a1b2c3d Initial commit

# Search commits by keyword
$ git log --grep="login"
# Show commits by a specific author
$ git log --author="Rahul"
# Show detailed changes in a commit
$ git show a1b2c3d

git diff — See Exactly What Changed

git diff
# See unstaged changes (what you changed but haven't added yet)
$ git diff
- old line that was removed
+ new line that was added

# See staged changes (what you git added, ready to commit)
$ git diff --staged

# Compare two branches
$ git diff main feature-login

# Compare two commits
$ git diff a1b2c3d 9e8f7g6

git stash — Pause Your Work Temporarily

📖 Analogy — Saving Your Game Mid-Level

You're coding a new feature when your team lead says "critical bug — fix it NOW!" Your code is half-done — not ready to commit. git stash saves your work-in-progress in a temporary drawer so you can switch tasks immediately, then come back and pick up exactly where you left off.

git stash
# Save your half-done work (clears working directory)
$ git stash
Saved working directory and index state WIP on main

$ git status
nothing to commit, working tree clean ← clean slate!

# Fix the bug, commit, push...
$ git commit -m "Critical: fix payment crash bug"

# Bring your stashed work back
$ git stash pop
Dropped stash@{0} — your changes are back! 🎉

# See all stashes saved
$ git stash list
stash@{0}: WIP on main: Add dashboard header

git reset — Undo Commits

git reset --soft HEAD~1
# Undo the last commit but KEEP your changes (files stay edited)
$ git reset --soft HEAD~1
Unstaged changes after reset: login.py
# Your code is still there, just un-committed — fix the message or add more

# Undo the last commit AND unstage (files stay but not staged)
$ git reset --mixed HEAD~1

# ⚠️ DANGER: Undo commit AND delete your changes forever
$ git reset --hard HEAD~1
HEAD is now at a1b2c3d Previous commit (changes GONE)

git tag — Mark Important Versions

git tag
# Create a version tag (like v1.0, v2.1)
$ git tag v1.0

# Tag with a message (annotated tag — preferred for releases)
$ git tag -a v1.0 -m "First stable release"

# Push the tag to GitHub
$ git push origin v1.0
To github.com:rahul-kumar/project.git
* [new tag] v1.0 → v1.0

# Push ALL tags at once
$ git push origin --tags

# List all tags
$ git tag
v1.0
v1.1

revert vs reset vs checkout — Key Differences

CommandWhat It DoesSafe to Use After Pushing?Use Case
git revert <id> Creates a new commit that undoes the changes of a previous commit. History stays intact. ✅ Yes — Safe Undo something that's already on GitHub/in production
git reset HEAD~1 Moves the branch pointer back, erasing commits from history. ⚠️ No — Dangerous Undo commits that are only on your local machine
git checkout <file> Discards unsaved changes in a file, restoring it to the last commit. ✅ Always safe Oops — throw away edits you haven't committed yet

⚠️ Golden Rule of Undo

If the commit is only on your laptop (not pushed) → use git reset.
If the commit is already on GitHub → use git revert (it's safe, doesn't break teammates' history).

🐱
SECTION 12

GitHub Features — Collaboration & Community

Star a Repository

Like bookmarking a project you find useful. Stars show appreciation to creators and let you find repos later. A repo with many stars = popular & trusted.

How: Open any repo → click the ⭐ Star button in the top right.

🍴

Fork a Repository

Creates your own personal copy of someone else's project. You can freely change your fork without touching the original. Essential for contributing to open source.

How: Open repo → click Fork button → it appears under your account.

🐛

Raise an Issue

Report a bug, suggest a feature, or ask a question about a project. Issues are public discussions tied to the repository.

How: Repo → Issues tab → New Issue → describe the problem clearly.

🔀

Pull Request (PR)

A request to merge your branch (or fork) into the main codebase. The team reviews your changes, leaves comments, requests edits, and eventually approves + merges.

How: Push your branch → GitHub shows "Compare & pull request" → fill details → submit.

🤝

Contributing to a Repo

The standard open-source flow: Fork → Clone your fork → Create a branch → Make changes → Push → Open a PR to the original repo.

Most repos have a CONTRIBUTING.md file explaining how to contribute.

⚙️

Managing Pull Requests

As a reviewer: read the code, leave inline comments, request changes, or approve. As the author: respond to comments, push updates, and the PR auto-updates.

Merge options: Merge commit / Squash & merge / Rebase & merge.

Full Open Source Contribution Workflow

1

Fork the Repository

Click Fork on GitHub → creates your-username/project as your own copy.

2

Clone YOUR Fork Locally

git clone https://github.com/YOUR-USERNAME/project.git

3

Add Original as "upstream"

git remote add upstream https://github.com/ORIGINAL-AUTHOR/project.git
This lets you pull future updates from the original.

4

Create a Feature Branch

git checkout -b fix-typo-in-readme

5

Make Changes and Commit

Edit files → git add .git commit -m "Fix typo in README"

6

Push to YOUR Fork

git push origin fix-typo-in-readme

7

Open a Pull Request

Go to the original repo on GitHub → GitHub detects your push → click "Compare & pull request" → describe your changes → submit!

SSH vs HTTPS — Which Should You Use?

🔒 HTTPS

Pros: Zero setup, works everywhere out of the box.

Cons: GitHub asks for credentials every time (unless you use a credential manager).

Best for: One-time cloning or unfamiliar computers.

🔑 SSH

Pros: Set up once → never type a password again. Faster and more secure.

Cons: Needs 5-minute setup (generate key, add to GitHub).

Best for: Your own laptop — the professional way.

Set Up SSH Key (one-time)
# Generate SSH key (accept defaults, press Enter)
$ ssh-keygen -t ed25519 -C "rahul@example.com"
Generating public/private ed25519 key pair...

# Copy the public key to clipboard
$ cat ~/.ssh/id_ed25519.pub
ssh-ed25519 AAAAC3Nza... rahul@example.com

# Then: GitHub → Settings → SSH Keys → New SSH Key → Paste it
# Test it:
$ ssh -T git@github.com
Hi rahul-kumar! You've successfully authenticated. 🎉
📋
SECTION 13

Complete Command Cheat Sheet

⚙️ Setup (One-Time)
git config --global user.name "Name"Set your name
git config --global user.email "a@b.com"Set email
git config --listView all config
git --versionCheck Git version
🚀 Start a Project
git initInitialize new repo
git clone <url>Download repo from GitHub
git remote add origin <url>Connect to GitHub
git remote -vCheck remote connection
📦 Daily Workflow
git statusSee changed files
git add <file>Stage a file
git add .Stage all changes
git commit -m "msg"Save snapshot
git push origin mainUpload to GitHub
git pull origin mainDownload latest
🌿 Branching
git branchList branches
git branch <name>Create branch
git switch <name>Switch branch (new)
git checkout <name>Switch branch (old)
git switch -c <name>Create + switch
git branch -d <name>Delete branch
🔗 Sync & Merge
git fetch originDownload (no merge)
git merge <branch>Merge branch in
git push -u origin mainFirst push ever
git push origin <branch>Push a branch
🔧 Fix Mistakes
git restore <file>Discard file changes
git restore --staged <file>Unstage a file
git reset --soft HEAD~1Undo last commit (keep files)
git reset --hard HEAD~1⚠️ Undo + delete changes
git revert <commit-id>Safe undo (new commit)
🕵️ Inspect
git log --onelineShort history
git log --oneline --graph --allVisual branch history
git diffSee unstaged changes
git diff --stagedSee staged changes
git show <commit-id>Details of one commit
⚡ Advanced
git stashSave work-in-progress
git stash popRestore stashed work
git stash listSee all stashes
git tag v1.0Create a version tag
git push origin v1.0Push tag to GitHub
git push origin --tagsPush all tags

Alternative Git Hosting Platforms

🦊 GitLab

More features than GitHub, generous free tier, can self-host on your own server. Great for teams wanting full control.

🪣 Bitbucket

Integrates deeply with Jira and the Atlassian suite. Free for small teams. Used heavily in enterprise software companies.

🫖 Gitea

Ultra-lightweight, self-hosted only. Perfect for companies wanting a private internal Git server with minimal resources.

💼 The Industry Reality

Every tech company — from startups to Google — uses Git. Most use GitHub. Learning Git and GitHub makes you instantly employable. If a company uses GitLab or Bitbucket instead, you'll transfer your Git knowledge in minutes since the commands are identical. The platform changes, the tool (Git) stays the same.