Skip to main content

🌳 Git

A time machine for your code

The Save Game Analogy

Playing a video game:

Game ActionGit Equivalent
Save before boss fightCommit (checkpoint to return to)
Multiple save slotsBranches (try different approaches)
Share save with friendPush (share your progress)
Load friend's savePull (get their changes)

Git is save points for your code. Every commit is a snapshot you can return to. Branches let you experiment safely.


Why Git Matters

Without Version Control

my_project/
  project.py
  project_v2.py
  project_v2_final.py
  project_v2_final_ACTUAL.py
  project_v2_final_ACTUAL_fixed.py
         ↓
  Which is the real version?
  What changed between them?

With Git

my_project/
  project.py  ← Usually the current version

Git maintains full history:
  commit 5: "Fixed login bug"
  commit 4: "Added user profiles"
  commit 3: "Implemented auth"
  commit 2: "Added database"
  commit 1: "Initial project"

Travel back in time anytime!

Core Concepts

Repository (Repo)

A project tracked by Git. Contains:

ComponentWhat It Holds
FilesYour actual code
HistoryEvery change ever made
BranchesParallel versions

Repos can be local (your machine) or remote (GitHub/GitLab).

Commits

A snapshot of your code at a point in time.

Each commit has:
┌─────────────────────────────────────┐
│ Hash: a7c3e8f (unique ID)          │
│ Author: Alice                       │
│ Date: YYYY-MM-DD HH:MM             │
│ Message: "Add user authentication" │
└─────────────────────────────────────┘

Commits are your "save points" - return to any of them.

Branches

Parallel versions of your code.

main:    A ─── B ─── C ─── D
                \
feature:         E ─── F

Main continues normally.
Feature branch experiments independently.
When ready, merge feature into main.

The Git Workflow

The Four Areas

Working       Staging       Local        Remote
Directory     Area          Repo         Repo
    │            │            │            │
    │  git add   │            │            │
    │───────────→│            │            │
    │            │ git commit │            │
    │            │───────────→│            │
    │            │            │  git push  │
    │            │            │───────────→│
    │            │            │            │
    │           git pull (remote → local)  │
    │←─────────────────────────────────────│

Daily Workflow

StepCommandWhat Happens
1. Edit(in editor)Make changes to files
2. Stagegit add .Mark changes for commit
3. Commitgit commit -m "..."Save snapshot locally
4. Pushgit pushShare with team

Branching Strategy

Why Branch?

Working on MainWorking on Branch
Break something = team impactedBreak something = more isolated
Risk deploying bad codeSafely experiment
Hard to review changesEasy to review before merge

Common Branch Names

main (or master)   → Production-ready code
develop            → Development version
feature/login      → New feature
bugfix/header      → Bug fix
hotfix/security    → Urgent production fix

Branch Lifecycle

1. Create branch from main
2. Work on branch (multiple commits)
3. Push branch to remote
4. Open Pull Request
5. Team reviews code
6. Merge to main
7. Delete branch (cleanup)

Merging

Fast-Forward Merge

When main hasn't changed since you branched:

Before:  main: A ─── B
                     \
         feature:     C ─── D

After:   main: A ─── B ─── C ─── D

Main just "moves forward" to include your commits.

Three-Way Merge

When main has new commits too:

Before:  main:    A ─── B ─── E
                        \
         feature:        C ─── D

After:   main:    A ─── B ─── E ─── M (merge commit)
                        \         /
         feature:        C ─── D

Creates a merge commit combining both.

Merge Conflicts

When both branches edited the same lines:

Git says: "I can't automatically merge these!"

You'll typically:
1. Open the conflicted file
2. Choose which changes to keep
3. Mark as resolved
4. Complete the merge

Conflicts are normal and usually need human judgment.

Common Commands Reference

Getting Started

CommandPurpose
git initCreate new repo
git clone <url>Copy remote repo
git statusSee what's changed

Daily Work

CommandPurpose
git add .Stage all changes
git commit -m "message"Save snapshot
git pushUpload to remote
git pullDownload from remote

Branching

CommandPurpose
git checkout -b <name>Create & switch
git checkout <name>Switch branch
git merge <branch>Merge into current

Undoing

CommandPurpose
git checkout -- <file>Discard changes
git reset --soft HEAD~1Undo last commit
git diffSee changes

Pull Requests

A Pull Request (PR) is a proposal to merge your branch.

What a PR Contains

SectionPurpose
Title & DescriptionExplain what changed
DiffSee exactly what code changed
CommentsDiscussion with team
CI StatusDid automated tests pass?
ApprovalsTeam sign-off

PR Workflow

1. Push your branch
2. Open PR on GitHub/GitLab
3. Teammates review code
4. Address feedback (more commits)
5. Get approval
6. Merge to main
7. Delete branch

Common Practices

Good Commit Messages

❌ Bad✅ Good
"Fixed stuff""Fix login redirect on expired session"
"WIP""Add user profile page with avatar upload"
"asdf""Update payment API to v2 format"

Good messages explain what and why, not just how.

Small, Focused Commits

❌ Bad✅ Good
One commit with 50 filesMultiple focused commits
"Added everything""Add user model", "Add user API", "Add user UI"

Small commits are easier to review, test, and revert.

Keep Main Clean

Main should typically work (deploy-ready).
Feature branches for experiments.
PRs for code review before merge.

Common Mistakes

1. Committing Secrets

Avoid committing passwords, API keys, or certificates.

Solution:
- Use .gitignore for secret files
- Use environment variables
- If committed, rotate the secret immediately

2. Giant Commits

1000 lines changed = very hard to review. Break into smaller, logical commits.

3. Force Pushing Shared Branches

git push --force on shared branches can destroy others' work. In general, avoid force pushing shared branches.

If force pushing is needed, coordinate with your team and consider a safer option like --force-with-lease.


FAQ

Q: Git vs GitHub?

Git: the version control tool (runs locally) GitHub: a hosting service for Git repos (remote)

Git is the tool. GitHub, GitLab, Bitbucket are services that host repos.

Q: How often should I commit?

Frequently! Each logical change. Ask: "If this breaks, can I revert just this?"

Q: Merge vs Rebase?

Merge: creates merge commit, preserves full history Rebase: rewrites history for a linear timeline

Teams have different preferences. Follow your team's convention.

Q: What's .gitignore?

A file listing what Git should ignore:

  • node_modules/ (dependencies)
  • .env (secrets)
  • *.log (generated files)

Summary

Git tracks changes to your code, enabling collaboration, lower-risk experimentation, and time travel through your project's history.

Key Takeaways:

  • Commits are save points you can return to
  • Branches let you experiment without breaking main
  • Pull requests enable code review before merging
  • Often pull (or fetch + rebase/merge) before pushing to reduce conflicts
  • Write clear, descriptive commit messages
  • Avoid committing secrets (use .gitignore and secret managers)
  • Small, focused commits are easier to manage

Git is the foundation of modern software development!

Related Concepts

Leave a Comment

Comments (0)

Be the first to comment on this concept.

Comments are approved automatically.