I like git worktree, but keep getting into situations where the local working directory is not the same as the remote branch, even though git pull says "Already up to date".
Here's a little MRE I did:
- Created a remote repo in the GitLab web interface.
- Cloned it using
git clone --bare <url>
- Added the
main
branch locally usinggit worktree add main
- Added a new branch using
git worktree add new-branch
,cd
ed into it and did agit push
. - Using the GitLab web interface, I added a file
main-branch-change-1
directly in themain
branch, then rebasednew-branch
on top of the newmain
, then added a second filefeature-branch-change-1
innew-branch
. git pull
on the localnew-branch
says "Already up to date", while commit hash andgit log
clearly shows the local is not up to date. The filemain-branch-change-1
is present, but notfeature-branch-change-1
.git fetch --all
in the bare repo followed bygit pull
innew-branch
changes nothing.git pull
in themain
branch followed bygit pull
innew-branch
changes nothing.
What do I have to do to sync these changes?
Some screenshots:
CodePudding user response:
Added the main branch locally using
git worktree add main
This is your main problem. When you run git worktree add whatever
git will by default create a new branch called whatever
and attach it to the head of the new worktree. This new branch is in no way connected to any branches on any remotes, origin
included, even if there happens to be some branch with the same name.
If you want your local main
branch to track origin/main
that can (and must in your particular case) be done with the following command:
git branch --set-upstream-to=origin/main main
However your usage of worktrees (and bare repository) seems a bit strange and I would strongly recommend not using worktrees yet until you get some more experience. Worktrees are excellent for using git test and possibly as an alternative to using git stash (which I never use)1, but not as an alternative to just switching branches.
1 I recently created a temporary worktree when needing to do something else when I has an interactive rebase with conflict ongoing which I did not want to abandon.
CodePudding user response:
As torek pointed out in a comment, the issue was caused by cloing with --bare
. That's something I picked up from "ThePrimeagen" here (2 mins in). But rather than having a full (non-bare) repo at the root, which I think I don't want, this command seems to fix it all:
git config --add remote.origin.fetch " refs/heads/*:refs/remotes/origin/*"
I still have to do git branch --set-upstream-to=origin/new-branch new-branch
from the new-branch
folder, which failed previously with "error: the requested upstream branch 'origin/main' does not exist", but succeeds after the above command.