Git: 切换到已隐藏更改的分支时发出警告

Git: Warn when switching to a branch that has stashed changes

有没有办法让 git 在切换到已隐藏更改的分支时自动警告您?

我正在寻找类似的东西:

$ git checkout my-branch
Switched to branch 'my-branch'
Stashed changes present: stash@{0}: WIP on my-branch: 836b45a My HEAD commit

只是为了让我在几天后回到项目时不会忘记我已经在分支机构开始的工作。

不,那是不可能的,只是因为在 Git 中,隐藏的更改与分支无关。 IE。在分支 A 上时,您可以轻松 stash 未提交的更改,而在分支 B 上时,您可以轻松 stash pop 未提交的更改。在这种情况下,您可能需要解决冲突,但它仍然证明存储对于存储库是全局的,而不是分支的本地存储。

另见问题Is git stash branch-specific or for the whole repository? or Why isn't the git stash unique per branch?

一个分支没有"a stash".

存储只是一个补丁列表,您可以将其应用到任何地方。

How about appending the warning to a more branch-neutral command like git status then?

您有 commit 2414b45(git 1.6.4,2009 年 6 月)

Show presence of stashed changes in bash prompt.

Add a '$' in the __git_ps1 output to show stashed changes are present, when GIT_PS1_SHOWSTASHSTATE is set to a nonempty value.

The code for checking if the stash has entries is taken from 'git-stash.sh'.

所以尝试:

export GIT_PS1_SHOWSTASHSTATE=1 # Unix
set GIT_PS1_SHOWSTASHSTATE=1 # Windows

git stash 最初由 Nanako Shiraishi 在 commit f2c66ed(git 1.5.3,2007 年 6 月)中添加到 git。

这只是一个最近的 git(2.4.2,2014 年 4 月,commit ed178ef)试图显示警告,仅针对您当前的索引(与您当前的分支无关) :

Cannot apply stash: Your index contains uncommitted changes.

stash: require a clean index to apply

If you have staged contents in your index and run "stash apply", we may hit a conflict and put new entries into the index. Recovering to your original state is difficult at that point, because tools like "git reset --keep" will blow away anything staged. We can make this safer by refusing to apply when there are staged changes.

It's possible we could provide better tooling here, as "git stash apply" should be writing only conflicts to the index (so we know that any stage-0 entries are potentially precious).
But it is the odd duck; most "mergy" commands will update the index for cleanly merged entries, and it is not worth updating our tooling to support this use case which is unlikely to be of interest (besides which, we would still need to block a dirty index for "stash apply --index", since that case would be ambiguous).

这在 commit 1937610(git 2.4.6,2015 年 6 月)中恢复了。


为此使用一些 bash 怎么样?

您可以在 ~/.bashrc 中添加如下内容:

gco() {
    git checkout $@
    local CURRENT_BRANCH=$(git branch | grep '*' | awk '{ print  }')
    git stash list | grep $CURRENT_BRANCH
    if [ $? -eq 0 ]; then
        echo Hello! The current branch has stashed content!
    fi
}

注意:别名优先于函数。首先确保 gco 没有别名。

如果 which gco 显示类似 gco: aliased to git checkout 的内容,您将不得不使用其他内容。