git stash - >使用当前更改合并存储更改

问题描述 投票:147回答:6

我对我的分支进行了一些更改,并意识到我忘了我已经对所述分支进行了一些其他必要的更改。我想要的是一种将我的隐藏更改与当前更改合并的方法。

有没有办法做到这一点?

为了方便起见,我最终放弃并首先承诺了我目前的变化,然后是我的变化,但我宁愿一举将它们送进去。

git git-merge git-stash
6个回答
222
投票

我刚刚发现如果你的未提交的更改被添加到索引(即“staged”,使用git add ...),那么git stash apply(以及,可能是git stash pop)实际上会进行适当的合并。如果没有冲突,你就是金色的。如果没有,请像往常一样使用git mergetool解决它们,或者使用编辑器手动解决它们。

要清楚,这是我正在谈论的过程:

mkdir test-repo && cd test-repo && git init
echo test > test.txt
git add test.txt && git commit -m "Initial version"

# here's the interesting part:

# make a local change and stash it:
echo test2 > test.txt
git stash

# make a different local change:
echo test3 > test.txt

# try to apply the previous changes:
git stash apply
# git complains "Cannot apply to a dirty working tree, please stage your changes"

# add "test3" changes to the index, then re-try the stash:
git add test.txt
git stash apply
# git says: "Auto-merging test.txt"
# git says: "CONFLICT (content): Merge conflict in test.txt"

......这可能就是你要找的东西。


tl;dr

先运行git add


69
投票

运行git stash popgit stash apply本质上是一个合并。您不应该提交当前更改,除非在存储中更改的文件也在工作副本中更改,在这种情况下您将看到此错误消息:

error: Your local changes to the following files would be overwritten by merge:
       file.txt
Please, commit your changes or stash them before you can merge.
Aborting

在这种情况下,您无法一步将存储应用于当前更改。您可以提交更改,应用存储,再次提交,并使用git rebase压缩这两个提交,如果您真的不想要两个提交,但这可能会更麻烦,它值得。


21
投票

我想要的是一种将我的隐藏更改与当前更改合并的方法

这是另一种选择:

git stash show -p|git apply
git stash drop

git stash show -p将显示最后保存的藏匿的补丁。 git apply将适用它。合并完成后,可以使用git stash drop删除合并的存储。


0
投票

正如@Brandan所说,这就是我需要做的事情

error: Your local changes to the following files would be overwritten by merge:
       file.txt
Please, commit your changes or stash them before you can merge.
Aborting

请遵循以下流程:

git status  # local changes to `file`
git stash list  # further changes to `file` we want to merge
git commit -m "WIP" file
git stash pop
git commit -m "WIP2" file
git rebase -i HEAD^^  # I always use interactive rebase -- I'm sure you could do this in a single command with the simplicity of this process -- basically squash HEAD into HEAD^
# mark the second commit to squash into the first using your EDITOR
git reset HEAD^

而且你将完全合并本地更改到file,准备做进一步的工作/清理或做出一个好的提交。或者,如果你知道file的合并内容是正确的,你可以写一个合适的消息并跳过git reset HEAD^


0
投票

我这样做的方式是git add这首先是git stash apply <stash code>。这是最简单的方法。


0
投票

可能是,合并(通过difftool)并非最糟糕的想法......是......分支!

> current_branch=$(git status | head -n1 | cut -d' ' -f3)
> stash_branch="$current_branch-stash-$(date +%yy%mm%dd-%Hh%M)"
> git stash branch $stash_branch
> git checkout $current_branch
> git difftool $stash_branch

-1
投票

另一个选择是对本地未提交的更改执行另一个“git stash”,然后组合两个git stashes。不幸的是,git似乎没有办法轻松地结合两个藏匿处。因此,一种选择是创建两个.diff文件并将它们应用于两者 - 至少它不是额外的提交,并且不涉及十步过程:

怎么样:https://stackoverflow.com/a/9658688/32453

© www.soinside.com 2019 - 2024. All rights reserved.