๐ฆ Git & GitHub Complete Guide
Your interactive journey to version control mastery
Introduction to Git
What is Git?
Git is a distributed version control system that tracks changes in your code over time. Think of it as a time machine for your code - you can see what changed, who changed it, and go back to any previous version whenever you want!
Why Should You Learn Git?
- Track Changes: Every modification to your code is recorded with a message explaining what and why
- Collaborate Efficiently: Multiple developers can work on the same project without stepping on each other's toes
- Backup & Safety: Your code is safely stored and you can always revert mistakes
- Experiment Freely: Try new features in separate branches without affecting the main code
- Professional Standard: Git is used by virtually every tech company and open-source project
Git vs GitHub
| Git | GitHub |
|---|---|
| Version control system (software) | Web-based hosting service for Git repositories |
| Runs locally on your computer | Cloud-based platform accessible anywhere |
| Command-line tool | Provides GUI, collaboration features, CI/CD |
| Free and open-source | Free for public repos, paid plans available |
How Git Works
Git uses a three-stage workflow:
- Working Directory: Where you edit files on your computer
- Staging Area: Where you prepare files before saving them
- Repository: Where Git permanently stores the snapshots of your project
Installation & Setup
Installing Git
Let's get Git installed on your machine. Choose your operating system:
๐ช Windows
Option 1: Download from official website
Visit: https://git-scm.com/download/win
Option 2: Use Windows Package Manager
winget install --id Git.Git -e --source winget๐ macOS
# Requires Homebrew package manager
๐ง Linux (Ubuntu/Debian)
Verify Installation
After installing, verify Git is working:
# Should output: git version 2.x.x
Initial Configuration
Configure Git with your identity. This information will be attached to every commit you make:
Optional Configuration
Set your default text editor (VS Code example):
Check Your Configuration
# View all Git settings
git config user.name# Check specific setting
--global flag applies settings to all repositories on your computer. You can override these per-repository by omitting the flag!
Git Basics
Creating Your First Repository
There are two ways to start with Git:
Method 1: Initialize a New Repository
Start tracking an existing project:
# Creates a .git folder to track changes
Method 2: Clone an Existing Repository
Download a project from GitHub:
# Clone into a specific folder name
The Git Workflow
Understanding the three-stage workflow is crucial:
- Working Directory โ Make changes to files
- Staging Area โ Select which changes to include
- Repository โ Permanently save the snapshot
Check Status
Always start by checking what's changed:
# Shows: modified files, staged changes, current branch
Stage Changes
Add files to the staging area:
# Stage a specific file
git add .# Stage all changes in current directory
git add *.js# Stage all JavaScript files
git add -A# Stage all changes including deletions
Commit Changes
Save your staged changes permanently:
# Stage and commit tracked files in one step
- Use present tense: "Add" not "Added"
- Be specific: "Fix login validation bug" not "Fix bug"
- Keep first line under 50 characters
- Explain what and why, not how
View History
# Full commit history
git log --oneline# Compact view
git log --graph --oneline --all# Visual branch graph
View Changes
# See unstaged changes
git diff --staged# See staged changes
git show commit-hash# See specific commit details
Undo Changes
# Discard changes in working directory
git restore --staged filename.txt# Unstage file (keep changes)
git reset HEAD~1# Undo last commit, keep changes
git reset --hard permanently deletes changes. Always make sure you don't need those changes before using it!
Branching & Merging
What Are Branches?
Branches are independent lines of development. Think of them as parallel universes for your code where you can experiment without affecting the main project!
Use branches for:
- Developing new features without breaking existing code
- Fixing bugs in isolation
- Experimenting with new ideas safely
- Collaborating with teammates on different tasks
- Maintaining multiple versions of your project
Viewing Branches
See all your branches and identify which one you're currently on:
# List local branches (* shows current)
git branch -a# List all branches (including remote)
git branch -v# Show last commit on each branch
git branch -r# List only remote branches
Creating Branches
Create new branches for your features or experiments:
# Create new branch (stay on current branch)
git checkout -b feature/user-auth# Create and switch in one command
git switch -c feature/user-auth# Modern way (Git 2.23+) - recommended
feature/feature-name- for new featuresfix/bug-description- for bug fixeshotfix/urgent-fix- for urgent production fixesrefactor/code-improvement- for refactoringexperiment/idea-name- for experiments
Switching Branches
Move between different branches:
# Classic way
git switch main# Modern way (recommended)
git switch -# Switch to previous branch (like cd -)
Renaming Branches
# Rename any branch
git branch -m new-name# Rename current branch
Merging Branches
Once your feature is complete and tested, merge it back into the main branch:
# Switch to the branch you want to merge INTO
git pull# Make sure main is up-to-date
git merge feature/user-auth# Merge feature branch into main
Types of Merges
1. Fast-Forward Merge
When no changes were made to the base branch, Git simply moves the pointer forward:
# Git will fast-forward if possible
2. No-Fast-Forward Merge
Create a merge commit even when fast-forward is possible (preserves branch history):
# Always creates a merge commit
3. Squash Merge
Combine all commits from the feature branch into one commit:
# Squash all commits into one
git commit -m "Add complete user authentication"# Commit the squashed changes
Handling Merge Conflicts
When Git can't automatically merge changes, you'll see conflict markers in your files:
Conflict markers in your file:
<<<<<<< HEAD
Your current changes (in main branch)
=======
Incoming changes (from feature branch)
>>>>>>> feature-branch
Steps to Resolve Conflicts:
- Identify conflicted files:
git status - Open conflicted files in your code editor
- Decide which changes to keep:
- Keep your changes (HEAD)
- Keep their changes (incoming)
- Keep both (combine manually)
- Write something completely new
- Remove conflict markers (
<<<<<<<,=======,>>>>>>>) - Stage resolved files:
git add filename - Complete the merge:
git commit
# View conflicted files
git status# After resolving conflicts manually
git add . git commit -m "Resolve merge conflicts"# Or abort the merge
git merge --abort# Cancel merge and return to previous state
- Pull from main frequently to stay updated
- Keep feature branches small and short-lived
- Communicate with team about file changes
- Use
git merge --no-commit --no-ffto preview merge before committing
Merge Tools
Use visual merge tools for complex conflicts:
# Opens configured merge tool (e.g., VS Code, Meld)
git config --global merge.tool vscode# Set VS Code as default merge tool
Deleting Branches
Clean up merged branches to keep your repository organized:
# Delete merged branch (safe)
git branch -D feature/user-auth# Force delete unmerged branch โ ๏ธ
git push origin --delete feature/user-auth# Delete remote branch
Viewing Merge History
# Visual branch history
git log --merges# Show only merge commits
git show-branch# Show branch relationships
Common Branching Workflow
# Step 1: Create and switch to feature branch
git checkout main git pull git checkout -b feature/payment-integration# Step 2: Make changes and commit
# ...write code...
git add . git commit -m "Add payment gateway integration"# Step 3: Push feature branch
git push -u origin feature/payment-integration# Step 4: After review, merge to main
git checkout main git pull git merge feature/payment-integration git push# Step 5: Cleanup
git branch -d feature/payment-integration git push origin --delete feature/payment-integration- Don't merge main into your feature branch multiple times (use rebase instead)
- Don't force-delete branches with
-Dunless you're sure - Don't forget to pull before merging
- Don't leave too many feature branches hanging around
Working with Remotes
What Are Remotes?
Remote repositories are versions of your project hosted on the internet or network. They enable collaboration by allowing multiple developers to work on the same project from different locations!
Viewing Remotes
Check which remote repositories are connected to your project:
# List all remotes (just names)
git remote -v# Show remote URLs (fetch and push)
git remote show origin# Detailed info about a specific remote
Adding a Remote
Connect your local repository to a remote server (like GitHub, GitLab, or Bitbucket):
# Add remote named 'origin' (standard convention)
git remote add upstream https://github.com/original/repo.git# Add upstream remote (for forked repos)
- origin - Your main remote (usually your GitHub repo)
- upstream - Original repo you forked from (for contributing to open source)
Cloning a Repository
Download a complete copy of a remote repository to your local machine:
# Clone into a folder named 'repo'
git clone https://github.com/username/repo.git my-project# Clone into custom folder name
git clone -b develop https://github.com/username/repo.git# Clone specific branch
git clone --depth 1 https://github.com/username/repo.git# Shallow clone (only latest commit, faster)
Fetching Changes
Fetch downloads changes from remote but doesn't merge them (safe to check what's new):
# Fetch all branches from origin
git fetch origin# Fetch from specific remote
git fetch origin main# Fetch specific branch
git fetch --all# Fetch from all remotes
git fetch --prune# Remove deleted remote branches
Pulling Changes
Pull = Fetch + Merge (downloads and automatically merges into current branch):
# Pull from tracking branch
git pull origin main# Pull from specific remote and branch
git pull --rebase# Pull and rebase instead of merge
git pull --no-commit# Pull but don't auto-commit merge
- git fetch - Safe, just downloads. You review then merge manually
- git pull - Convenient, downloads AND merges automatically
- Use
fetchwhen you want to be careful,pullwhen you trust the changes
Pushing Changes
Upload your local commits to the remote repository:
# Push to tracking branch
git push origin main# Push to specific remote and branch
git push -u origin feature-branch# Push and set upstream tracking
git push --all# Push all branches
git push --tags# Push all tags
git push -u origin branch-name sets up tracking so future git push and git pull commands know where to go automatically!
Force Pushing
# Force push (DANGEROUS - overwrites remote)
git push --force-with-lease# Safer - only if no one else pushed
Only use force push when:
- You're working on your own feature branch
- You've accidentally pushed sensitive data
- You need to fix commit history on your branch
- NEVER force push to main/master or shared branches!
Managing Remotes
Renaming a Remote
# Change remote name
Changing Remote URL
# Update remote URL (e.g., switching from HTTPS to SSH)
Removing a Remote
# Remove remote connection
Tracking Branches
Set up your local branch to track a remote branch:
# Show which remote branches are tracked
git branch --set-upstream-to=origin/main# Set tracking for current branch
git checkout --track origin/feature-branch# Create local branch tracking remote
Working with Multiple Remotes
You can have multiple remotes (useful for forks and collaboration):
# Fetch from upstream
git fetch upstream# Merge upstream changes into your branch
git merge upstream/main# Push to your fork
git push origin mainChecking Remote Status
# Detailed information about remote
git ls-remote# List all remote branches and tags
git branch -r# List all remote branches
Common Remote Workflow
# 1. Start your workday - get latest changes
git checkout main git pull origin main# 2. Create feature branch
git checkout -b feature/new-feature# 3. Make changes and commit
git add . git commit -m "Add new feature"# 4. Push to remote (first time)
git push -u origin feature/new-feature# 5. Continue working - subsequent pushes
git push# 6. Stay updated with main
git checkout main git pull git checkout feature/new-feature git merge mainTroubleshooting Common Issues
Rejected Push (Remote has changes you don't have)
Error: ! [rejected] main -> main (non-fast-forward)
# Solution: Pull first, then push
git pull origin main git push origin mainAuthentication Issues
# Switch from HTTPS to SSH for easier authentication
git remote set-url origin git@github.com:username/repo.git# Or use GitHub CLI for HTTPS
gh auth loginAccidentally Pushed to Wrong Branch
# Reset remote branch to previous state
git push origin HEAD^:branch-name --force- Always
git pullbefore starting work - Commit and push your work regularly (don't lose progress!)
- Use
git fetchto see what's new without merging - Never force push to shared branches
- Use descriptive branch names that match remote conventions
- Keep your local main/master in sync with remote
GitHub Essentials
What is GitHub?
GitHub is a web-based platform built on top of Git that provides hosting for Git repositories plus powerful collaboration features. Think of it as social media for developers where you can share code, collaborate on projects, and contribute to open source!
Git (version control) + Hub (central place where developers connect)
Creating a Repository on GitHub
Two ways to start:
Method 1: Create on GitHub First
1. Go to github.com โ Click "New repository"
2. Choose name, description, public/private
3. Initialize with README (optional)
4. Clone to your computer:
git clone https://github.com/username/repo-name.gitMethod 2: Push Existing Local Repo
1. Create empty repo on GitHub (no README)
2. In your local project:
git remote add origin https://github.com/username/repo-name.git git branch -M main git push -u origin mainPull Requests (PRs)
Pull Requests are GitHub's way of proposing changes. They're essential for team collaboration!
Creating a Pull Request
- Create a branch for your changes
- Make commits and push to GitHub
- Open PR on GitHub comparing your branch to main
- Request review from team members
- Address feedback with additional commits
- Merge when approved!
# Complete PR workflow
git checkout -b feature/add-login# Make your changes
git add . git commit -m "Add user login feature" git push -u origin feature/add-login# Then go to GitHub and click "Compare & pull request"
- Write clear PR title and description
- Keep PRs small and focused (easier to review)
- Link related issues (#123)
- Add screenshots for UI changes
- Request specific reviewers
- Be responsive to feedback
Code Review
Reviewing others' code is crucial for maintaining quality:
How to Review a PR
- Read the description - understand what's being changed
- Check the code - look for bugs, style issues, improvements
- Test locally - pull the branch and run it
- Leave comments - be constructive and specific
- Approve or request changes
# Test someone's PR locally
git fetch origin pull/123/head:pr-123 git checkout pr-123# Or use GitHub CLI
gh pr checkout 123Issues & Project Management
GitHub Issues are like a built-in task tracker for your project:
Creating Issues
- Bug reports - document problems with code
- Feature requests - suggest new functionality
- Questions - ask for help or clarification
- Tasks - track work items
Linking Issues & PRs
In commit messages or PR descriptions:
git commit -m "Fix login bug - closes #42"# When merged, issue #42 auto-closes!
Magic keywords that auto-close issues:
closes #123fixes #123resolves #123
Forking & Contributing
Fork repositories to contribute to open source projects:
Contributing to Open Source
# 1. Fork the repo on GitHub (click Fork button)
# 2. Clone YOUR fork
git clone https://github.com/YOUR-USERNAME/repo.git cd repo# 3. Add original repo as upstream
git remote add upstream https://github.com/ORIGINAL-OWNER/repo.git# 4. Create branch and make changes
git checkout -b fix-typo# Make your changes
git commit -m "Fix typo in documentation"# 5. Push to YOUR fork
git push origin fix-typo# 6. Open PR on GitHub from your fork to original repo
Keeping Fork in Sync
GitHub Actions (CI/CD)
Automate testing, building, and deployment with GitHub Actions:
Create .github/workflows/test.yml:
name: Run Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Run tests
run: npm test
Common use cases:
- Run tests on every push
- Deploy to production when merging to main
- Check code style and linting
- Build documentation automatically
- Send notifications to Slack/Discord
GitHub Pages
Host static websites directly from your repository for FREE!
1. Create a branch called "gh-pages" (or use main)
git checkout -b gh-pages git push origin gh-pages2. Go to Settings โ Pages โ Select branch
3. Your site will be at: username.github.io/repo-name
README.md Best Practices
Your README is the front page of your project. Make it great!
# Project Name Brief description of what your project does ## Features - Feature 1 - Feature 2 ## Installation ```bash npm install ``` ## Usage ```bash npm start ``` ## Contributing Pull requests welcome! ## License MIT
- Add badges (build status, version, license)
- Include screenshots/GIFs for visual projects
- Write clear installation instructions
- Provide usage examples
- Add contributing guidelines
- Specify license
GitHub CLI (gh)
Work with GitHub from your terminal:
# Create repo from terminal
gh pr create --title "Add feature" --body "Description"# Create PR from terminal
gh pr list# List open PRs
gh pr checkout 123# Checkout PR locally
gh issue create --title "Bug report"# Create issue from terminal
gh issue list# List issues
SSH Keys for GitHub
Set up SSH for password-free authentication:
# 1. Generate SSH key
ssh-keygen -t ed25519 -C "your-email@example.com"# 2. Start SSH agent
eval "$(ssh-agent -s)" ssh-add ~/.ssh/id_ed25519# 3. Copy public key
cat ~/.ssh/id_ed25519.pub# Copy output and add to GitHub โ Settings โ SSH Keys
# 4. Test connection
ssh -T git@github.comRepository Settings
Important settings to configure:
- Branch Protection - Require PR reviews before merging to main
- Required Checks - Tests must pass before merging
- Code Owners - Auto-assign reviewers for specific files
- Secrets - Store API keys securely for Actions
- Collaborators - Add team members with different permissions
GitHub Gists
Share code snippets quickly:
Go to gist.github.com
- Create public or secret gists
- Share code snippets, configs, notes
- Clone gists like regular repos
git clone https://gist.github.com/username/gist-id.git- Never commit API keys, passwords, or secrets
- Use
.gitignorefor sensitive files - Use GitHub Secrets for Actions
- Enable 2FA (Two-Factor Authentication)
- Review third-party app access regularly
- Use SSH keys instead of password authentication
- Press
.on any repo to open in VS Code web editor - Press
tto search files in a repo - Press
?to see all keyboard shortcuts - Use
@mentionsto tag people in issues/PRs - Create custom labels for better organization
- Use GitHub Projects for Kanban-style task management
- Star repos you find useful (builds your profile!)
Advanced Commands
Git Rebase
Rebase rewrites commit history by moving commits to a new base. It creates a cleaner, linear history compared to merge!
Merge: Preserves history, creates merge commits
Rebase: Rewrites history, creates linear timeline
Basic Rebase
# Moves feature-branch commits on top of main
Interactive Rebase
Powerful tool to edit, reorder, squash, or delete commits:
# Interactive rebase last 3 commits
git rebase -i main# Rebase all commits since main
Interactive rebase commands:
pick- Keep commit as isreword- Change commit messageedit- Pause to amend commitsquash- Combine with previous commitfixup- Like squash but discard messagedrop- Remove commit
Git Stash
Temporarily save uncommitted changes without committing them:
# Stash current changes
git stash save "WIP: working on feature"# Stash with descriptive message
git stash list# View all stashes
git stash pop# Apply and remove most recent stash
git stash apply# Apply stash but keep it in stash list
git stash apply stash@{2}# Apply specific stash
git stash drop stash@{0}# Delete specific stash
git stash clear# Delete all stashes
- Need to switch branches but not ready to commit
- Quick experiment without losing current work
- Pull latest changes but have uncommitted work
Git Cherry-Pick
Copy specific commits from one branch to another:
# Apply commit abc123 to current branch
git cherry-pick abc123 def456# Cherry-pick multiple commits
git cherry-pick abc123..def456# Cherry-pick range of commits
git cherry-pick --no-commit abc123# Apply changes without committing
Git Reflog
Reflog is Git's safety net - it records every HEAD movement. Use it to recover "lost" commits!
# Show history of HEAD movements
git reflog show feature-branch# Show reflog for specific branch
git reset --hard HEAD@{2}# Undo to specific reflog entry
git reflog to find the commit hash and git checkout or git reset to recover it!
Git Bisect
Binary search to find which commit introduced a bug:
# Mark current commit as bad
git bisect good abc123# Mark known good commit
# Git checks out middle commit - test it
git bisect good# If works - mark good
git bisect bad# If broken - mark bad
# Repeat until Git finds the culprit commit
git bisect reset# Return to original branch
Git Blame
See who last modified each line of a file (not for blaming, but understanding!):
# Show author and commit for each line
git blame -L 10,20 filename.js# Blame specific line range
git blame -e filename.js# Show email addresses
Git Clean
Remove untracked files and directories:
# Dry run - show what would be deleted
git clean -f# Force delete untracked files
git clean -fd# Delete untracked files and directories
git clean -fX# Delete only ignored files
git clean permanently deletes files! Always use -n first to preview what will be deleted.
Git Tags
Mark specific points in history (usually for releases):
# Create lightweight tag
git tag -a v1.0.0 -m "Release version 1.0.0"# Create annotated tag (recommended)
git tag# List all tags
git show v1.0.0# Show tag details
git push origin v1.0.0# Push specific tag
git push origin --tags# Push all tags
git tag -d v1.0.0# Delete local tag
git push origin --delete v1.0.0# Delete remote tag
Git Submodules
Include other Git repositories within your repository:
# Add submodule
git clone --recurse-submodules https://github.com/user/repo.git# Clone repo with submodules
git submodule update --init --recursive# Initialize and update submodules
git submodule update --remote# Update submodules to latest
Git Worktree
Work on multiple branches simultaneously without switching:
# Create worktree in different directory
git worktree list# List all worktrees
git worktree remove ../project-feature# Remove worktree
Git Hooks
Automate tasks at specific Git events:
Hooks are scripts in .git/hooks/
Common hooks:
- pre-commit: Run tests before commit
- pre-push: Run checks before push
- commit-msg: Validate commit message format
- post-merge: Run after merge (npm install, etc.)
Git Archive
Create a zip/tar archive of your repository:
# Create zip of main branch
git archive --format=tar --output=project.tar HEAD# Create tar of current commit
Git Grep
Search through your repository faster than regular grep:
# Search for "function" in tracked files
git grep -n "TODO"# Show line numbers
git grep --count "import"# Count matches per file
Amending Commits
# Modify last commit message
git commit --amend --no-edit# Add staged changes to last commit
git commit --amend --author="Name# Change author of last commit
Advanced Reset Options
# Undo commit, keep changes staged
git reset --mixed HEAD~1# Undo commit, keep changes unstaged (default)
git reset --hard HEAD~1# Undo commit, discard all changes โ ๏ธ
git reset --hard origin/main# Match local branch to remote exactly
Patch Files
Share changes without pushing:
# Create patch file
git apply changes.patch# Apply patch
git format-patch HEAD~3# Create patches for last 3 commits
git am *.patch# Apply all patch files
- Use
git rebase -ito clean up commits before pushing git reflogis your safety net - use it when things go wrong- Stash often when switching contexts quickly
- Use annotated tags for releases (
-aflag) - Practice advanced commands on test repos first!
- Set up Git aliases for commonly used advanced commands
Git Workflows
What Are Git Workflows?
Git workflows are standardized strategies for how teams organize branches, collaborate, and release code. Choosing the right workflow depends on your team size, project type, and deployment process.
1. Centralized Workflow
Simplest workflow - everyone works on main branch. Good for small teams or transitioning from SVN.
How It Works
# Get latest changes
# Make changes locally
git add . git commit -m "Add feature" git pull origin main# Pull again before pushing
git push origin mainPros: Simple, easy to learn, minimal overhead
Cons: No isolation, conflicts more common, risky for production
2. Feature Branch Workflow
Each feature gets its own branch. Most popular workflow for teams of any size!
How It Works
# 1. Start from main
git checkout main git pull origin main# 2. Create feature branch
git checkout -b feature/user-authentication# 3. Work and commit
git add . git commit -m "Implement login" git commit -m "Add password validation"# 4. Push feature branch
git push -u origin feature/user-authentication# 5. Create Pull Request on GitHub
# After approval, merge to main and delete branch
Pros: Isolated features, easy code review, safer than centralized
Cons: Merge conflicts if branches live too long
feature/- New featuresfix/orbugfix/- Bug fixeshotfix/- Urgent production fixesrefactor/- Code improvementsdocs/- Documentationtest/- Adding tests
3. Gitflow Workflow
Structured workflow with multiple long-lived branches. Great for scheduled releases and larger teams.
Branch Structure
- main - Production-ready code only
- develop - Integration branch for features
- feature/* - New features (branch from develop)
- release/* - Release preparation
- hotfix/* - Emergency production fixes
Complete Gitflow Example
# Feature Development
git checkout develop git pull origin develop git checkout -b feature/new-dashboard# Work on feature
git push -u origin feature/new-dashboard# Create PR to develop (not main!)
# Release Process
git checkout develop git checkout -b release/1.2.0# Final testing, bug fixes, version bumps
git checkout main git merge release/1.2.0 git tag v1.2.0 git checkout develop git merge release/1.2.0# Hotfix (production emergency)
git checkout main git checkout -b hotfix/security-patch# Fix critical bug
git checkout main git merge hotfix/security-patch git tag v1.2.1 git checkout develop git merge hotfix/security-patchPros: Very organized, clear release process, supports multiple versions
Cons: Complex for small teams, overhead with many branches
4. GitHub Flow
Simplified workflow perfect for continuous deployment. Used by GitHub themselves!
The Rules
- main branch is always deployable
- Create descriptive feature branches from main
- Push to remote regularly
- Open PR when ready for feedback
- Merge only after review and passing tests
- Deploy immediately after merging
# Make changes, commit, push
git push -u origin improve-search# Open PR โ Review โ Merge โ Deploy
Pros: Simple, fast deployment, works great with CI/CD
Cons: Requires good testing, not ideal for scheduled releases
5. Trunk-Based Development
Everyone commits to one branch (trunk or main) very frequently. Used by Google, Facebook!
Key Principles
- Commit to main multiple times per day
- Very short-lived feature branches (hours, not days)
- Feature flags for incomplete features
- Extensive automated testing
# Make small change
git add . git commit -m "Small incremental change" git pull --rebase origin main git push origin main# Repeat frequently throughout the day
Pros: Fast integration, fewer merge conflicts, continuous delivery
Cons: Requires mature testing, feature flags, team discipline
6. Forking Workflow
Each developer has their own server-side fork. Common in open source projects.
# 1. Fork repo on GitHub
git clone https://github.com/YOUR-USERNAME/project.git cd project git remote add upstream https://github.com/ORIGINAL-OWNER/project.git# 2. Work on feature
git checkout -b fix-bug# Make changes
git push origin fix-bug# 3. Create PR from your fork to original repo
# 4. Keep your fork synced
git fetch upstream git checkout main git merge upstream/main git push origin mainChoosing the Right Workflow
| Workflow | Best For |
|---|---|
| Centralized | Small teams, learning Git, simple projects |
| Feature Branch | Most teams, general purpose, balanced approach |
| Gitflow | Scheduled releases, multiple versions, large teams |
| GitHub Flow | Continuous deployment, web apps, fast iterations |
| Trunk-Based | Mature teams, strong testing, continuous delivery |
| Forking | Open source, external contributors |
Release Management Strategies
Semantic Versioning (SemVer)
Version format: MAJOR.MINOR.PATCH (e.g., 2.4.1)
- MAJOR - Breaking changes (1.0.0 โ 2.0.0)
- MINOR - New features, backward compatible (1.0.0 โ 1.1.0)
- PATCH - Bug fixes (1.0.0 โ 1.0.1)
Team Collaboration Best Practices
- main/master is sacred - Always keep it stable and deployable
- Pull before push - Always sync before pushing your work
- Small, frequent commits - Easier to review and revert
- Descriptive branch names - team/feature/add-payment-gateway
- Review before merge - Never merge your own PR without review
- Clean up branches - Delete after merging
- Communicate - Tell team about breaking changes
Commit Message Conventions
Consistent commit messages make history readable:
feat: Add user login functionality - Implement JWT authentication - Add login form validation - Create user session management Closes #123
Common prefixes:
feat:- New featurefix:- Bug fixdocs:- Documentationstyle:- Formatting, no code changerefactor:- Code restructuringtest:- Adding testschore:- Maintenance tasks
CI/CD Integration
Automate testing and deployment in your workflow:
Typical CI/CD pipeline:
1. Developer pushes to feature branch
2. CI runs tests automatically
3. Create PR when tests pass
4. Code review + approval
5. Merge triggers deployment to staging
6. Manual approval for production
7. Auto-deploy to production
- Start simple, don't over-engineer
- Document your workflow in README.md
- Use branch protection rules on main
- Set up status checks (tests must pass)
- Require PR reviews before merging
- Automate what you can (CI/CD, testing)
Troubleshooting
Common Problems & Solutions
Even experienced developers run into Git issues. Here's how to solve the most common problems!
1. "Detached HEAD" State
Problem: You're not on any branch, just at a specific commit.
Warning: HEAD is detached
# Solution 1: Create new branch from here
git checkout -b new-branch-name# Solution 2: Return to a branch
git checkout main2. Uncommitted Changes Blocking Checkout
Problem: Can't switch branches because of uncommitted changes.
error: Your local changes would be overwritten by checkout
# Solution 1: Stash changes
git stash git checkout other-branch git stash pop# Apply stashed changes on new branch
# Solution 2: Commit changes first
git add . git commit -m "WIP: Save progress" git checkout other-branch# Solution 3: Discard changes (โ ๏ธ CAREFUL!)
git checkout -- .3. Merge Conflicts
Problem: Git can't automatically merge changes.
CONFLICT (content): Merge conflict in file.js
# Step 1: See conflicted files
git status# Step 2: Edit files, remove conflict markers
Open file and choose which code to keep
# Step 3: Mark as resolved
git add file.js git commit -m "Resolve merge conflict"# Or abort the merge
git merge --abort4. Rejected Push (Non-Fast-Forward)
Problem: Remote has changes you don't have locally.
! [rejected] main -> main (non-fast-forward)
# Solution: Pull, then push
git pull origin main# Resolve any conflicts if they occur
git push origin main# Or use rebase for cleaner history
git pull --rebase origin main git push origin main5. Accidentally Committed to Wrong Branch
Problem: Made commits on main instead of a feature branch.
# Solution: Move commits to new branch
git branch feature-branch# Creates branch with current commits
git reset --hard HEAD~2# Remove last 2 commits from main
git checkout feature-branch# Switch to branch with your commits
6. Need to Undo Last Commit
Problem: Just committed but need to make changes.
# Keep changes, undo commit
git reset --soft HEAD~1# Changes stay staged
# Keep changes, unstage them
git reset HEAD~1# Changes become unstaged (default)
# Discard everything (โ ๏ธ DANGEROUS!)
git reset --hard HEAD~17. Accidentally Deleted Branch
Problem: Deleted a branch before merging it.
# Find the commit with reflog
git reflog# Look for the branch's last commit
# Recreate branch at that commit
git branch recovered-branch abc123# Replace abc123 with actual commit hash
8. Large File Causing Push Issues
Problem: File too large for GitHub (>100MB).
remote: error: File large-file.zip is 150MB; exceeds 100MB
# Solution 1: Remove from history
git filter-branch --tree-filter 'rm -f large-file.zip' HEAD# Solution 2: Use BFG Repo-Cleaner (faster)
bfg --delete-files large-file.zip# Solution 3: Use Git LFS for large files
git lfs install git lfs track "*.zip"9. Corrupted Repository
Problem: Git reports corruption or broken objects.
# Step 1: Verify repository
git fsck --full# Step 2: Try to recover
git gc --prune=now# Step 3: Last resort - reclone
cd .. git clone https://github.com/user/repo.git repo-backup# Copy uncommitted work from old repo
10. Authentication Failed
Problem: Can't push/pull due to authentication issues.
remote: Support for password authentication was removed
# Solution 1: Use Personal Access Token
Go to GitHub โ Settings โ Developer settings โ Personal access tokens
Use token as password when prompted
# Solution 2: Switch to SSH
git remote set-url origin git@github.com:user/repo.git# Solution 3: Use GitHub CLI
gh auth login11. Staged Wrong Files
Problem: Accidentally staged files you don't want to commit.
# Unstage specific file
git reset HEAD file.txt# Unstage all files
git reset HEAD .12. Need to Edit Old Commit Message
Problem: Typo in commit message from several commits ago.
# Last commit - simple
git commit --amend# Older commit - use interactive rebase
git rebase -i HEAD~5# Change 'pick' to 'reword' for the commit
13. Lost Work After Hard Reset
Problem: Accidentally did git reset --hard and lost changes.
# Check reflog for lost commits
git reflog# Reset to previous state
git reset --hard HEAD@{1}# Or use specific commit hash from reflog
14. Merge Creating Too Many Conflicts
Problem: Merge has dozens of conflicts, overwhelming to resolve.
# Abort and try different strategy
git merge --abort# Option 1: Use theirs/ours for specific files
git checkout --theirs file.txt# Accept their version
git checkout --ours file.txt# Keep your version
# Option 2: Try rebase instead
git rebase main# Conflicts appear one commit at a time
15. Pushed Secret/Password to GitHub
Problem: Accidentally committed API keys or passwords.
# Step 1: IMMEDIATELY rotate/invalidate the secret
Change password, regenerate API key, etc.
# Step 2: Remove from history
git filter-branch --force --index-filter \ 'git rm --cached --ignore-unmatch path/to/file' \ --prune-empty --tag-name-filter cat -- --all# Step 3: Force push
git push origin --force --allDiagnostic Commands
When you're stuck, these commands help diagnose issues:
# Current state overview
git log --oneline --graph --all# Visual commit history
git reflog# History of HEAD movements
git remote -v# Check remote connections
git branch -vv# Branch tracking status
git diff# See unstaged changes
git diff --staged# See staged changes
Prevention Tips
- Commit often - Small, frequent commits are easier to manage
- Pull before push - Always sync before pushing your work
- Use branches - Never work directly on main
- Check before committing - Run
git statusandgit diff - Use .gitignore - Prevent sensitive files from being tracked
- Test before merging - Make sure code works before merging to main
- Backup important work - Push to remote regularly
Emergency Commands
โ ๏ธ NUCLEAR OPTIONS - Use with extreme caution!
# Discard ALL local changes
git reset --hard HEAD# Match local to remote exactly
git reset --hard origin/main# Start fresh (keeps uncommitted files)
rm -rf .git git init git remote add origin URLBest Practices
Write Quality Code
Following Git best practices makes collaboration smoother and keeps your project maintainable!
1. Commit Message Guidelines
Good commit messages are crucial for understanding project history.
The Perfect Commit Message
# Format:
type(scope): Short summary (50 chars or less) Detailed explanation of what and why (not how). Wrap at 72 characters. - Bullet points are okay - Use imperative mood: "Add feature" not "Added feature" Fixes #123Commit Types
# New feature for users
fix: Resolve memory leak in image processor# Bug fix
docs: Update API documentation# Documentation only
style: Format code with prettier# Code style/formatting
refactor: Simplify database query logic# Code restructure, no functionality change
test: Add unit tests for payment module# Adding tests
chore: Update dependencies# Maintenance tasks
perf: Optimize image loading speed# Performance improvements
โ "Fixed stuff"
โ "WIP"
โ "Updated files"
โ "fix(auth): Resolve token expiration edge case"
โ "feat(ui): Add dark mode toggle to settings"
โ "refactor(api): Extract validation logic into middleware"
2. When to Commit
Commit frequency and size matter!
- Commit early, commit often - Small, logical units
- One logical change per commit - Don't mix refactoring with new features
- Commit working code - Tests should pass
- Commit before switching tasks - Clean context switching
# Good: Atomic commits
git add auth/login.js git commit -m "feat(auth): Add login form validation" git add auth/api.js git commit -m "feat(auth): Implement login API endpoint" git add tests/auth.test.js git commit -m "test(auth): Add login flow tests"# Bad: One huge commit
git add . git commit -m "Added login stuff"3. Branching Strategy
Consistent branch naming prevents confusion.
Branch Naming Convention
# New feature
git checkout -b fix/navbar-alignment# Bug fix
git checkout -b hotfix/security-patch# Urgent production fix
git checkout -b refactor/database-layer# Code refactoring
git checkout -b docs/api-reference# Documentation
git checkout -b test/payment-integration# Testing
Branch Lifecycle
# 1. Create from updated main
git checkout main git pull origin main git checkout -b feature/new-feature# 2. Work and commit regularly
git add . git commit -m "feat: Add feature implementation"# 3. Keep branch updated
git fetch origin git rebase origin/main# 4. Push and create PR
git push origin feature/new-feature# 5. After merge, clean up
git checkout main git pull origin main git branch -d feature/new-feature4. Never Commit These Files
Use .gitignore to prevent committing sensitive or generated files.
# .gitignore essentials
# Dependencies node_modules/ vendor/ venv/ # Environment & Secrets .env .env.local secrets.yaml *.pem *.key # Build outputs dist/ build/ *.min.js *.bundle.js # IDE & OS files .vscode/ .idea/ .DS_Store Thumbs.db # Logs & temp files *.log npm-debug.log* tmp/ temp/5. Pull Request Guidelines
Make your PRs easy to review and merge.
- โ Clear, descriptive title
- โ Detailed description explaining what and why
- โ Link related issues
- โ Include screenshots/GIFs for UI changes
- โ Keep PR focused (one feature/fix)
- โ Tests are passing
- โ No merge conflicts
- โ Self-review your code first
- โ Request specific reviewers
PR Description Template
6. Code Review Best Practices
Both authors and reviewers have responsibilities.
As a PR Author
- Keep PRs small (< 400 lines when possible)
- Respond to feedback promptly
- Be open to suggestions
- Explain your reasoning when pushing back
- Mark conversations as resolved
As a Reviewer
- Review within 24 hours
- Be specific with feedback
- Suggest improvements, don't just criticize
- Ask questions to understand
- Praise good code!
- Test the changes locally when needed
# Bad review comment:
"This is wrong"# Good review comment:
"Consider using Array.filter() here instead of a for loop. It's more readable and follows our functional programming style guide. Example: const active = users.filter(u => u.active);"7. Protect Your Main Branch
Never break production! Set up branch protection rules.
# GitHub Branch Protection Rules to Enable:
โ Require pull request reviews before merging โ Require status checks to pass before merging โ Require branches to be up to date before merging โ Require conversation resolution before merging โ Include administrators (enforce for everyone) โ ๏ธ Do not allow force pushes โ ๏ธ Do not allow deletions8. Keep History Clean
A clean Git history is easier to navigate and debug.
Before Merging to Main
# Clean up messy commits with interactive rebase
git rebase -i HEAD~5# Squash, reorder, or reword commits
# Common rebase actions:
pick abc123 feat: Add login form squash def456 fix typo# Combines def456 into abc123
reword ghi789 Add API endpoint# Edit commit message
drop jkl012 WIP commit# Remove commit entirely
Merge Strategies
# Option 1: Squash and merge (cleanest)
All feature branch commits become one commit on main
โ Best for: Small features, individual contributors# Option 2: Rebase and merge
Preserves individual commits, linear history
โ Best for: When commit history is valuable# Option 3: Merge commit
Preserves branch history with merge commit
โ Best for: Large features, team collaboration9. Documentation Standards
Your README and documentation are part of your codebase.
- Project Title & Description - What it does
- Installation - Step-by-step setup
- Usage - How to use it
- Contributing - How to contribute
- License - Legal information
- Contact - Where to get help
# Also document:
CONTRIBUTING.md # How to contribute CODE_OF_CONDUCT.md # Community guidelines CHANGELOG.md # Version history LICENSE # Legal license .github/ # GitHub templates PULL_REQUEST_TEMPLATE.md ISSUE_TEMPLATE/10. Security Practices
Keep your repository secure from day one.
- โ Use .gitignore from the start
- โ Scan commits for secrets before pushing
- โ Enable GitHub's secret scanning
- โ Use environment variables for config
- โ Keep dependencies updated
- โ Enable 2FA on GitHub account
- โ Use signed commits (optional but good)
- โ Review third-party actions/workflows
# Sign commits with GPG
git config --global user.signingkey YOUR_KEY_ID git config --global commit.gpgsign true git commit -S -m "feat: Signed commit"11. Team Collaboration
Make working together seamless.
- Agree on workflow - Everyone uses same strategy
- Document conventions - Write them down
- Use consistent formatting - Setup Prettier/ESLint
- Communicate in commits/PRs - Don't use Slack for code discussions
- Regular sync meetings - Prevent merge conflicts
- Share knowledge - Review each other's code
12. Performance & Efficiency
Keep your repository fast and manageable.
# Check repository size
du -sh .git# Clean up unnecessary files
git gc --aggressive --prune=now# Use Git LFS for large files
git lfs track "*.psd" git lfs track "*.mp4"# Shallow clone for CI/CD
git clone --depth 1 URL# Faster clones in pipelines
Common Anti-Patterns to Avoid
- โ Committing directly to main branch
- โ Force pushing to shared branches
- โ Huge commits with mixed changes
- โ Meaningless commit messages
- โ Committing broken code
- โ Not pulling before pushing
- โ Leaving dead code/commented code
- โ Not using branches for features
- โ Ignoring merge conflicts
- โ Rewriting public history
Quick Win Checklist
- โ Create a comprehensive .gitignore
- โ Write better commit messages
- โ Use branches for all changes
- โ Set up branch protection rules
- โ Pull before you push
- โ Review your own PRs first
- โ Keep PRs small and focused
- โ Document as you code
Quick Reference
Git Commands Cheat Sheet
Your go-to reference for all essential Git commands. Bookmark this page!
๐ Getting Started
# Set your name
git config --global user.email "email@example.com"# Set your email
git config --list# View all settings
git --version# Check Git version
git help <command># Get help for any command
๐ฆ Creating Repositories
# Initialize new repository
git init <directory># Create repo in specific directory
git clone <url># Clone remote repository
git clone <url> <directory># Clone into specific directory
git clone --depth 1 <url># Shallow clone (faster)
๐ Basic Commands
# Check repository status
git add <file># Stage specific file
git add .# Stage all changes
git add -p# Stage changes interactively
git commit -m "message"# Commit staged changes
git commit -am "message"# Stage and commit tracked files
git commit --amend# Modify last commit
git commit --amend --no-edit# Add to last commit, keep message
๐ Viewing History
# View commit history
git log --oneline# Compact history view
git log --graph --all# Visual branch history
git log -p# Show changes in each commit
git log --author="Name"# Filter by author
git log --since="2 weeks ago"# Time-based filter
git log --grep="keyword"# Search commit messages
git show <commit># Show specific commit details
git blame <file># See who changed each line
๐ Undoing Changes
# Discard changes in working directory
git restore --staged <file># Unstage file
git reset HEAD~1# Undo last commit, keep changes
git reset --soft HEAD~1# Undo commit, keep staged
git reset --hard HEAD~1# Undo commit, discard changes โ ๏ธ
git revert <commit># Create new commit that undoes changes
git clean -fd# Remove untracked files โ ๏ธ
๐ฟ Branching
# List all branches
git branch -a# List all branches (including remote)
git branch <branch-name># Create new branch
git branch -d <branch># Delete branch (safe)
git branch -D <branch># Force delete branch
git branch -m <old> <new># Rename branch
git checkout <branch># Switch to branch
git checkout -b <branch># Create and switch to branch
git switch <branch># Switch to branch (modern)
git switch -c <branch># Create and switch (modern)
๐ Merging & Rebasing
# Merge branch into current branch
git merge --no-ff <branch># Merge with merge commit
git merge --squash <branch># Merge and squash commits
git merge --abort# Cancel merge
git rebase <branch># Rebase current branch
git rebase -i HEAD~3# Interactive rebase last 3 commits
git rebase --continue# Continue after resolving conflicts
git rebase --abort# Cancel rebase
๐ Remote Repositories
# List remote connections
git remote add <name> <url># Add new remote
git remote remove <name># Remove remote
git remote rename <old> <new># Rename remote
git remote set-url origin <url># Change remote URL
git fetch# Download remote changes
git fetch --all# Fetch from all remotes
git fetch --prune# Remove deleted remote branches
git pull# Fetch and merge
git pull --rebase# Fetch and rebase
git push# Push commits to remote
git push -u origin <branch># Push and set upstream
git push --force# Force push โ ๏ธ Dangerous!
git push --force-with-lease# Safer force push
git push origin --delete <branch># Delete remote branch
๐ฆ Stashing
# Save changes temporarily
git stash save "message"# Stash with description
git stash list# List all stashes
git stash pop# Apply and remove latest stash
git stash apply# Apply stash without removing
git stash apply stash@{2}# Apply specific stash
git stash drop# Delete latest stash
git stash clear# Delete all stashes
git stash show# Show stash changes
๐ Comparing Changes
# Show unstaged changes
git diff --staged# Show staged changes
git diff <branch1> <branch2># Compare two branches
git diff <commit1> <commit2># Compare two commits
git diff HEAD~1 HEAD# Compare with previous commit
git diff --stat# Show diff statistics
git diff <file># Show changes in specific file
๐ท๏ธ Tags
# List all tags
git tag <tagname># Create lightweight tag
git tag -a v1.0 -m "Version 1.0"# Create annotated tag
git tag <tagname> <commit># Tag specific commit
git tag -d <tagname># Delete local tag
git push origin <tagname># Push tag to remote
git push origin --tags# Push all tags
git push origin --delete <tagname># Delete remote tag
git show <tagname># Show tag details
๐ Advanced Commands
# Apply specific commit to current branch
git reflog# Show history of HEAD movements
git reflog show <branch># Show reflog for specific branch
git bisect start# Start binary search for bug
git bisect bad# Mark current commit as bad
git bisect good <commit># Mark commit as good
git grep "pattern"# Search for pattern in files
git shortlog -sn# Count commits per author
git archive --format=zip HEAD > project.zip# Export repository as zip
๐ง Configuration
# Set default editor to VS Code
git config --global init.defaultBranch main# Set default branch name
git config --global pull.rebase true# Always rebase on pull
git config --global alias.st status# Create alias (git st)
git config --global alias.co checkout# Alias for checkout
git config --global alias.br branch# Alias for branch
git config --global alias.cm "commit -m"# Alias for commit
git config --global color.ui auto# Enable colored output
๐งน Maintenance
# Clean up unnecessary files
git gc --aggressive# More thorough cleanup
git fsck# Verify repository integrity
git prune# Remove unreachable objects
git count-objects -vH# Show repository size
๐ GitHub CLI (gh)
# Authenticate with GitHub
gh repo create# Create new repository
gh repo clone <repo># Clone repository
gh pr create# Create pull request
gh pr list# List pull requests
gh pr view# View PR details
gh pr checkout <number># Check out PR locally
gh issue create# Create new issue
gh issue list# List issues
gh workflow view# View GitHub Actions workflows
๐ Common Scenarios
Scenario 1: Undo Last Commit (Keep Changes)
# Undo commit, keep changes staged
Scenario 2: Change Last Commit Message
Scenario 3: Discard All Local Changes
Scenario 4: Create Branch from Remote
Scenario 5: Sync Fork with Upstream
Scenario 6: Squash Last 3 Commits
# Change 'pick' to 'squash' for commits to combine
Scenario 7: Find Commit That Introduced Bug
# Current commit is bad
git bisect good v1.0# v1.0 was good
# Test each commit, mark as good/bad
git bisect good/bad git bisect reset# When done
Scenario 8: Move Commits to New Branch
# Remove last 3 commits from current branch
git checkout new-branch# Commits are now on new-branch
โ ๏ธ Dangerous Commands (Use Carefully!)
git reset --hard- Discards all changesgit clean -fd- Removes untracked filesgit push --force- Overwrites remote historygit branch -D- Force deletes branchgit reflog expire- Removes reflog entries
๐ Useful Git Aliases
Add these to your ~/.gitconfig file:
๐ฏ Quick Tips
- Commit often - Small commits are easier to manage
- Pull before push - Avoid conflicts
- Use branches - Never work directly on main
- Write good messages - Your future self will thank you
- Check status - Always know what you're committing
- Use .gitignore - Don't commit unnecessary files
- Learn reflog - It's your safety net
๐ Congratulations!
You now have all the essential Git knowledge to work effectively with version control. Bookmark this page for quick reference, and remember: the best way to learn Git is by using it daily. Keep practicing, and you'll become a Git expert in no time!
Next Steps:
- Create your own projects and push them to GitHub
- Contribute to open-source projects
- Explore advanced topics like Git hooks and submodules
- Share your knowledge with others!