Home > OS >  How to sync local and remote repositories
How to sync local and remote repositories

Time:03-14

After a merged pull request (PR) on GitHub with 3 commits on the remote repository (origin), I performed a pull to update my local repository (main). Somehow the things went wrong, with the standard CI tests failing locally. I reset the local repository to ignore the 3 commits using

git reset --hard SHA

and regained the local status before the PR. Then, to check the commits individually, I performed the pull explicitly using

 git fetch origin
 git merge SHA-commit1
 git merge SHA-commit2
 git merge SHA-commit3

and arrived to the same (functional) status as on remote, with all CI tests OK.

Just for completeness: I have on the remote side another PR proposal, which is not yet merged (containing some errors).

Although, my local and remote repositories are now practically the same, the command

 git status origin

shows

On branch main
Your branch and 'origin/main' have diverged,
and have 3 and 2 different commits each, respectively.
  (use "git pull" to merge the remote branch into yours)

I wonder if there is an easy way to sync the two repositories (I am afraid the suggested git pull would have the same effect as before). Thanks in advance for any hint.

CodePudding user response:

The short answer

To discard any local changes and put your sandbox in the same state as origin, run:

git fetch
git reset --hard origin/main

(Assumption: you're working on branch main.)

Further comments

When you're not sure what's going on in your sandbox, you should use a tool to visually look at your commit graph. There are many graphical ones, but here's a simple command line one:

git log --all --oneline --graph --decorate

The key is to make it display the graph, the branch names (local and remote), and all the branches.

This command will show you exactly how the remote and local have diverged. And then, you can decide if you want to keep your local changes and use a merge or rebase, or discard your local changes and use a hard reset.

Another note: I'm really not a fan of git pull. In fact, I never use it. It's the same as git fetch followed by git merge, but blindly does the merge whether it's a good idea or not. I prefer to 1) fetch, 2) run that git log command showing the graph, and then 3) decide if I actually want to merge or rebase or reset or whatnot.

  • Related