1
Git and GitHub Fundamentals & Mental Model
🇬🇧 English Definition
Git is a distributed version-control system that tracks local file changes, commits, and branch history. GitHub is a cloud hosting platform for Git repositories that adds collaboration tools like Pull Requests, Code Review, Issues, Actions CI/CD, and Security scanning.
🇮🇳 Hinglish Definition
Git tumhare local machine par code changes aur history ko track karta hai. GitHub isi code ko online host karke team collaboration, review aur automation provide karta hai.
🔄 Mental Model Architecture Flowchart
Working Tree
Edited files
Edited files
➔
Staging Area
Staged changes
Staged changes
➔
Local Git Repo
Committed snapshots
Committed snapshots
➔
GitHub Remote
Cloud repository
Cloud repository
| Term | Meaning | Example |
|---|---|---|
| Repository | Project + Git history database | .git directory + project files |
| Working tree | Files currently being edited | app.py modified |
| Staging area | Next commit selection buffer | git add app.py |
| Commit | Recorded snapshot in history | abc1234 SHA hash |
| Branch | Movable commit pointer reference | main, feature/login |
| Remote | Named external GitHub repository | origin |
| Pull request | Proposed change for peer review | feature/login ➔ main |
| Workflow | GitHub Actions CI/CD automation | .github/workflows/ci.yml |
2
Install Git and GitHub CLI
// Verify Git installation
git --version
git --help
// Verify GitHub CLI installation
gh --version
// Authenticate GitHub CLI with browser/token
gh auth login
gh auth status
| Tool | Purpose / Description |
|---|---|
| Git | Core version control engine |
| Git Bash | Unix-like terminal shell on Windows |
| PowerShell | Windows terminal automation shell |
| GitHub CLI (gh) | GitHub interaction directly from terminal |
| VS Code / IDE | Code editing, Git integration and visual diff debugging |
3
First-Time Git Configuration
git config --global user.name "Your Name"
git config --global user.email "you@example.com"
git config --global init.defaultBranch main
// Inspect active configuration
git config --global --list
git config --list --show-origin
// Recommended optional settings
git config --global core.autocrlf true
git config --global fetch.prune true
git config --global pull.rebase false
4
Authentication: HTTPS, SSH and Tokens
| Method | Use Case | Key Security Idea |
|---|---|---|
| HTTPS | Clone/push over HTTPS | Requires Personal Access Token or Credential Helper |
| SSH | Clone/push with key pair | Private key stays safe on your machine |
| Token (PAT) | API / HTTPS authentication | Treat like password; scope narrowly |
| GitHub CLI auth | Terminal authentication | `gh auth login` automates secure token exchange |
// SSH Key Generation (ed25519)
ssh-keygen -t ed25519 -C "you@example.com"
// Add ~/.ssh/id_ed25519.pub to GitHub Account Settings -> SSH Keys
// Test SSH Connection
ssh -T git@github.com
5
Create / Clone a Repository
// Clone existing remote repo
git clone git@github.com:USERNAME/REPO.git
cd REPO
git remote -v
git status
// Initialize local repo and connect to GitHub remote
mkdir my-project
cd my-project
git init
git branch -M main
git remote add origin git@github.com:USERNAME/my-project.git
6
Repository Structure & Important Configuration Files
| Path / File | Purpose & Best Practice |
|---|---|
| .git/ | Git metadata and internal object database |
| README.md | Project overview, setup guidelines & usage documentation |
| .gitignore | Excludes build artifacts, secrets, and node_modules from Git |
| LICENSE | Legal open-source or proprietary licensing terms |
| CONTRIBUTING.md | Guidelines for external open-source contributors |
| SECURITY.md | Vulnerability reporting instructions & contact details |
| CODEOWNERS | Defines path-based review ownership rules |
| .github/workflows/ | GitHub Actions CI/CD automation workflow YAML files |
| .github/ISSUE_TEMPLATE/ | Standardized issue submission forms |
| .github/PULL_REQUEST_TEMPLATE.md | Standardized PR submission checklist |
| .github/dependabot.yml | Automated dependency update configuration |
| CHANGELOG.md | Human-readable version release history |
7
Git File Lifecycle
🇬🇧 English Definition
Git moves changes through 4 main states: Untracked/Modified, Staged (index buffer), Committed (local repository snapshot), and Pushed (GitHub remote repository).
🇮🇳 Hinglish Definition
File pehle working tree mein change hoti hai, phir `git add` se staging area mein jaati hai, `commit` se local history mein aur `push` se GitHub par.
🔄 File Lifecycle Flowchart
Untracked / Modified
Working Tree
Working Tree
➔
Staged
Index Buffer
Index Buffer
➔
Committed
Local History
Local History
➔
Pushed to GitHub
Remote Repo
Remote Repo
8
Essential Git Command Reference Table
| Command | Syntax Example | Purpose |
|---|---|---|
| init | git init | Create new local repository |
| clone | git clone URL | Copy remote repository |
| status | git status | Inspect current repository state |
| add | git add . | Stage modified files |
| commit | git commit -m "msg" | Create permanent commit snapshot |
| log | git log --oneline --graph | View commit history graph |
| show | git show SHA | Inspect specific commit details |
| diff | git diff | Inspect unstaged differences |
| switch | git switch -c branch | Create and switch branch |
| branch | git branch -a | List local and remote branches |
| merge | git merge branch | Combine history of branches |
| rebase | git rebase origin/main | Replay commits on new base |
| fetch | git fetch origin | Download remote references |
| pull | git pull | Fetch + integrate remote changes |
| push | git push -u origin branch | Upload local commits to remote |
| restore | git restore file | Discard uncommitted local changes |
| reset | git reset --soft HEAD~1 | Move branch pointer backwards |
| revert | git revert SHA | Create inverse commit safely |
| stash | git stash push -m "WIP" | Temporarily shelve changes |
| tag | git tag -a v1.0.0 -m "msg" | Create annotated version tag |
| remote | git remote -v | Display configured remote URLs |
| clean | git clean -n | Preview untracked files cleanup |
| reflog | git reflog | Inspect reference log for recovery |
9
git status / diff / add / commit Workflow
git status
git diff
git add .
git diff --cached
git commit -m "feat: add user registration"
// Stage specific file
git add app.py
// Stage selected interactive chunks (patch mode)
git add -p
🔍 Recommended Habit
10
Commit Messages & Conventional Commits
| Type | Example | Use Case |
|---|---|---|
| feat | feat: add payment API | New feature for end user |
| fix | fix: handle null user input | Bug fix |
| docs | docs: update setup guide | Documentation only |
| refactor | refactor: simplify auth middleware | Code change without behavior alteration |
| test | test: add login integration test | Adding or modifying tests |
| chore | chore: update dependencies | Maintenance task |
| build | build: update Docker toolchain | Build system / external dependencies |
| ci | ci: add GitHub Actions matrix | CI/CD workflow changes |
git log --oneline --graph --decorate --all
git show HEAD
git show HEAD~1
git log --since="2 weeks ago"
git log --author="Name"
git log -- path/to/file.py
11
Branches and Naming Conventions
git branch
git branch -a
git switch -c feature/login
git switch main
git branch -m feature/login feature/user-login
git branch -d feature/user-login
// Push new branch to remote
git push -u origin feature/user-login
git push origin --delete feature/user-login
12
Merge and Fast-Forward
git switch main
git pull --ff-only
git merge feature/user-login
// Abort conflicted merge
git merge --abort
🇬🇧 Fast-Forward Merge
Fast-forward occurs when the target branch HEAD has no divergent commits; Git moves the main pointer forward directly without creating an explicit merge commit.
🇮🇳 Non-Fast-Forward Merge
Jab dono branches par alag-alag commits ban jaate hain, toh Git divergent histories ko merge commit ke through combine karta hai.
13
Merge Conflicts Resolution
git status
git diff
// Resolution Steps:
// 1. Manually edit file to remove conflict markers and select clean code
// 2. Stage resolved file:
git add app.py
git commit -m "fix: resolve merge conflict in app.py"
// Cancel merge if needed:
git merge --abort
14
Rebase and Interactive Rebase
git fetch origin
git switch feature/login
git rebase origin/main
// Interactive Rebase (Clean last 5 commits)
git rebase -i HEAD~5
| Action | Meaning |
|---|---|
| pick | Keep commit in history as is |
| reword | Keep commit but edit commit message |
| edit | Pause rebase to modify commit content |
| squash | Combine commit into previous commit |
| fixup | Combine commit into previous commit and discard message |
| drop | Remove commit completely from history |
🎯 Golden Rule of Rebase
Never rebase commits that have already been pushed to a shared/protected public branch. Use rebase strictly for cleaning up private local feature branches before merging.
15
Restore vs Reset vs Revert
| Goal | Command | Best Use Case & Safety |
|---|---|---|
| Discard file changes | git restore file | Unstaged local changes |
| Unstage file | git restore --staged file | Remove file from staging index |
| Undo shared commit | git revert SHA | Safe for team/remote history |
| Move HEAD, keep changes | git reset --soft HEAD~1 | Local history cleanup |
| Move HEAD and index | git reset HEAD~1 | Local history cleanup |
| Discard local changes | git reset --hard HEAD~1 | Dangerous; rewrites history permanently |
git restore app.py
git restore --staged app.py
git revert abc1234
git reset --soft HEAD~1
git reset HEAD~1
git reset --hard HEAD~1
16
Reflog and Recovery
🇬🇧 English Definition
Git reflog (reference log) records every movement of HEAD and local branch pointers. It allows recovering lost commits, deleted branches, or aborted rebases.
🇮🇳 Hinglish Definition
Reflog Git ke sabhi local pointer movements ka record rakhta hai. Galti se reset ya branch delete hone par reflog se exact SHA dhoondh kar recover kar sakte hain.
git reflog
git reflog show main
// Recover lost commit by creating a new branch at lost SHA
git switch -c recovery_branch abc1234
git show abc1234
17
Git Stash
git stash push -m "WIP login form"
git stash list
git stash show -p stash@{0}
git stash apply stash@{0}
git stash pop
git stash drop stash@{0}
git stash clear
18
Remote Repositories: fetch / pull / push
git remote -v
git remote show origin
git fetch origin
git fetch --prune origin
git pull
git pull --rebase
git pull --ff-only
git push -u origin feature/login
git push --force-with-lease
19
Tags and Releases
git tag
git tag -a v1.0.0 -m "Release version 1.0.0"
git show v1.0.0
git push origin v1.0.0
git push origin --tags
// Delete tag
git tag -d v1.0.0
git push origin --delete v1.0.0
20
Advanced Git Tools (Cherry-pick, Bisect, Worktree, Rerere)
| Command | Purpose | Typical Use Case |
|---|---|---|
| git cherry-pick | Apply specific commit to current branch | Backport hotfix from main to release branch |
| git bisect | Binary search commit history | Find exact commit that introduced a bug regression |
| git worktree | Multiple working directories attached to single repo | Work on feature and hotfix concurrently |
| git rerere | Reuse recorded resolution of conflicted merges | Repeated conflict resolution during rebases |
| git range-diff | Compare two commit series | Review interactive rebase changes |
// Cherry pick
git cherry-pick abc1234
// Bisect binary search
git bisect start
git bisect bad
git bisect good v1.0.0
// test project
git bisect good // or git bisect bad
git bisect reset
// Worktree
git worktree add ../hotfix hotfix/payment
git worktree list
git worktree remove ../hotfix
21
Submodules and Git LFS
// Add Git Submodule
git submodule add https://github.com/org/shared-lib.git libs/shared-lib
git submodule update --init --recursive
// Configure Git Large File Storage (LFS)
git lfs install
git lfs track "*.psd"
git add .gitattributes design.psd
git commit -m "chore: track design asset with LFS"
22 & 23
GitHub UI & Issues / Project Planning
🇬🇧 English Definition
GitHub Issues track bugs, tasks, and feature requests. GitHub Projects provides kanban boards, tables, and roadmaps to organize, prioritize, and monitor work progress.
🇮🇳 Hinglish Definition
Issue mein bug, task ya feature proposal record hota hai. Projects board aur roadmap ke through puri team ke tasks ko visually arrange karta hai.
📋 Typical Software Engineering Lifecycle
24
Pull Requests (PRs)
git switch -c feature/profile
// make changes & test
git add .
git commit -m "feat: add profile endpoint"
git push -u origin feature/profile
// Open GitHub PR: base: main <- compare: feature/profile
| PR Template Section | What to Write |
|---|---|
| Title | Clear summary of business outcome |
| Description | What changed and why |
| Testing | Exact commands executed & verification results |
| Risk / Impact | Potential risks reviewers should watch out for |
| Issue link | Fixes ID-123 (links PR to issue) |
25
Code Review Best Practices
🔍 Code Reviewer Checklist
- 1. Understand requirement & business scope before reading code.
- 2. Check logic correctness, edge cases, and error handling.
- 3. Check security, credential exposure, and SQL injection risks.
- 4. Verify unit tests and test coverage metrics.
- 5. Provide constructive, respectful, and actionable feedback.
26
Forks and Open-Source Workflow
🔄 Fork Workflow Flowchart
Original Repo
Upstream
Upstream
➔
Fork
Your Origin
Your Origin
➔
Feature Branch
Local Work
Local Work
➔
Pull Request
Proposed Changes
Proposed Changes
➔
Review + Merge
Integrated Code
Integrated Code
git clone https://github.com/YOU/project.git
git remote add upstream https://github.com/OWNER/project.git
git fetch upstream
git switch main
git merge upstream/main
git switch -c fix/bug
git push -u origin fix/bug
27
CODEOWNERS & Repository Templates
// .github/CODEOWNERS syntax example
/api/ @backend-team
/frontend/ @frontend-team
/docs/ @docs-team
/.github/workflows/ @devops-team
28
Branch Protection & Rulesets
| Control Gate | Purpose & Protection |
|---|---|
| Require pull request | Prevents uncontrolled direct commits to main |
| Required approvals | Enforces peer review gate (e.g. 1 or 2 approvals) |
| Required status checks | Enforces green CI build & test suite passage before merge |
| Code-owner review | Requires approval from CODEOWNERS for specific paths |
| Block force pushes | Prevents history rewriting on main branch |
| Block deletion | Protects critical production branches from accidental deletion |
29
GitHub Actions Architecture
🇬🇧 English Definition
GitHub Actions is an automated workflow engine integrated into GitHub. Workflows are declared in YAML under `.github/workflows/`. Workflows respond to events, execute jobs on runners, and run sequential steps.
🇮🇳 Hinglish Definition
GitHub Actions GitHub ka builtin automation engine hai. Event trigger hone par YAML workflow runner machine par jobs aur steps automatically run karta hai.
🔄 Actions Architecture Flowchart
Event
Push / PR / Cron
Push / PR / Cron
➔
Workflow YAML
.github/workflows/
.github/workflows/
➔
Jobs
Runners
Runners
➔
Steps
Actions / Commands
Actions / Commands
➔
Artifact / Deploy
Output
Output
30
Workflow YAML Syntax & Example
name: CI
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- run: echo "Run tests here"
31 & 32
Triggers, Jobs, Steps & Runners
on:
push:
branches: [main]
pull_request:
branches: [main]
workflow_dispatch:
schedule:
- cron: "0 2 * * 1"
release:
types: [published]
33
Contexts and Expressions
// Useful Context Expressions:
${{ github.ref }}
${{ github.sha }}
${{ github.actor }}
${{ github.repository }}
${{ github.event_name }}
${{ runner.os }}
${{ matrix.node }}
${{ secrets.DEPLOY_KEY }}
${{ vars.APP_ENV }}
${{ needs.build.outputs.version }}
34
Conditions, Matrix Builds & Step Outputs
jobs:
test:
strategy:
fail-fast: false
matrix:
node: ["20", "22"]
os: [ubuntu-latest, windows-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v5
with:
node-version: ${{ matrix.node }}
- run: npm ci
- run: npm test
35
Artifacts and Dependency Caching
// Upload Artifact
- name: Upload Build Artifact
uses: actions/upload-artifact@v4
with:
name: build-dist
path: dist/
// Download Artifact
- name: Download Build Artifact
uses: actions/download-artifact@v4
with:
name: build-dist
path: dist/
36
Service Containers (PostgreSQL / Redis Integration Tests)
jobs:
test:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16
env:
POSTGRES_PASSWORD: postgres
ports:
- 5432:5432
options: >-
--health-cmd "pg_isready -U postgres"
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
- uses: actions/checkout@v5
- run: pytest -q
37
Reusable Workflows
// .github/workflows/reusable-ci.yml
name: Reusable CI
on:
workflow_call:
inputs:
python:
required: true
type: string
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/setup-python@v6
with:
python-version: ${{ inputs.python }}
- run: pytest -q
// Caller Workflow:
jobs:
ci:
uses: OWNER/REPO/.github/workflows/reusable-ci.yml@v1
with:
python: "3.13"
38
Composite Actions
// .github/actions/setup-project/action.yml
name: Setup Project
description: Common project setup
inputs:
version:
required: true
runs:
using: composite
steps:
- uses: actions/setup-python@v6
with:
python-version: ${{ inputs.version }}
- shell: bash
run: pip install -r requirements.txt
39
Secrets, Variables and Least-Privilege Permissions
permissions:
contents: read
jobs:
build:
permissions:
contents: read
steps:
- uses: actions/checkout@v5
40
Environments and Deployments
jobs:
deploy:
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/checkout@v5
- run: ./scripts/deploy.sh
41
Continuous Integration (CI) Pipeline
🔄 CI Pipeline Flowchart
Checkout
Source code
Source code
➔
Install
Dependencies
Dependencies
➔
Lint / Type
Static checks
Static checks
➔
Unit Tests
Pytest/Jest
Pytest/Jest
➔
Security
Scans
Scans
42
Continuous Delivery / Deployment (CD) Pipeline
🔄 CD Pipeline Flowchart
Build Once
Artifact / Image
Artifact / Image
➔
Publish
Container Registry
Container Registry
➔
Deploy Staging
Validation
Validation
➔
Approve Gate
Manual Review
Manual Review
➔
Deploy Prod
Production
Production
43 & 44
GitHub Security & Dependabot
// .github/dependabot.yml configuration
version: 2
updates:
- package-ecosystem: "pip"
directory: "/"
schedule:
interval: "weekly"
- package-ecosystem: "npm"
directory: "/frontend"
schedule:
interval: "weekly"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
45 & 46
Packages & GitHub Releases
git switch main
git pull --ff-only
git tag -a v1.0.0 -m "Release 1.0.0"
git push origin v1.0.0
// Create release via GitHub CLI with auto notes
gh release create v1.0.0 --generate-notes
47
GitHub CLI (gh) Command Reference
gh auth login
gh repo clone OWNER/REPO
gh issue create
gh issue list
gh pr create
gh pr list
gh pr checkout 123
gh pr review 123 --approve
gh pr merge 123
gh run list
gh run watch
48 & 49
GitHub REST API & GraphQL Basics
// REST API Example via curl
curl -L -H "Accept: application/vnd.github+json" -H "Authorization: Bearer $GITHUB_TOKEN" -H "X-GitHub-Api-Version: 2022-11-28" https://api.github.com/repos/OWNER/REPO
// GraphQL Query Example
query {
repository(owner: "OWNER", name: "REPO") {
name
description
stargazerCount
}
}
50 & 51
Webhooks and Local Git Hooks
// .git/hooks/pre-commit executable shell script
// bin/sh
ruff check .
pytest -q
52
Git Internals & Object Model
🔄 Git Object Model Flowchart
Commit
Tree + Parent + Meta
Tree + Parent + Meta
➔
Tree
Names + Modes + Blobs
Names + Modes + Blobs
➔
Blob
Raw File Content
Raw File Content
➔
Refs
Branch / Tag Pointers
Branch / Tag Pointers
git rev-parse HEAD
git cat-file -t HEAD
git cat-file -p HEAD
git count-objects -v
git fsck --full
53 & 54
Monorepos, Dev Containers & GitHub Pages
// .devcontainer/devcontainer.json
{
"name": "Project Dev Environment",
"image": "mcr.microsoft.com/devcontainers/python:3.13",
"postCreateCommand": "pip install -r requirements.txt"
}
55
Troubleshooting Reference Guide
| Problem | First Checks | Likely Resolution Direction |
|---|---|---|
| Nothing to commit | git status / diff | No changes made or already committed |
| Push rejected | git fetch / log | Remote branch has newer history; fetch & integrate |
| Authentication failed | ssh -T / gh auth status | Expired token, wrong URL or missing SSH key |
| Merge conflict | git status / diff | Resolve unmerged conflict paths manually |
| Detached HEAD | git status | Switch back to branch or create new recovery branch |
| Lost commit | git reflog | Find lost SHA in reflog and recreate branch |
| Secret detected | Rotate credential first! | Rotate key, remove from code, remediate git history |
56
Real Development Workflow
🔄 Enterprise Development Workflow Flowchart
Task / Issue
Planning
Planning
➔
Feature Branch
Development
Development
➔
Commit + Push
Upload
Upload
➔
Pull Request
Review
Review
➔
CI + Review
Automated Gate
Automated Gate
➔
Merge & Deploy
Release
Release
57
10 Complete Practical Portfolio Projects
🚀 Practical Projects List
- 1. Portfolio Website — README + project code + issues + PR + Actions CI
- 2. Python API Pipeline — Tests + lint + matrix CI + artifact upload
- 3. Node Application — npm CI + build + release workflow
- 4. Docker Application — Build image + scan vulnerabilities + publish to GHCR
- 5. Database Integration — Actions service container (PostgreSQL) + integration tests
- 6. Release Pipeline — Tag ➔ build ➔ test ➔ GitHub Release
- 7. Open-Source Contribution — Fork ➔ branch ➔ PR ➔ review
- 8. DevSecOps Repo — Secret scanning + dependency scanning + protected main
- 9. Reusable CI Platform — Reusable workflow matrix used by multiple repos
- 10. Documentation Site — Markdown docs + GitHub Pages publishing workflow
58 & 59
150+ Interview Questions & Scenario-Based Answers
🎯 Key Scenario Answers
Scenario: Bad commit merged to main? Do not rewrite shared history. Assess impact, revert the bad commit (`git revert SHA`), run CI checks, communicate with team, then fix forward.
Scenario: Secret committed? Rotate and revoke credentials immediately! Investigate exposure, remove secret from current code, remediate Git history if required, and enable secret scanning push protection.
Scenario: Secret committed? Rotate and revoke credentials immediately! Investigate exposure, remove secret from current code, remediate Git history if required, and enable secret scanning push protection.
60
Master Command Cheat Sheet
// DAILY WORKFLOW
git status
git switch main
git pull --ff-only
git switch -c feature/name
git diff
git add .
git commit -m "feat: description"
git push -u origin feature/name
// UNDO & RECOVERY
git restore file
git restore --staged file
git revert SHA
git reset --soft HEAD~1
git reset --hard HEAD~1
git reflog
// GITHUB CLI
gh auth status
gh repo clone OWNER/REPO
gh issue list
gh pr create
gh pr checkout 123
gh pr review 123 --approve
61 & 62
30/60/90 Day Roadmap & Final Readiness Checklist
🇬🇧 90-Day Roadmap
Days 1–15: Git basics, commits, branches, merge, rebase & reflog.
Days 16–30: GitHub PRs, Code Review, CODEOWNERS & rulesets.
Days 31–45: Actions YAML workflows, matrix builds & caching.
Days 46–60: CD pipelines, environments, service containers.
Days 61–75: DevSecOps, secret scanning, Dependabot & GHCR.
Days 76–90: CLI, REST/GraphQL APIs, webhooks & monorepos.
Days 16–30: GitHub PRs, Code Review, CODEOWNERS & rulesets.
Days 31–45: Actions YAML workflows, matrix builds & caching.
Days 46–60: CD pipelines, environments, service containers.
Days 61–75: DevSecOps, secret scanning, Dependabot & GHCR.
Days 76–90: CLI, REST/GraphQL APIs, webhooks & monorepos.
🇮🇳 Golden Rule
Before executing a destructive Git command, know exactly which history it alters and how you will recover it using reflog or revert!