我想强调的是,虽然您确实提到了每天都会出现的需求,git
强制命令删除你的工作没有警告也是问题的根源,会带来更严重的后果(查找“我在之后失去了工作”)git reset --hard
/ git checkout .
,我可以拿回来吗?”问题)。
和你的pull -f
例如,当您与遥控器交互时,这一事实会放大这一点,你不知道你会得到什么从遥控器。
根据我的卑微经验,我强烈建议养成不使用的习惯git pull
并且只使用git fetch
.
然后检查差异origin/branchname
,然后选择是否要重置或变基或...
最好有一个命令一次性说“移至该提交并放弃所有更改”,我将在这里重复我在评论中建议的内容@VonC 的回答 https://stackoverflow.com/a/72195298/86072 :
#!/bin/bash
target=$1
if [ -z "$target" ]; then
target=HEAD
fi
set -e # avoid going forward if one command fails ...
git stash
git restore -SW -s "$target" -- .
git reset "$target"
(我没有一个好的别名:git goto
?)
它将提供一个相当安全的替代方案git reset
;主要警告是:磁盘上的文件,不在起始提交中跟踪,但在$target
将被覆盖而不保存。
你需要一个更复杂的变体git stash
也保存这些文件。
[更新]我想我找到了一个脚本,可以设法隐藏受影响的文件(并且仅隐藏这些文件):
#!/bin/bash
target=$1
if [ -z "$target" ]; then
target=HEAD
fi
set -e # avoid going forward if one command fails ...
list_impacted_files () {
local target=$1
# tracked files in the working tree that have a diff
git diff --no-renames --name-only HEAD
# untracked files that will be clobbered when restoring $target :
# * files that are present in $target but not in HEAD
# * and that currently exist on disk (use 'ls' to keep only those)
# add '|| true' to ignore error code returned by 'ls' on non existing files
git diff --no-renames --name-only --diff-filter=A HEAD "$target" |\
xargs -r ls 2> /dev/null || true
}
# list files as described above, and feed this list to `git stash -u`
# 'xargs -r <cmd>' avoids running <cmd> at all if stdin is empty
# in our case: don't run 'git stash -u' if no files are to be stashed ...
list_impacted_files "$target" | xargs -r git stash -u --
git restore -SW -s "$target" -- .
git reset "$target"
要将您的存储库恢复到原来的状态:
- 恢复到初始提交(使用
git reset
或上面的脚本...)
- 发现
stash@{xx}
你想恢复在git stash list
- run
git stash apply --index stash@{xx}