Learning Objectives
- Understand and resolve merge conflicts effectively
- Handle detached HEAD states and orphaned commits
- Recover from lost or overwritten changes
- Resolve remote repository conflicts
Common Git Problems
Even experienced developers encounter Git issues. Understanding common problems and their solutions helps you work more confidently with Git.
Issue Categories
- •Merge conflicts
- •Branch problems
- •Lost work
- •Remote conflicts
Prevention Tips
- •Regular commits and pushes
- •Clear branch strategy
- •Good communication
- •Proper Git configuration
Handling Merge Conflicts
Merge conflicts occur when Git cannot automatically resolve differences between two commits. Understanding how to resolve them is crucial for any Git user.
<<<<<<< HEADconsole.log("Hello from main branch");=======console.log("Hello from feature branch");>>>>>>> feature/greeting
Resolution Steps
- 1.
Identify Conflicts
$ git status - 2.
Review Changes
$ git diff - 3.
Resolve and Mark
# After editing files$ git add .$ git commit -m "Resolve merge conflict"
Dealing with Detached HEAD
A detached HEAD state occurs when you checkout a specific commit instead of a branch. While not necessarily problematic, it requires careful handling to avoid losing work.
# Check if in detached HEAD state$ git status # To save your work in detached HEAD$ git branch temp-branch # Switch to the new branch$ git checkout temp-branch # Merge changes into main branch$ git checkout main$ git merge temp-branch # Clean up$ git branch -d temp-branch
Prevention Tips
- •Use tags for historic commits
- •Create branches before exploring
- •Use git log to navigate history
Recovering Lost Changes
Git keeps track of all changes for a period of time, even if they're not in any branch. Understanding recovery tools helps you avoid losing work.
Using Reflog
# View recent actions$ git reflog # Recover lost commit$ git checkout -b recovery HEAD@{2} # Restore deleted branch$ git checkout -b restored HEAD@{4}
Using FSMonitor
# Enable FSMonitor$ git config core.fsmonitor true # Find lost file$ git fsmonitor--daemon status # Restore file$ git checkout HEAD~1 -- path/to/file
Remote Repository Conflicts
Remote conflicts can occur when pushing or pulling changes. Understanding how to handle these situations prevents workflow disruptions.
# Failed push scenario$ git push origin main! [rejected] main -> main (fetch first) # Resolution steps$ git fetch origin$ git merge origin/main # Or use pull with rebase$ git pull --rebase origin main # Force push (use carefully!)$ git push --force-with-lease origin main
Best Practices
- •Fetch before push
- •Use pull --rebase for cleaner history
- •Avoid force push on shared branches
What's Next?
Now that you understand common Git issues, let's explore the tools and techniques for recovering from more complex problems. In the next lesson, you'll learn about:
- Advanced recovery tools
- Git maintenance commands
- Data recovery techniques
- Advanced repository maintenance