git - merge 、更新和 pull Git 分支而不使用 checkout

标签 git git-merge git-pull git-checkout

我在一个有 2 个分支 A 和 B 的项目上工作。我通常在分支 A 上工作,然后 merge 分支 B 中的东西。对于 merge ,我通常会这样做:

git merge origin/branchB

但是,我还想保留分支 B 的本地副本,因为我可能偶尔会在不先与我的分支 A merge 的情况下检查该分支。为此,我会这样做:

git checkout branchB
git pull
git checkout branchA

有没有一种方法可以在一个命令中完成上述操作,而不必来回切换分支?我应该为此使用 git update-ref 吗?怎么办?

最佳答案

简短的回答

只要你在进行快进 merge ,那么你就可以简单地使用

git fetch <remote> <sourceBranch>:<destinationBranch>

例子:

# Merge local branch foo into local branch master,
# without having to checkout master first.
# Here `.` means to use the local repository as the "remote":
git fetch . foo:master

# Merge remote branch origin/foo into local branch foo,
# without having to checkout foo first:
git fetch origin foo:foo

虽然 Amber's answer 也可以在快进情况下工作,但以这种方式使用 git fetch 比仅仅强制移动分支引用要安全一点,因为只要你不这样做,git fetch 就会自动防止意外的非快进不要在 refspec 中使用 +

长答案

如果不先检查 A,就不能将分支 B merge 到分支 A,否则会导致非快进 merge 。这是因为需要工作副本来解决任何潜在的冲突。

但是,在快进 merge 的情况下,这是可能的,因为根据定义,此类 merge 永远不会导致冲突。要在不首先 checkout 分支的情况下执行此操作,您可以使用带有 refspec 的 git fetch

如果您检查了另一个分支 master,这里是更新 feature(不允许非快进更改)的示例:

git fetch upstream master:master

这个用例很常见,你可能想在你的 git 配置文件中为它创建一个别名,就像这样:

[alias]
    sync = !sh -c 'git checkout --quiet HEAD; git fetch upstream master:master; git checkout --quiet -'

这个别名的作用如下:

  1. git checkout HEAD :这会将您的工作副本置于分离头状态。如果你想更新 master 而你碰巧 checkout 它,这很有用。我认为有必要使用 with ,否则 master 的分支引用将不会移动,但我不记得那是否真的是我的想法。

  2. git fetch upstream master:master :这会将您的本地 master 快进到与 upstream/master 相同的位置。

  3. git checkout - checkout 您之前 checkout 的分支(这就是 - 在这种情况下所做的)。

用于(非)快进 merge 的 git fetch 语法

如果更新是非快进的,如果您希望 fetch 命令失败,那么您只需使用以下形式的 refspec

git fetch <remote> <remoteBranch>:<localBranch>

如果你想允许非快进更新,那么你添加一个 + 到 refspec 的前面:

git fetch <remote> +<remoteBranch>:<localBranch>

请注意,您可以使用 . 将本地存储库作为“远程”参数传递:

git fetch . <sourceBranch>:<destinationBranch>

文档

来自 git fetch documentation that explains this syntax(强调我的):

<refspec>

The format of a <refspec> parameter is an optional plus +, followed by the source ref <src>, followed by a colon :, followed by the destination ref <dst>.

The remote ref that matches <src> is fetched, and if <dst> is not empty string, the local ref that matches it is fast-forwarded using <src>. If the optional plus + is used, the local ref is updated even if it does not result in a fast-forward update.

另见

  1. Git checkout and merge without touching working tree

  2. Merging without changing the working directory

关于git - merge 、更新和 pull Git 分支而不使用 checkout ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3216360/

相关文章:

git - Gerrit 可以在 Gitlab 前面工作还是意味着要取代它

git - 为什么 Git 即使在配置之后也不允许我提交?

git - Git 推送不能快进 merge 是什么意思?

git - 使用 NetBeans pull 时如何获取修改后的文件?

GIT 下载 pull 请求文件已更改

git - 'git pull' 的默认行为

linux - 使用 GIT 将 TFS-GIT 存储库克隆到 GIT 存储库(Linux)

svn - 用于管理远程专用服务器上的站点的版本控制建议

git - git如何检查是否需要 merge ?

git - 如何检查 git merge 问题是否已修复?