如何在我的分支中只存储多个已更改文件中的一个?
当前回答
您还可以选择只存储单个文件、文件集合或文件内的单个更改。如果您将-p选项(或--patch)传递给git stash,它将遍历工作副本中每个更改的“hunk”,并询问您是否希望隐藏它:
$ git stash -p
按以下键之一,它将运行该命令
Command Description
y stash this hunk
/ search for a hunk by regex .
? help .
n don't stash this hunk .
q quit (any hunks that have already been selected will be stashed) .
s split this hunk into smaller hunks
其他回答
一个复杂的方法是首先提交所有内容:
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^
是的,有点尴尬。。。
我会使用git存储保存补丁。我不觉得交互很烦人,因为在交互过程中,可以选择将所需的操作应用于整个文件。
使用SourceTree,这可以通过3个步骤轻松完成。
暂时提交所有你不想隐藏的东西。Git添加所有其他内容,然后将其隐藏。通过运行git reset来弹出临时提交,在临时提交之前进行提交。
这一切都可以在SourceTree中在几秒钟内完成,您只需单击要添加的文件(甚至单个行)。添加后,只需将它们提交到临时提交。接下来,单击复选框以添加所有更改,然后单击“隐藏”以隐藏所有更改。在隐藏的更改不碍事的情况下,浏览一下提交列表,并在临时提交之前记录提交的哈希值,然后运行“git reset hash_b4_temp_commit”,这基本上就像通过将分支重置为提交之前的提交来“弹出”提交。现在,只剩下不想隐藏的内容。
我没有找到我需要的答案,这很简单:
git add -A
git reset HEAD fileThatYouWantToStash
git commit -m "committing all but one file"
git stash
这只存储了一个文件。
更新(2015年2月14日)-我重写了一点脚本,以更好地处理冲突的情况,现在应该将其显示为未合并的冲突,而不是.rej文件。
我经常发现,与@bukzor的方法相反更直观。也就是说,要进行一些更改,然后只隐藏那些已进行的更改。
不幸的是,git没有提供git存储——只有索引或类似的内容,所以我编写了一个脚本来实现这一点。
#!/bin/sh
# first, go to the root of the git repo
cd `git rev-parse --show-toplevel`
# create a commit with only the stuff in staging
INDEXTREE=`git write-tree`
INDEXCOMMIT=`echo "" | git commit-tree $INDEXTREE -p HEAD`
# create a child commit with the changes in the working tree
git add -A
WORKINGTREE=`git write-tree`
WORKINGCOMMIT=`echo "" | git commit-tree $WORKINGTREE -p $INDEXCOMMIT`
# get back to a clean state with no changes, staged or otherwise
git reset -q --hard
# Cherry-pick the index changes back to the index, and stash.
# This cherry-pick is guaranteed to succeed
git cherry-pick -n $INDEXCOMMIT
git stash
# Now cherry-pick the working tree changes. This cherry-pick may fail
# due to conflicts
git cherry-pick -n $WORKINGCOMMIT
CONFLICTS=`git ls-files -u`
if test -z "$CONFLICTS"; then
# If there are no conflicts, it's safe to reset, so that
# any previously unstaged changes remain unstaged
#
# However, if there are conflicts, then we don't want to reset the files
# and lose the merge/conflict info.
git reset -q
fi
您可以将上面的脚本保存为路径上的某个位置的git stash索引,然后将其作为git stach索引调用
# <hack hack hack>
git add <files that you want to stash>
git stash-index
现在,存储包含一个新条目,该条目仅包含您已暂存的更改,而您的工作树仍然包含任何未暂存的更改。
在某些情况下,工作树的更改可能取决于索引的更改,因此当您隐藏索引更改时,工作树更改会发生冲突。在这种情况下,您将得到通常的未合并冲突,可以使用gitmerge/gitmergetool/等解决。
推荐文章
- 为什么我需要显式地推一个新分支?
- 如何撤消最后的git添加?
- Rubymine:如何让Git忽略Rubymine创建的.idea文件
- Gitignore二进制文件,没有扩展名
- Git隐藏错误:Git隐藏弹出并最终与合并冲突
- 了解Git和GitHub的基础知识
- 没有。Git目录的Git克隆
- Git与Mercurial仓库的互操作性
- 忽略git中修改(但未提交)的文件?
- “git restore”命令是什么?“git restore”和“git reset”之间有什么区别?
- Git合并与强制覆盖
- Git拉另一个分支
- 在Bash命令提示符上添加git分支
- 如何更改Git日志日期格式
- git pull -rebase和git pull -ff-only之间的区别