How it protects you:git branch saves your commit history, while git stash push -u && git stash apply safely snapshots uncommitted and untracked files into the stash list without clearing your working directory.
What are you trying to do?
Click a goal to jump directly to its complete, verified workflow:
Guided Essentials • Mental Models
The 60-Second Mental Model
How Git actually works: intuitive conceptual models before diving into commands.
Quick Concept: Repo = Time Machine • Commit = Save Point • Staging = Cart • 5-Step Safe Routine
The Repository ("Repo")
Project Folder + Time Machine
A repository is your project folder paired with an automatic ledger. It tracks your files and records a permanent, rewound history of every saved change.
The Commit
A Game Save Point
A commit is a permanent snapshot of your project at one moment. If something breaks tomorrow, you can safely reload your codebase back to this exact checkpoint.
The Staging Area (git add)
Your Shopping Cart
Before you buy items, you place them into a cart. git add picks which edited files enter the cart. git commit pays at the register to seal the checkpoint.
Remote & Pipelines
Cloud Storage & Configured Robot
GitHub is a cloud host for your repo. A Pipeline is a robot that runs automated tests and deploys, if your repository has a workflow file configured.
The Safe Daily Workflow Routine
1
Inspect Status
See which files were modified or untracked.
git status
2
Stage Intended Files
Add only the specific files you meant to touch.
git add src/app.js
3
Review Staged Diff
Verify line-by-line what will enter the commit.
git diff --staged
4
Seal Checkpoint
Record the snapshot with a meaningful note.
git commit -m "feat: login"
5
Push When Ready
Publish to your remote upstream.
git push
Core Architecture • Data Flow
The 4 Git Zones & Data Flow Lifecycle
Git separates files across 4 distinct physical zones. Click any zone card or simulation step to trace how code advances forward, what git status reports at each checkpoint, and how to safely reverse without data loss:
Trace Lifecycle:
Zone 1Working Directory
The Worktable (Disk Files)
Untracked / Modified
Your real files in your project directory. Changes are editable in your IDE, but NOT yet snapshot-protected by Git.
git add →
Zone 2Staging Area (Index)
The Shopping Cart (.git/index)
Changes to be committed
The staging index. A curated staging cart where you gather only the files ready to be photographed in your next save point.
git commit →
Zone 3Local Repository
The Vault / Save Points (HEAD)
Sealed Commit Objects
Your immutable cryptographic ledger in .git/objects. Permanent checkpoints sealed locally on this machine.
git push →
Zone 4Remote Cloud Host
Central Forge (GitHub • GitLab • Bitbucket)
Published Team History
The remote upstream repository. Where teammates pull your commits, review Pull Requests, and automated CI pipelines run.
Interactive Troubleshooter
The Undo & Recovery Decision Tree
Not sure which command to use? Select where your changes are located to get the exact, safe recovery command.
Live Terminal Analyzer: Paste Status or Error Output
100% Client-Side • Never Uploaded
Run git status, git status -sb, or copy any red error message from your terminal. Paste it below for an instant, safe diagnosis:
Try sample output:
Interactive Visual Map
🗺️ How Git & GitHub Actually Work (Visual Timeline)
Think of Git as an automatic scrapbook of save points. Each time you save, Git leaves a breadcrumb trail back to where you started. Click any button below to watch how save points, bookmarks (branches), and your current view (HEAD) move in real time:
Under the Hood: Actual .git/ FilesLive File System State
See exactly what 41-byte text files Git reads and writes inside the hidden .git/ database for this scenario:
.git/HEAD
ref: refs/heads/main
Points to active branch ref
.git/refs/heads/main
3a7f82b49e10d54c82b90198273645102938475a
40-char SHA-1 hash pointing to commit c3
Computer Science Deep Dive: The Real Git Data Model (DAG, SHA Hashes, and Refs)Expand Technical Theory
While real-world analogies (save points, breadcrumbs, bookmarks, camera lens) provide an intuitive daily mental model, under the hood Git is an elegant, mathematically rigorous Directed Acyclic Graph (DAG) built atop an immutable content-addressable object store. Here is the formal technical architecture:
1. Directed Acyclic Graph (DAG)
Git history is formally represented as a Directed Acyclic GraphG = (V, E):
Directed Edges (E): Pointers directed backwards from child commits to their parent(s). A commit points to its parent because the parent existed first; the parent cannot know its future children.
Acyclic Invariant: It is mathematically impossible for a commit to be its own ancestor, preventing infinite loops during graph traversal.
Topological Ordering: Git orders commits chronologically and topologically during operations like git log and git rev-list.
2. Content-Addressable Object Store
All data in .git/objects/ is addressed by a cryptographic checksum (SHA-1 / SHA-256):
Blob: Raw file data (binary or text). Filenames and permissions are not stored inside blobs.
Commit: Top-level object storing: the root Tree hash, zero or more Parent commit hashes, author/committer timestamps, and the commit message.
Annotated Tag: An immutable ref object pointing to a commit hash with GPG signature and tagger metadata.
3. References (Refs) & Symbolic Refs
Branches and HEAD are lightweight pointers, not folder copies:
Branch Ref: A 41-byte text file in .git/refs/heads/<branch-name> containing a single 40-character hexadecimal commit hash. When you commit, Git writes the commit object and updates this file.
HEAD (Symbolic Ref): The file .git/HEAD contains ref: refs/heads/main, delegating where the working tree is anchored. In detached HEAD state, .git/HEAD holds a raw commit hash instead of a branch path.
Remote-Tracking Refs: Read-only pointers in .git/refs/remotes/origin/ reflecting the last known commit on the remote server.
4. Best Common Ancestor (BCA) & 3-Way Merge
How Git calculates merges without manual guesswork:
Lowest Common Ancestor (LCA): When merging two branches (B1 and B2), Git traverses the DAG backwards to find their Best Common Ancestor commit A.
3-Way Diff Matrix: Git computes Δ1 = diff(A, B1) and Δ2 = diff(A, B2). Clean changes to disjoint lines are automatically combined. Changes to identical lines trigger conflict markers.
Merge Commit: The resulting snapshot has two parent pointers: Parent 1 (B1) and Parent 2 (B2).
Start a Repository from Scratch
Onboarding
Scope: Local → RemoteRisk: Safe
Guided ConceptTurns a regular folder into a tracked project with a time-machine ledger in .git/, then links it to GitHub.
When to use: You started a new project folder on your machine and want to begin tracking it with Git and connect it to GitHub.
Initialization Sequence
Customize:
# 1. Initialize local repository with default branch 'main'
git init -b main
# 2. Stage all initial files and make the first milestone
git add .
git commit -m "feat: initial project setup"
# 3. Link to your empty GitHub repository and push
git remote add origin https://github.com/username/repo.git
git push -u origin main
What happens: Creates a hidden .git database in your folder, snapshots your initial files, and links your local main branch to GitHub.
Verify result: Run git remote -v and git status to confirm clean tree and upstream tracking.
Related:git clone · .gitignore
Clone an Existing Project
Onboarding
Scope: Remote → LocalRisk: Safe
Guided ConceptDownloads an exact duplicate of the project and its entire history from GitHub onto your computer.
When to use: You want to download a team repository or open-source project from GitHub onto your computer and start working.
Clone & Inspect
Customize:
# 1. Download complete repository history into a new folder:
git clone https://github.com/username/repo.git
# 2. Enter directory and inspect status:
cd repo
git status
# 3. List all local and remote branches:
git branch -a
What happens: Downloads the full historical object graph, sets up origin remote tracking branches, and checks out the default branch.
Verify result: Run git branch -vv to see the active checked-out branch.
Related:git switch · git fetch
Precise Staging & Checkpoints
Daily Essential
Scope: Working Tree → IndexRisk: Safe
Guided Conceptgit add puts files into your shopping cart; git commit pays at the register to seal a permanent save point.
When to use: You edited several files and want to seal a clean milestone snapshot containing only the changes intended for this commit.
Status, Add & Diff
Customize:
# 1. Review status of modified files:
git status
# 2. Stage specific intended files:
git add src/app.js
# 3. Review the exact staged snapshot:
git diff --staged
# 4. Commit with a clear note:
git commit -m "feat: add user authentication"
What happens: Places file snapshots into the staging index, then seals them into an immutable cryptographic commit object.
Verify result: Run git status to confirm clean tree and git log -1 to inspect the new commit.
Caution on git add .: Stages all non-ignored files under the current folder. Prefer naming files or using git add -p to stage hunk-by-hunk.
Related:git diff · git restore --staged
Branches: Isolated Sandboxes
Branches
Scope: Local HistoryRisk: Safe
Guided ConceptCreates an isolated sandbox where you can code and test safely without risking the working production code on main.
When to use: Starting a new feature, bugfix, or experiment without risking the working production code on main.
Branch Navigation
Customize:
# 1. Create and switch to a new branch:
git switch -c feature/redesign
# 2. Work safely, edit files, and commit:
git add src/redesign.css
git commit -m "style: apply new color palette"
# 3. Return to main branch when ready:
git switch main
What happens: Creates a lightweight 41-byte pointer to your current commit and moves HEAD to track it.
Verify result: Run git branch --show-current to verify your active branch.
Task
Modern Standard (Git 2.23+)
Legacy Overloaded
Switch branch
git switch <name>Clean
git checkout <name>
Create & switch
git switch -c <name>Clear
git checkout -b <name>
Undoing Mistakes Safely
Undo & Recovery
Scope: Working Tree & IndexRisk: Destructive / Reversible
Guided Conceptrestore --staged takes items out of your shopping cart safely; restore throws away changes on disk permanently.
When to use: You made accidental edits or staged files too early and need to back out without losing unintended work.
Restore Commands
Customize:
# 1. Unstage a file (SAFE: keeps your local edits in file):
git restore --staged src/app.js
# 2. Discard uncommitted edits (PERMANENT: overwrites file):
git restore src/app.js
# 3. Undo a pushed commit safely with an inverse commit:
git revert a1b2c3d
What happens:restore --staged removes files from index without touching files on disk. restore copies the committed version over disk.
Verify result: Run git status to confirm file state.
Permanent Loss Warning:git restore <filename> permanently overwrites uncommitted working edits. Those unstaged edits are not saved anywhere in Git.
Related:git reset · git revert · git reflog
🔬 Deep Dive: The Three Trees & Reset MatrixCS Theory
Git does not just track files; it coordinates Three Trees of repository state:
HEAD: The commit snapshot checked out in your repository database.
Index / Staging (.git/index): A binary cache recording file paths, stat caches, and blob SHA hashes for the next commit.
Working Tree: The physical files and directories you edit directly on your operating system filesystem.
The git reset command alters how many of these three trees move:
Reset Flag
HEAD
Index (Cart)
Working Tree
Risk Level
git reset --soft
Moves
Untouched
Untouched
🟢 Safe
git reset --mixed(default)
Moves
Resets
Untouched
🟡 Reversible
git reset --hard
Moves
Resets
Overwritten
🔴 Destructive
Takeaway:git restore --staged copies from HEAD into Index (leaving Working Tree alone), while git restore copies from Index into Working Tree.
Working with Remotes (GitHub, GitLab, Bitbucket)
Cloud & Remotes
Scope: Remote & LocalRisk: Reversible
Guided Conceptgit pull downloads teammates' newest checkpoints; git push uploads your save points to the cloud host.
When to use: Sharing your commits with teammates on GitHub, GitLab, or Bitbucket, or downloading their latest updates before merging.
Fetch, Rebase & Remote URLs
Customize:
# 1. Download remote changes WITHOUT altering working files:
git fetch origin
# 2. Pull & integrate linearly into your branch:
git pull --rebase origin main
# 3. Upload your commits to remote:
git push origin feature/my-branch
# Remote URL conventions across hosts:
git remote add origin https://github.com/user/repo.git # GitHub
git remote add origin https://gitlab.com/user/repo.git # GitLab
git remote add origin https://bitbucket.org/user/repo.git # Bitbucket
What happens:fetch updates remote-tracking references (`origin/main`). pull --rebase replays your local commits on top of incoming work.
Verify result: Run git status to confirm your branch is up to date with origin/main.
Fetch vs. Pull:git fetch downloads remote objects and updates origin/<branch> tracking references without touching your local working files.
🌐 The Cloud Host Rosetta Stone (GitHub vs. GitLab vs. Bitbucket)Multi-Host
The Git command-line engine is identical across all hosts, but team review workflows and automation conventions differ:
Capability
GitHub
GitLab
Bitbucket
Code Review
Pull Request (PR)
Merge Request (MR)
Pull Request (PR)
Official CLI
gh pr create
glab mr create
bb / Atlassian CLI
Issue Links
#123 / GH-123
#123 / GL-123
Jira: PROJ-123 #resolve
Default Branch
main
main
main (legacy: master)
CI/CD Config
.github/workflows/*.yml
.gitlab-ci.yml
bitbucket-pipelines.yml
Takeaway: Once configured as an origin remote, standard Git commands behave identically regardless of which platform hosts the repository.
When to use: You ran into a remote platform rejection on GitHub, GitLab, or Bitbucket: a protected branch push rejection, invalid authentication or credentials, automated secret detection blocks, or fork divergence.
Pipelines & Automated CI/CD
Cloud & Remotes
Scope: Remote CloudRisk: Read-Only
When to use: Understanding how pushing code triggers cloud robots that test code, build assets, and deploy applications automatically across GitHub, GitLab, or Bitbucket.
GitHub Actions (.github/workflows/ci.yml)
# .github/workflows/ci.yml
name: CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run Tests
run: npm test
What happens: Without an explicit workflow file, cloud hosts act solely as code storage. Pushing only triggers automated jobs if a configuration file is detected in the repository root.
Verify result: Check the "Actions" (GitHub), "Pipelines" (GitLab), or "Pipelines" (Bitbucket) tab in your web browser to view live job logs.
When to use: You are halfway through coding when an urgent bugfix is requested. Shelve your uncommitted edits so your workspace is clean, then restore them later.
Stash Lifecycle
# 1. Stash changes (use -u to include newly created files):
git stash push -u -m "WIP: navigation refactor"
# 2. Your workspace is now clean. Switch branches or patch...
git switch hotfix
# 3. Return to branch and pop your shelved work:
git stash pop
What happens: Saves modified and untracked files into the stash stack and reverts your working tree to HEAD.
Verify result: Run git stash list to inspect saved stashes.
Untracked Files Caveat: Default git stash ignores new untracked files. Always pass -u if you created new files.
Merge Conflict Resolution
Branches
Scope: Working Tree & HistoryRisk: Reversible
When to use: Git halts a merge or rebase because two branches altered identical lines and requires you to pick the right code.
# 1. Edit file: delete the 3 marker lines and keep the right code
# 2. Mark conflict resolved:
git add src/config.js
# 3. Finalize merge (or abort if you need to rethink):
git merge --continue # Or 'git merge --abort'
What happens: Staging the cleaned file signals Git that the conflict is resolved. Finalizing creates the merge commit.
Verify result: Run git status to confirm all merge conflicts are cleared.
Interactive Rebase (Commit Polish)
Advanced / Pro
Scope: Local HistoryRisk: History Rewriting
When to use: Squashing WIP micro-commits into clean milestones before opening a Pull Request for your team.
Rebase Session
# Rebase the last 3 local commits:
git rebase -i HEAD~3
# In editor:
# pick = keep commit
# squash = combine into previous commit & merge message
# fixup = combine into previous commit & discard message
git rebase --continue
git rebase --abort # Safe escape hatch
What happens: Reconstructs a linear commit sequence with updated parent hashes.
Verify result: Run git log --oneline -n 5 to inspect the newly squashed history.
Golden Rule: Never rebase commits that have already been pushed to a shared public branch. Rewriting shared history breaks teammates' local branches.
🔬 Deep Dive: The Rebase Cherry-Pick PipelineCS Theory
Git cannot modify existing commits because commits in the DAG are cryptographically immutable. Under the hood, git rebase executes an automated patch pipeline:
1. LCA Discovery: Git traverses backwards to identify the Lowest Common Ancestor (A) between your branch and target base (B).
2. Patch Generation: Commits unique to your branch are serialized into temporary diff patches in .git/rebase-merge/.
3. HEAD Pointer Reset: Git resets HEAD to the target base commit (B).
4. Sequential Replay: Git applies each patch one-by-one (automated cherry-pick). Each applied patch creates a brand new commit object with a new parent hash, new committer timestamp, and a completely different SHA checksum.
Why shared branches break: Teammates' local DAGs still point to the old commit SHAs. Pushing rebased commits results in divergent histories and duplicate commits.
Detached HEAD Recovery
Advanced / Pro
Scope: HEAD PointerRisk: Reversible
When to use: You checked out a raw commit hash instead of a branch name, and need to safely save any test commits you made.
Diagnosis & Safe Exit
Customize:
# 1. Check if detached:
git status # Shows: "HEAD detached at a1b2c3d"
# Exit A: Discard experiments and return to safety:
git switch main
# Exit B: Preserve commits made while detached:
git switch -c recovery-branch
What happens: Creating a branch attaches a named pointer to your current detached commit so garbage collection will not prune it.
Verify result: Run git branch --show-current to verify you are back on a named branch.
Git Worktrees (Parallel Folders)
Advanced / Pro
Scope: Working Trees & BranchesRisk: Safe
When to use: Checking out two different branches simultaneously into separate directories on your computer without re-cloning.
Worktree Management
# 1. Check out hotfix branch into sibling folder:
git worktree add ../project-hotfix hotfix-branch
# 2. List all active directory locations:
git worktree list
# 3. Clean up folder when finished:
git worktree remove ../project-hotfix
What happens: Links multiple working directories to the same underlying .git repository database.
Verify result: Run git worktree list to verify registered directory paths.
Reflog Recovery (Lost Work)
Advanced / Pro
Scope: Local Reflog LedgerRisk: Reversible
When to use: You accidentally ran git reset --hard, deleted a branch with unmerged work, or lost a commit and thought it was gone forever.
Reflog Rescue Recipe
# 1. View chronological action ledger:
git reflog -n 15
# 2. Locate the commit hash before the mistake (e.g. HEAD@{2})
# 3. Create a rescue branch attached to that commit:
git switch -c rescue-branch HEAD@{2}
What happens: Git stores all HEAD reference movements locally for 30-90 days before garbage collection. Creating a branch resurrects the orphaned commit into active history.
Verify result: Run git log -1 rescue-branch to confirm your lost code is restored.
Related:git reset · git branch
🔬 Deep Dive: Object Reachability & Garbage CollectionCS Theory
Git almost never deletes your commits immediately. Even after git reset --hard or deleting a branch:
Unreachable Objects: The commit objects remain in .git/objects/. They are merely disconnected from named branch refs (dangling in the DAG).
Append-Only Reflogs: Files in .git/logs/HEAD and .git/logs/refs/heads/ log every SHA hash that references have pointed to locally.
Garbage Collection (git gc): Unreachable objects are only purged when git gc runs and an object exceeds both gc.reflogExpire (default: 90 days) and gc.pruneExpire (default: 14 days).
Takeaway: As long as you know the commit hash from git reflog, creating a new branch resurrects orphaned work into the active DAG with zero data loss.
Regression Hunting (bisect & blame)
Advanced / Pro
Scope: Local HistoryRisk: Safe / Read-Only
When to use: A bug appeared and you need to pinpoint the exact commit out of hundreds that introduced the regression, or see who authored specific lines.
Bisect Binary Search
# 1. Start binary search:
git bisect start
git bisect bad # Current version is broken
git bisect good v1.2.0 # Known good previous release
# 2. Test intermediate commits checked out by Git:
git bisect good # (or 'git bisect bad')
# 3. Finish and return to active branch:
git bisect reset
# Inspect line-by-line author timestamps:
git blame -L 20,45 src/app.js
What happens: Performs a binary search across commit history in logarithmic steps (log2N), isolating the faulty commit in minutes.
Verify result: Git outputs: [hash] is the first bad commit with author and commit message.
When to use: Marking an official production release, milestone, or version number (e.g. v1.0.0) in your Git history.
Annotated Tag Workflow
# 1. Create an annotated release tag:
git tag -a v1.0.0 -m "Release v1.0.0: Initial public launch"
# 2. Push tag to GitHub (tags are not pushed by default!):
git push origin v1.0.0
# Or push all local tags at once:
git push origin --tags
# List all tags sorted by version:
git tag -l -n 1
What happens: Creates an annotated Git tag object containing author, timestamp, and release notes permanently referencing the current commit.
Verify result: Run git describe --tags to verify the active release version.
When to use: Updating a pull request branch after rebasing or squashing local commits, without the danger of destroying teammates' pushed work.
Safe PR Force-Push
# Safely push rebased branch to remote pull request:
git push --force-with-lease origin feature/auth
# NEVER use raw 'git push --force' on shared repositories!
What happens: Git verifies if the remote branch has received commits from teammates since your last fetch. If someone else pushed work, Git refuses the push instead of blindly overwriting it.
Verify result: Git responds with [forced update] only if your local ref was synchronized with remote.
Related:git rebase -i · git fetch origin
Port Isolated Commits (cherry-pick)
Branch Maintenance
Scope: Commit PluckingRisk: Reversible
When to use: Applying a specific bugfix commit from one branch (e.g. main) into a separate maintenance or release branch without merging the whole branch.
Cherry-Pick Recipe
# 1. Switch to target branch (e.g. maintenance branch):
git switch release/v1.0
# 2. Pluck specific bugfix commit by hash:
git cherry-pick 7a1b2c3
# If conflict occurs:
# git cherry-pick --continue
# Or cancel and return to safety:
# git cherry-pick --abort
What happens: Re-applies the exact code diff from the specified commit hash and records a brand new commit on the currently active branch.
Verify result: Run git log -1 --stat to confirm the bugfix commit was applied.