【Git】回退单个文件到指定版本

文章目录

如果某次改动比较大,牵涉到的文件比较多。但是某个文件本来是没问题的,结果画蛇添足,改出问题来了,这时候直接回退版本会把所有代码都回退掉,可能得不偿失。这时候就需要指定回退单个文件到为修改之前的版本。

  • 首先先获取需要回退的文件路径,比较简单的方法就是,在该文件加个细微改动,比如一条无关注释,然后通过git status查看路径
➜  git:(test) git status
On branch test02
Changes not staged for commit:
  (use "git add ..." to update what will be committed)
  (use "git restore ..." to discard changes in working directory)
  		# modified:后面的就是文件路径
        modified:   packages/pages/src/table/index.vue

no changes added to commit (use "git add" and/or "git commit -a")
  • 路径获取到后,就把刚才的改动回退掉:git checkout -- .
➜ git:(test)git checkout -- .
➜ git:(test) git status
On branch test02
nothing to commit, working tree clean
  • 然后再查看commit版本信息:git log,后面的数字表示查看多少条记录
➜ git:(test) git log -2
commit 555a38d888d4c3743491ddeb8a4235c4ec3cc49b (HEAD -> test)
Author: 流星
Date:   Tue Feb 14 11:20:15 2023 +0800

    chore: 登录功能大改

commit 6f53d8d8d4d570082e580554b68d36707f50421b
Author: 流星
Date:   Mon Feb 13 16:45:21 2023 +0800

    feat: 添加登录功能

(END)
  • 由于我们是登录功能大改那个出现的问题,所有我们需要把这个文件回退到添加登录功能那一次

  • 这里有2个东西是要提前复制好的:

1. 需要回退的文件路径:packages/pages/src/table/index.vue
2. 需要回退到哪的 commit ID:6f53d8d8d4d570082e580554b68d36707f50421b
  • 然后执行:git checkout ID 路径
➜  git:(test) git checkout 6f53d8d8d4d570082e580554b68d36707f50421b packages/pages/src/table/index.vue
Updated 1 path from 1ccf76171
  • 此时代码就会还原到登录功能大改之前,如果不需要做啥修改,这时候出现commit即可
➜ git:(test)git status
On branch test02
Changes to be committed:
  (use "git restore --staged ..." to unstage)
        modified:   packages/pages/src/table/index.vue

➜ git:(test)git commit -m 'chore: 还原某某文件'
→ No staged files match any configured task.
✔ Preparing lint-staged...
✔ Running tasks for staged files...
✔ Applying modifications from tasks...
✔ Cleaning up temporary files...
--------------------- git add ------------------
Nothing specified, nothing added.
hint: Maybe you wanted to say 'git add .'?
hint: Turn this message off by running
hint: "git config advice.addEmptyPathspec false"
---------------------- done --------------------
[lstest02 758a23df5] chore: 还原某某文件
 1 file changed, 1 insertion(+), 1 deletion(-)

你可能感兴趣的:(Git,使用技巧,git,github)