Introduction
Distributed Version Control Systems (DVCS) allow multiple developers to work on the same project simultaneously while maintaining a complete history of changes. Unlike centralized systems, every developer has a full copy of the project history, enabling offline work and reducing single points of failure. Git is the most popular DVCS, powering platforms like GitHub, GitLab, and Bitbucket.
Why DVCS Matters:
- Complete project history on every machine
- Offline capabilities
- Superior branching and merging
- Enhanced collaboration workflows
- Better backup and redundancy
Core Concepts & Principles
Repository Structure
- Working Directory: Your local files and folders
- Staging Area (Index): Prepared changes ready to commit
- Local Repository: Your complete project history
- Remote Repository: Shared repository (GitHub, GitLab, etc.)
Key Principles
- Snapshots, Not Differences: Git stores complete snapshots of your project
- Integrity: Everything is checksummed with SHA-1 hashes
- Three States: Modified, Staged, Committed
- Branching: Lightweight, fast branch creation and switching
- Distributed: No central authority required
Essential Git Configuration
Initial Setup
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
git config --global init.defaultBranch main
git config --global core.editor "code --wait"
Useful Configuration
git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.unstage 'reset HEAD --'
Basic Git Commands by Category
Repository Operations
Command | Description | Example |
---|---|---|
git init | Initialize new repository | git init my-project |
git clone | Clone remote repository | git clone https://github.com/user/repo.git |
git status | Check repository status | git status |
git log | View commit history | git log --oneline --graph |
File Operations
Command | Description | Example |
---|---|---|
git add | Stage changes | git add file.txt or git add . |
git commit | Commit staged changes | git commit -m "Add new feature" |
git rm | Remove files | git rm file.txt |
git mv | Move/rename files | git mv old.txt new.txt |
git restore | Restore files | git restore file.txt |
Branch Operations
Command | Description | Example |
---|---|---|
git branch | List/create branches | git branch feature-xyz |
git checkout | Switch branches | git checkout main |
git switch | Switch branches (new) | git switch feature-xyz |
git merge | Merge branches | git merge feature-xyz |
git rebase | Rebase branches | git rebase main |
Remote Operations
Command | Description | Example |
---|---|---|
git remote | Manage remotes | git remote add origin <url> |
git fetch | Download remote changes | git fetch origin |
git pull | Fetch and merge | git pull origin main |
git push | Upload changes | git push origin main |
Git Workflow Methodologies
1. Centralized Workflow
Best for: Small teams, simple projects
- Single main branch
- All changes committed directly to main
- Linear history
git clone <repository>
# Make changes
git add .
git commit -m "Description"
git push origin main
2. Feature Branch Workflow
Best for: Medium teams, feature-based development
- Create branches for each feature
- Merge back to main when complete
git checkout -b feature/user-auth
# Develop feature
git add .
git commit -m "Implement user authentication"
git push origin feature/user-auth
# Create pull request
git checkout main
git merge feature/user-auth
3. Gitflow Workflow
Best for: Release-based projects, larger teams
- main: Production-ready code
- develop: Integration branch
- feature/*: New features
- release/*: Release preparation
- hotfix/*: Emergency fixes
4. GitHub Flow
Best for: Continuous deployment, web applications
- Create branch from main
- Add commits
- Open pull request
- Deploy and test
- Merge to main
Advanced Git Commands
History and Inspection
Command | Description | Example |
---|---|---|
git diff | Show changes | git diff HEAD~1 |
git show | Show commit details | git show abc1234 |
git blame | Show line authors | git blame file.txt |
git bisect | Binary search for bugs | git bisect start |
Undoing Changes
Command | Description | Example |
---|---|---|
git reset | Reset to previous state | git reset --soft HEAD~1 |
git revert | Create reverse commit | git revert abc1234 |
git reflog | Show reference log | git reflog |
git cherry-pick | Apply specific commit | git cherry-pick abc1234 |
Stashing
Command | Description | Example |
---|---|---|
git stash | Save temporary changes | git stash push -m "WIP" |
git stash pop | Apply and remove stash | git stash pop |
git stash list | List all stashes | git stash list |
git stash drop | Delete stash | git stash drop stash@{0} |
Branching Strategies Comparison
Strategy | Pros | Cons | Best For |
---|---|---|---|
Single Branch | Simple, easy to understand | No isolation, conflicts common | Solo projects, prototypes |
Feature Branches | Isolated development, clean history | Merge conflicts, overhead | Most team projects |
Gitflow | Structured, handles releases well | Complex, slower development | Enterprise, scheduled releases |
GitHub Flow | Simple, continuous deployment | Less control over releases | Web apps, SaaS products |
Common Challenges and Solutions
Merge Conflicts
Problem: Conflicting changes in same file lines Solution:
git status # See conflicted files
# Edit files to resolve conflicts
git add resolved-file.txt
git commit -m "Resolve merge conflict"
Accidental Commits
Problem: Committed wrong files or messages Solutions:
# Undo last commit, keep changes
git reset --soft HEAD~1
# Undo last commit, discard changes
git reset --hard HEAD~1
# Amend commit message
git commit --amend -m "Corrected message"
Large Files
Problem: Repository becomes bloated Solutions:
- Use
.gitignore
for build artifacts - Implement Git LFS for large files
- Use
git clean -fd
to remove untracked files
Detached HEAD
Problem: Working in detached HEAD state Solution:
# Create branch from current state
git checkout -b new-branch-name
# Or return to main branch
git checkout main
Best Practices and Tips
Commit Guidelines
- Write clear commit messages: Use imperative mood (“Add feature” not “Added feature”)
- Make atomic commits: One logical change per commit
- Commit frequently: Small, focused commits are easier to track
- Use conventional commits:
feat:
,fix:
,docs:
,refactor:
Branch Management
- Use descriptive branch names:
feature/user-authentication
,bugfix/login-error
- Keep branches short-lived: Merge frequently to avoid conflicts
- Delete merged branches: Clean up after merging
- Protect main branch: Use branch protection rules
Repository Organization
- Maintain
.gitignore
: Exclude build files, IDE settings, secrets - Use README.md: Document project setup and usage
- Tag releases: Use semantic versioning (
v1.2.3
) - Regular maintenance: Clean up old branches and tags
Collaboration Tips
- Pull before push: Always sync with remote before pushing
- Use pull requests: Enable code review and discussion
- Write descriptive PR descriptions: Explain what and why
- Review code thoroughly: Check for bugs, style, and logic
Git Aliases for Productivity
# Status and log shortcuts
git config --global alias.s status
git config --global alias.l "log --oneline --graph --decorate"
git config --global alias.ll "log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset'"
# Branch shortcuts
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.sw switch
# Useful combinations
git config --global alias.unstage 'reset HEAD --'
git config --global alias.last 'log -1 HEAD'
git config --global alias.visual '!gitk'
Troubleshooting Quick Reference
Problem | Command | Description |
---|---|---|
See what changed | git diff | Compare working directory to staging |
Undo unstaged changes | git restore file.txt | Discard changes in working directory |
Unstage files | git restore --staged file.txt | Remove from staging area |
See commit history | git log --oneline | Condensed commit history |
Find when bug introduced | git bisect start | Binary search through commits |
Recover deleted branch | git reflog | Find branch reference |
Clean untracked files | git clean -fd | Remove untracked files and directories |
Advanced Workflows
Rebase vs Merge Decision Matrix
Scenario | Use Rebase | Use Merge |
---|---|---|
Feature branch to main | ✓ | ✗ |
Updating feature branch | ✓ | ✗ |
Shared branch | ✗ | ✓ |
Public commits | ✗ | ✓ |
Preserving context | ✗ | ✓ |
Clean linear history | ✓ | ✗ |
Git Hooks Examples
# Pre-commit hook (run tests)
#!/bin/sh
npm test
if [ $? -ne 0 ]; then
echo "Tests must pass before commit!"
exit 1
fi
# Pre-push hook (prevent force push to main)
#!/bin/sh
protected_branch='main'
current_branch=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,')
if [ $protected_branch = $current_branch ]; then
echo "Direct push to main branch is not allowed"
exit 1
fi
Resources for Further Learning
Official Documentation
- Git Official Documentation: https://git-scm.com/doc
- Pro Git Book: https://git-scm.com/book (Free online)
- Git Reference: https://git-scm.com/docs
Interactive Learning
- Learn Git Branching: https://learngitbranching.js.org/
- GitHub Skills: https://skills.github.com/
- Atlassian Git Tutorials: https://www.atlassian.com/git/tutorials
Advanced Topics
- Git Internals: Understanding how Git works under the hood
- Git Workflows: Comparing different team collaboration strategies
- Git Hooks: Automating tasks with Git hooks
- Git LFS: Managing large files in Git repositories
Tools and GUIs
- GitKraken: Cross-platform Git GUI
- SourceTree: Free Git GUI by Atlassian
- VS Code Git Integration: Built-in Git support
- GitHub Desktop: Simple Git GUI for GitHub
Command Line Enhancements
- Oh My Zsh Git Plugin: Enhanced Git aliases and prompts
- Git Flow Extensions: Tools for Gitflow workflow
- Tig: Text-based Git repository browser