我想使用这个工作流:

进行一些改变。 将未分阶段的更改保存到存储中。 用阶段中的东西做一些事情(构建、测试等)。 提交。 恢复未分阶段的更改。

有办法完成第二步吗?

例子:

git init
echo one >file
git add file
git commit
echo two >>file
git add file
echo three >>file
git stash push
test
git commit
git stash pop

当前回答

这可以通过3个步骤完成:保存阶段性更改,保存所有其他内容,使用阶段性更改恢复索引。基本上就是:

git commit -m 'Save index'
git stash push -u -m 'Unstaged changes and untracked files'
git reset --soft HEAD^

这正是你想要的。

其他回答

我对Python程序如何预提交感兴趣。这是代码。 https://github.com/pre-commit/pre-commit/blob/3fe38dff05957f609cf7b97f471b35a8d9e0659a/pre_commit/staged_files_only.py#L50

它在功能上等同于:

git diff-index --ignore-submodules --binary --exit-code --no-color --no-ext-diff $(git write-tree) -- >stash.patch
git checkout -- .

# Do stuff now

git apply stash.patch && rm stash.patch

我使用了一个别名,它接受一个字符串作为消息发送到存储条目。

mystash = "!f() { git commit -m hold && git stash push -m \"$1\" && git reset HEAD^; }; f"

哪一个:

提交索引中的所有内容, 将更改的内容存储在工作树中(当然可以添加-u或-a), 将最后一次提交重置回工作尝试(可能需要使用——soft将其保留在索引中)。

另一个建议,与这个问题有关:

当您使用

$ git stash save -keep-index

你可能希望给stash一个消息,这样当你做一个git隐藏列表时,它会更明显地显示你之前隐藏了什么,特别是当你跟随stash操作进一步保存时。例如

$ git保存保存—keep-index“尚未进行更改”

(尽管实际上它确实包含了其他答案中提到的所有变化)。

例如,上面的语句之后可以立即加上:

$ git保存“功能X的阶段性变化”

但是要注意,你不能使用它

$ git stash apply "stash@{1}" ###所以并不完全符合你的要求

只恢复未分阶段的变化。

扩展前面的回答,我有时会有一组复杂的更改,但希望先提交一个单独的更改。例如,我可能发现了一个错误或其他不正确的代码,我想在进行阶段性更改之前修复它。一个可行的方法是:

首先把所有东西都藏起来,但保留阶段性的变化

$ git保存——keep-index[——include-untracked]

现在也将阶段性更改单独保存

$ git保存

为解决问题做出改变;和测试;提交:

$ git add[——interactive][——patch] $ git commit -m"fix…"

现在恢复之前的更改:

$ git隐藏pop

解决任何冲突,并注意如果存在冲突,git将应用而不是删除顶部的隐藏条目。

(…然后提交分阶段的更改,并恢复所有其他更改的存储,然后继续…)

Git没有只存储未分阶段更改的命令。

但是,Git允许您指定要保存哪些文件。

git stash push --message 'Unstaged changes' -- app/controllers/products_controller.rb test/controllers/products_controller_test.rb

如果您只想在这些文件中保存特定的更改,请添加——patch选项。

git stash push --patch --message 'Unstaged changes' -- app/controllers/products_controller.rb test/controllers/products_controller_test.rb

——include-untracked选项允许你隐藏未跟踪的文件。

git stash push --include-untracked --message 'Untracked files' -- app/controllers/widgets_controller.rb test/controllers/widgets_controller_test.rb

运行git help stash(或man git-stash)获取更多信息。

注意:如果您的未分阶段更改相当混乱,@alesguzik的答案可能更简单。