Mastering Tricky Git Situations: Solutions to Common Challenges

Mastering Tricky Git Situations: Solutions to Common Challenges

Here’s an outline of the article:

1. Recovering a Deleted Branch

Situation: Accidentally deleted a branch locally or remotely.

Solution:

Find the branch commit:

git reflog

Restore the branch:

git checkout -b <branch_name> <commit_hash>

2. Undoing a Commit without Losing Changes

Situation: Committed changes prematurely.

Solution:

git reset --soft HEAD~1

3. Resolving Merge Conflicts

Situation: Merge conflicts during git merge.

Solution:

Open conflicting files, resolve manually.

Add resolved files:

git add <file>

Complete the merge:

git commit

4. Pushing a Commit to the Wrong Branch

Situation: Pushed a commit to the incorrect branch.

Solution:

git checkout <correct_branch>

git cherry-pick <commit_hash>

git checkout <wrong_branch>

git reset --hard HEAD~1

5. Working with Detached HEAD State

Situation: Made changes in detached HEAD state.

Solution:

git switch -c new_branch_name

6. Rewriting Commit History

Situation: Need to modify commit messages or squash commits.

Solution:

git rebase -i HEAD~<n>

7. Undoing a Pushed Commit

Situation: Pushed a wrong commit to the remote.

Solution:

git revert <commit_hash>

8. Accidentally Committed Sensitive Data

Situation: Added credentials or secrets to a commit.

Solution:

Remove from history:

git filter-repo --path <file> --invert-paths

Push the rewritten history:

git push --force

9. Fixing a Corrupted Repository

Situation: Repository shows errors like “fatal: not a git repository.”

Solution:

Re-initialize Git:

git init

Pull fresh changes from remote:

git fetch --all

git reset --hard origin/<branch>

10. Resolving "Diverged Branch" Issues

Situation: Local and remote branches have diverged.

Solution:

git pull --rebase

git push --force-with-lease

These examples cover common scenarios that developers face when working with Git. Would you like me to expand any section?

Did you find this article valuable?

Support saurabhnative by becoming a sponsor. Any amount is appreciated!