如何确保我的本地分支跟踪远程是相同的而无需额外提交?

How do I ensure that my local branch tracking remote is identical without additional commits?

$ cd my/repo
$ git checkout develop
$ git fetch origin
$ git checkout -b branch origin/branch
$ git pull origin HEAD
CONFLICT (content): Merge conflict in folder/file.ext
Auto-merging folder/file.ext
Automatic merge failed; fix conflicts and then commit the result.

我真的很困惑为什么我的分支不是最新的。我认为 git fetch 从源头获取所有带有增量信息的远程分支。

甚至回去开发,删除分支,重复步骤,问题还是重复。我究竟做错了什么?我只是想确保拿下他们的,但即使在我拿下之后

$ git checkout --theirs folder/file.ext

git status 显示 folder/file.ext 已修改并要我提交更改。我根本不明白为什么要进行更改。我只想要 origin/branch 与原点完全一样,在本地,在一个名称相同的跟踪分支中。

这是如何实现的?

如果你想确保你的远程和本地同名分支是相同的,你需要从远程获取最新的更改(如果有的话)或者将你本地的最新提交(如果有的话)推送到遥控器。为此,您需要在 pull 命令中指定分支名称,而不是使用 HEAD git pull origin branch_name

如果你想确保在拉取远程分支中可用的最新代码时没有额外的提交,你应该修复将远程分支拉到本地分支后可能发生的冲突。您可以使用 git diff 命令来做到这一点。然而,Git 使解决冲突变得更容易,但如果您特别不希望有额外的提交,那么您可以修复冲突的行然后拉取。

"I thought git fetch grabs all the remote branches with their delta info from origin" - 是的,你是对的,但它停止获取信息并且不会合并这些更改,除非你执行 git mergegit pull (= git fetch + git merge).

我想我明白我想要什么了。首先,检查 git log 或浏览到 Github 上的远程 branch_name 并找到分支中的最新提交,假设 abc123... 是散列。

$ git co master
$ git fetch
$ git pull origin master
$ # remove local branch if you have one, losing changes if any!
$ git branch -D branch_name
$ git checkout abc123
Note: checking out 'abc123...'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

git checkout -b new_branch_name

HEAD is now at abc123... commit message here

$ git checkout -b branch_name
$ git branch --set-upstream-to=origin/branch_name
Branch branch_name set up to track remote branch branch_name from origin by rebasing
$ git pull origin/branch_name

我现在有一个本地 branch_name 跟踪 origin/branch_name 在准确的时间点(完全相同的提交散列)作为 origin/branch_name 没有 diff/merge/rebase 也没有额外的合并提交被推送到我的远程仓库以便继续。