Git Best Practices Every Developer Should Know

January 15, 2024 (2y ago)

Git Best Practices Every Developer Should Know

Git is the backbone of modern software development. Here are the best practices that will level up your Git game.

Commit Messages

Use Conventional Commits

Follow a structured format for clear history:

feat: add user authentication
fix: resolve login redirect issue
docs: update API documentation
style: format code with prettier
refactor: simplify user service logic
test: add unit tests for auth module
chore: update dependencies

Write Meaningful Messages

# Bad
git commit -m "fix bug"
 
# Good
git commit -m "fix: prevent duplicate form submission on slow networks"

Branching Strategy

Git Flow Branches

# Main branches
main        # Production-ready code
develop     # Integration branch
 
# Supporting branches
feature/*   # New features
bugfix/*    # Bug fixes
hotfix/*    # Urgent production fixes
release/*   # Release preparation

Create Feature Branch

git checkout -b feature/user-authentication

Keep Branches Updated

git checkout develop
git pull origin develop
git checkout feature/my-feature
git rebase develop

Essential Commands

Interactive Rebase

Clean up commits before merging:

git rebase -i HEAD~3

Stash Changes

# Save changes temporarily
git stash save "work in progress"
 
# List stashes
git stash list
 
# Apply and remove stash
git stash pop
 
# Apply without removing
git stash apply stash@{0}

Undo Last Commit

# Keep changes staged
git reset --soft HEAD~1
 
# Keep changes unstaged
git reset HEAD~1
 
# Discard changes completely
git reset --hard HEAD~1

Cherry Pick

git cherry-pick <commit-hash>

Collaboration Tips

Pull with Rebase

git pull --rebase origin main

Squash Commits Before Merge

git rebase -i HEAD~5
# Change 'pick' to 'squash' for commits to combine

View Commit History

# Pretty log
git log --oneline --graph --all
 
# Search commits
git log --grep="authentication"

Git Aliases

Add to ~/.gitconfig:

[alias]
  co = checkout
  br = branch
  ci = commit
  st = status
  lg = log --oneline --graph --all
  last = log -1 HEAD
  unstage = reset HEAD --

.gitignore Best Practices

# Dependencies
node_modules/
vendor/
 
# Environment
.env
.env.local
.env*.local
 
# Build outputs
dist/
build/
.next/
 
# IDE
.vscode/
.idea/
 
# OS
.DS_Store
Thumbs.db
 
# Logs
*.log
npm-debug.log*

Master these practices to write cleaner history, collaborate effectively, and avoid common Git pitfalls.