Nanfeng

Notes on software development, code, and curious ideas

Safely Making a Local Git Branch Match Its Remote

Sometimes a local branch must exactly match its remote-tracking branch. This discards local tracked changes and commits that are not present on the remote, so inspect and preserve anything valuable first.

Inspect the target

1
2
3
4
5
git status --short --branch
git remote -v
git branch --show-current
git fetch origin
git log --oneline --left-right HEAD...origin/main

Replace main with the intended branch. git fetch updates remote-tracking references but does not modify working files.

Preserve a recovery point

If local commits or edits might be useful, create a backup branch and optionally stash uncommitted work:

1
2
git branch backup-before-sync
git stash push --include-untracked -m "before remote sync"

Then make the checked-out branch match the verified remote target:

1
git reset --hard origin/main

This overwrites tracked working-tree and index changes. Untracked files remain; review them with git status and remove only explicit paths if they are genuinely unwanted. Do not run a broad git clean without first previewing its exact targets.

Recovery

The backup branch retains the previous commit. A stash retains saved working-tree changes, and git reflog may locate recent commits even without a backup. These are safety nets, not a substitute for checking the repository and branch before a destructive reset.

For ordinary collaboration, prefer merging, rebasing, or resolving conflicts. A hard reset is appropriate only when discarding the local state is the actual goal.

+