git stash create 和 git stash store 的目的是什么?

What is the purpose of git stash create and git stash store?

git-scm 的文档中,有两个 git stash 命令提到了与脚本的相关性,但没有提到一般用途:

create

Create a stash (which is a regular commit object) and return its object name, without storing it anywhere in the ref namespace. This is intended to be useful for scripts. It is probably not the command you want to use; see "save" above.

store

Store a given stash created via git stash create (which is a dangling merge commit) in the stash ref, updating the stash reflog. This is intended to be useful for scripts. It is probably not the command you want to use; see "save" above.

假设我们正在考虑自动化脚本的上下文,git stash creategit stash store 比通常的 git stash save 和朋友有什么优势?

当您编写需要作为实现细节存储的脚本并且不想打扰用户的存储引用日志时,您可以使用 git stash create

根据接下来发生的情况,您可能(例如,在出现错误的情况下)决定您确实想要打扰 stash reflog,此时您可以使用 git stash store.

显然,常规存储可以根据 create 然后 store 来实现,但我也可以想象它被用在一个假设的 update-branch 命令中,它执行如下操作:

git stash create
git fetch
git rebase
git stash apply

不幸的是,Andrew 上面展示的很好的例子并不适用于所有情况,因为:

  • 如果 本地更改,则 git stash create 将创建一个未引用的提交,但实际上不会清除本地更改。

  • 如果 没有 任何本地更改,那么它根本不会创建提交(正如 BlackVegetable 指出的那样)。在那种情况下,我们不应该在最后 apply

  • (未成年人:Andrew 忘记保留和使用 create 生成的提交 ID。)

考虑到这一点,在我看来用法应该是这样的:

# Save the local changes, keep a reference to them, and clear them
stashed_commit="$(git stash create)"
git reset --hard

# Do your thing
git fetch
git rebase

# If there were local changes, then restore them
if [ -n "${stashed_commit}" ]
then git stash apply "${stashed_commit}"
fi

至少可以说是笨拙!

唉。如果我可以在顶部 git stash save --allow-empty,在底部 git stash pop,那就简单多了。

我宁愿错了。请指正!