将单个文件提交到另一个分支

Commit a single file to another branch

我在分支feature-x做一些工作,突然遇到一个真正应该在另一个分支解决的问题,hotfix

我想创建一个带有该更改的提交,但是在 hotfix 分支上。

来自 this question 我知道标准程序是

# On branch feature-x
git stash
git checkout hotfix
git stash pop
git add -A
git commit -m "Fixed issue #562"

如果我在分支 feature-x 上没有很多更改已经在进行中,那会起作用,这会引发与分支 hotfix 的冲突。我想避免解决不必要的冲突。

为了避免这种情况,我认为我只能从存储中提取一个文件,如 this answer 中所述。所以程序是:

# On branch feature-x
git stash
git checkout hotfix
git checkout stash@{0} -- <src/buggyfile.xxx>
git add -A
git commit -m "Fixed issue #562"

然后我应该回到feature-x

git checkout feature-x
git stash pop

虽然there's a way直接从另一个分支带来文件,但我想知道是否有办法发送文件到另一个分支,没有所有这些麻烦。 实际修改的只是几个字符。

您可以在 feature-x 中提交更改并在 hotfix 中提交更改 cherry-pick,如下所示:

# On branch feature-x
git add <file>
git commit -m "Fixed issue #562" // Note commit-id
git checkout hotfix
git cherry-pick <commit-id>
git push origin hotfix

根据@torek 的评论扩展答案,使用git-worktree,如下:

git worktree add -b hotfix ../hotfix origin/master
cd ../hotfix/
git add <file>
git commit -m "Fixed issue #562"
git push origin hotfix

要将文件从 feature-x 提交到 hotfix,有一种简单的方法可以做到这一点(假设您刚刚在 feature-x 分支上添加的提交是 4712df727f7303bc95545d0f6a024129be97c5c2 ):

# on branch hotfix
git checkout 4712d filename
git commit