Git Troubleshooting and Maintenance

Git Troubleshooting and Maintenance

Practical recipes to fix common Git problems, keep repositories healthy, and build a reliable backup & recovery strategy.

Introduction

Git is powerful, but with power comes complexity. This post collects clear, repeatable steps for: resolving detached HEAD states, handling merge conflicts, recovering broken commits, cleaning and optimizing repositories, and backing up & recovering Git data. Keep these commands handy — they’ll save time and panic.

Resolving Common Git Issues

1. Fixing a detached HEAD state

A detached HEAD happens when HEAD points directly to a commit instead of a branch (for example after checking out a commit hash). You can either attach those changes to a branch or create a new branch from the detached state.

  1. Create a branch from the detached HEAD:
    git checkout -b my-work
  2. Move an existing branch to point to the detached commit:
    git branch -f target-branch HEAD
    git checkout target-branch
  3. Recover uncommitted work:
    git fsck --lost-found
    git reflog

2. Resolving merge conflicts

Merge conflicts occur when changes in two branches affect the same lines. Git will pause the merge so you can manually resolve differences.

git status               # See conflicting files
# Open each file, look for <<<<<<< and >>>>>>> markers
git add <file>            # Mark resolved files
git commit                # Finalize the merge

3. Fixing broken commits

Broken commits might have wrong messages or missing changes. Use amend for the latest commit, or rebase for older commits.

  • Amend last commit:
    git commit --amend
  • Rebase interactively:
    git rebase -i HEAD~3

Maintaining Repository Health

1. Cleaning up branches

git branch --merged       # See merged branches
git branch -d branch-name # Delete local branch
git push origin --delete branch-name

2. Optimizing repository size

git gc --aggressive --prune=now

Also consider removing large unused files and use git filter-repo or BFG Repo-Cleaner to rewrite history.

3. Refactoring history

For cleaner history, squash related commits during rebase:

git rebase -i HEAD~5

Backup and Disaster Recovery

1. Cloning as a backup

git clone --mirror <repo-url> /backup/location

2. Using remote hosting

Hosting platforms like GitHub, GitLab, and Bitbucket provide redundancy. Push your local changes regularly to keep backups current.

3. Recovering from failures

  • Use reflog to find lost commits:
    git reflog
  • Restore from bare or mirror backup:
    git clone /backup/location

By keeping your repository organized, resolving issues quickly, and maintaining a solid backup plan, you ensure that Git remains a dependable tool rather than a source of stress.

Post a Comment

0 Comments