前端项目git commit后,代码丢失如何找回

1,112 阅读1分钟

背景

前端项目为了保证代码的规范性,通常需要在git commit时进行校验。本项目通过husky插件设置了lint-staged,具体怎么配置,本篇文章就不讲述了,这里主要叙述git commit时如果代码有错误,代码丢失后如何找回。

场景

git commit时,发现下载的一个外部js文件有语法错误,导致修改的代码全部没有了。通过git log 或者git reflog也查找不到对应提交记录。

解决办法

在Git Bash终端敲下面代码(注意:此处一点要在Git Bash终端进行,亲测在cmd或者vscode中敲第2条命令会报错,小插曲部分会详细介绍)第1条命令

git stash list

此时,会看到下列结果

stash@{0}: lint-staged automatic backup

继续输入第2条命令

git stash apply --index stash@{0}

丢失的代码就可以成功找回

小插曲

开始我在vscode命令行敲第2条命令,出现下述问题。此时不用怀疑命令出了问题,改用Git Bash终端就可以。

error: unknown switch `e'
usage: git stash apply [--index] [-q|--quiet] [<stash>]

    -q, --quiet           be quiet, only report errors
    --index               attempt to recreate the index