如何在我的分支中只存储多个已更改文件中的一个?


当前回答

一个复杂的方法是首先提交所有内容:

git add -u
git commit // creates commit with sha-1 A

重置回原始提交,但从新提交中签出_one_file:

git reset --hard HEAD^
git checkout A path/to/the_one_file

现在,您可以存储_one_file:

git stash

通过将提交的内容保存在文件系统中并重置为原始提交来进行清理:

git reset --hard A
git reset --soft HEAD^

是的,有点尴尬。。。

其他回答

有时,我在提交分支之前对其进行了不相关的更改,我想将其移动到另一个分支并单独提交(如master)。我这样做:

git stash
git checkout master
git stash pop
git add <files that you want to commit>
git commit -m 'Minor feature'
git stash
git checkout topic1
git stash pop
...<resume work>...

请注意,第一个stash和stash pop可以取消,您可以在结账时将所有更改转移到主分支,但前提是没有冲突。此外,如果您要为部分更改创建新分支,则需要隐藏。

假设没有冲突和新分支,您可以简化它:

git checkout master
git add <files that you want to commit>
git commit -m 'Minor feature'
git checkout topic1
...<resume work>...

甚至不需要Stash。。。

这里的每个答案都很复杂。。。

“藏起来”怎么样

git diff /dir/to/file/file_to_stash > /tmp/stash.patch
git checkout -- /dir/to/file/file_to_stash

这将弹出文件更改:

git apply /tmp/stash.patch

与隐藏一个文件并将其弹出完全相同的行为。

使用git存储推送,如下所示:

git stash push [--] [<pathspec>...]

例如:

git stash push -- my/file.sh

这是自2017年春季发布的Git 2.13以来提供的。

如果不想指定包含隐藏更改的消息,请在双破折号后传递文件名。

$ git stash -- filename.ext

如果它是一个未跟踪的/新的文件,则必须先将其暂存。

此方法适用于git2.13版本+

我不知道如何在命令行上执行,只使用SourceTree。假设您已经更改了文件A,并且在文件B中有两个更改块。如果您只想将第二个块存储在文件B,而其他所有内容都保持不变,请执行以下操作:

舞台上的一切对工作副本执行更改,以撤消文件A中的所有更改(例如,启动外部diff工具并使文件匹配)使文件B看起来好像只应用了第二个更改。(例如,启动外部diff工具并撤消第一个更改。)使用“保留暂存更改”创建存储。取消标记所有内容完成!