Skip to content

Git Fundamentals

Git Fundamentals

Git is a distributed version control system: every clone contains the full project history (commits, branches, tags). This design enables offline work, fast local operations, safer experimentation, and powerful collaboration patterns.


1. Mental Model

Think in snapshots and pointers: | Concept | What It Represents | Physical Storage | |---------|--------------------|------------------| | Commit | Snapshot + metadata (parents, author, message) | .git/objects | | Branch | Movable pointer to a commit | .git/refs/heads/* | | HEAD | Current checkout reference | .git/HEAD | | Staging (Index) | Proposed next snapshot | .git/index | | Remote | Another repo reference (URL + refs) | .git/config |

Diagram of core flow:

flowchart LR
    A[Working Directory] -->|git add| B[Staging Area]
    B -->|git commit| C[Local Repository]
    C -->|git push| D[Remote Repository]
    D -->|git fetch/pull| C


2. Core Lifecycle (Feature Branch)

sequenceDiagram
    participant Dev as Developer
    participant Repo as Local Repo
    participant Remote as Origin
    Dev->>Repo: git switch -c feat/login
    Dev->>Repo: edit code
    Dev->>Repo: git add .
    Dev->>Repo: git commit -m "feat(auth): add login form"
    Dev->>Remote: git push -u origin feat/login
    Remote-->>Dev: PR created & reviewed
    Dev->>Remote: Merge (squash)
    Remote-->>Repo: git pull origin main

3. Essential Commands (Curated)

Goal Command Note
Initialize repo git init Creates .git directory
Clone remote git clone <url> Full history locally
Check status git status Working vs staged changes
Stage file git add <file> Promote to index
Commit staged git commit -m "msg" Snapshot index
New branch git switch -c feat/x Pointer from current HEAD
Change branch git switch main Update HEAD
View graph git log --oneline --graph --decorate --all Visual topology
Diff unstaged git diff Working vs index
Diff staged git diff --cached Index vs HEAD
Push branch git push -u origin feat/x Set upstream tracking
Update & merge git pull Fetch + merge
Update (rebase) git pull --rebase Cleaner history
Stash WIP git stash push -m wip Temp hide changes
Restore stash git stash pop Reapply + drop

4. Branching & Integrations (Summary)

Integration Style Command(s) Produces When
Fast-forward git merge feat/x (no divergence) Linear advance Small, up-to-date branch
Merge commit git merge feat/x (diverged) Merge commit (2 parents) Preserve parallel dev history
Squash merge UI or --squash + manual commit Single commit Keep main concise
Rebase git rebase main Rewritten commits Clean local branch before PR

See: branching-strategies.md for deeper discussion & policies.


5. HEAD, Detached HEAD, and Safety

HEAD points at a branch ref normally. Detached HEAD means you checked out a commit (not a branch). Commits made there can be lost if not referenced. Recovering lost work (if reflog not expired):

git reflog
git switch -c restore-work <commit-id>


6. Staging vs Direct Commit

You can skip staging with git commit -am "msg" (only modifies tracked files). Prefer explicit git add when learning to maintain clarity.


7. Undo & Recovery Cheat Table

Goal Command Caution
Undo last commit (keep changes) git reset --soft HEAD~1 Rewrites history
Drop last commit (discard changes) git reset --hard HEAD~1 Permanent loss if not pushed
Amend message / add forgotten file git commit --amend Avoid after push
Revert a commit (safe undo) git revert <hash> Adds new inverse commit
Restore deleted file git checkout <hash> -- path Use git restore in newer versions
Discard unstaged changes git restore <file> Irreversible locally
Discard staged changes git restore --staged <file> Keeps working copy

8. Merge vs Rebase (Visual)

graph LR
    A0((A)) --> A1((B)) --> A2((C))
    A1 --> F1((F1))
    A2 --> F2((F2))
    subgraph Merge Path
        A2 --> M((Merge))
        F2 --> M
    end
    subgraph Rebase Path
        A2 --> R1((F1')) --> R2((F2'))
    end
Merge preserves branch topology; rebase rewrites commits for linear story.

Rule of Thumb: Rebase local, unpublished feature branches; never rebase public shared branches.


9. Collaboration Etiquette

Practice Why
Pull (or fetch+rebase) before pushing Reduce conflicts
Small, focused commits Easier reviews, bisects
Descriptive commit messages (Conventional Commits) Automation & clarity
Avoid large binary files in repo Bloats history, slows clones
Use draft PR early Feedback before polishing

10. Performance Tips

Issue Symptom Mitigation
Large history clone slow Long initial download Use shallow clone: git clone --depth 50
Accidental secrets commit Exposed credentials Rotate secret; use git filter-repo to purge
Merge conflict churn Frequent conflicts Pull/rebase more often; smaller branches
Hard to find bug intro Many commits Use git bisect to binary search history

git bisect example:

git bisect start
git bisect bad HEAD
git bisect good <known-good-hash>
# Run tests -> mark good/bad until isolated
git bisect reset


11. Troubleshooting Scenarios

Scenario Command / Approach Explanation
Pushed wrong branch name git push origin :wrong && git push -u origin right Delete remote misnamed branch
Need file from old commit git checkout <hash> -- path/to/file Extract file without full revert
Accidentally committed secrets Rotate & remove via history rewrite Use scanning tools (trufflehog, gitleaks)
Diverged histories git pull --rebase origin main Replay local commits atop updated remote
Stuck rebase git rebase --abort Return to pre-rebase state

12. Minimal Daily Workflow (Cheat Sheet)

git switch main
git pull --rebase
git switch -c feat/login-form
# edit files
git add src/login.js
git commit -m "feat(auth): add login form"
git push -u origin feat/login-form
# open PR, address review feedback
git switch main && git pull --rebase
git branch -d feat/login-form

13. Checklist

  • Global Git name/email configured (git config --global user.name)
  • SSH key or token auth set up
  • Branch naming convention documented
  • Commit messages follow convention
  • Pull or rebase before push habit formed
  • Conflicts resolved with clear commit messages
  • No large binaries/credentials added

14. Further Resources