Git部分提交分阶段更改

时间:2012-01-26 15:53:56

标签: git

我当前的git status看起来像这样:

# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#       modified:   docs/file3.org
#       modified:   src/main/R/lib.R
#
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#       modified:   docs/file3.org
#       modified:   src/main/R/lib.R

我想首先将暂存更改提交到docs/file3.org,然后再进行其他阶段更改。但是,如果我做git commit -m '...' docs/file3.org,它将同时提交分阶段&amp;对该文件的未分级更改。

有一种简单的方法吗?或者我是否需要stash我的未分级更改,取消其中一个文件,提交另一个,重新设置,提交和stash pop

4 个答案:

答案 0 :(得分:9)

由于您只需要将暂存的更改提交到文件,因此您可以隐藏,保持索引更改不变,然后提交文件。

git stash --keep-index #Note that the staged changes also become part of the stash
git commit -m "Commit only one file" docs/file3.org

git commit -m "Commit other staged changed"
git stash pop 
# This may raise CONFLICTS since the stash includes the earlier staged changes.
# In case of conflict, the stash is not popped, so you need to drop it explicitly.

答案 1 :(得分:3)

真正奇怪的是,git-scm书籍解释了你的描述:

同一文件的非分段更改不与提交一起进行,只有分阶段更改。

检查出来: http://git-scm.com/book/en/Git-Basics-Recording-Changes-to-the-Repository#Staging-Modified-Files

我开始测试,无论我上传的同一文件发生了什么变化,所有更改都随着提交而变化。

答案 2 :(得分:2)

我会假设你所有这些都在master ......

git branch whatever
git commit # commit currently staged changes as 'commit1'
git add docs/file3.org
git commit # commit unstaged changes as 'commit2'

你现在有了这个

master
  \
   \--commit1--commit2

现在,运行git log并记录'commit1'和'commit2'的SHA。

git checkout master
git cherry-pick commit2SHA
git cherry-pick commit1SHA

哪个会给你

master--newcommit2--newcommit1
   \
    \--commit1--commit2

然后你可以销毁'无论'分支

git branch -D whatever

修改

你也可以使用藏匿处做类似的事情:

git stash --keep-index  # Save unstaged changes
git stash               # Save staged changes
git stash pop stash@{1} # Pop unstanged changes
git commit ...          # Commit unstanged changes
git stash pop stash@{0} # Pop staged changes
git commit ...          # Commit staged changes

答案 3 :(得分:1)

git stash是最佳选择,并结合使用。

git add --interactive

这应该允许您“恢复”(取消)已添加到索引中的某些文件 然后git stash将允许您保存这些文件并将其还原。

(有关示例,请参阅“git add --patch and --interactive”文章)