How do I revert my changes to a git submodule?

2020-02-07 13:22发布

I have a git submodule (RestKit) which I have added to my repo.

I accidentally changed some files in there and I'd like to go back to the source version. In order to do that, I tried to run

Mac:app-ios user$ git submodule update RestKit

But as you can see here, this did not work as it is still "modified content":

Mac:app-ios user$ git status
...
#   modified:   RestKit (modified content)

Even

Mac:app-ios user$ git submodule update -f RestKit 

doesn't revert locally modified files.
How do I reset the content of that submodule?

11条回答
趁早两清
2楼-- · 2020-02-07 14:03

First try this, as others have said:

git submodule update --init

If that doesn't work, change to the submodule directory and use the following command to see if there are any changes to the submodule:

git status

If there are changes to your submodule, get rid of them. Verify that you can don't see any changes when you run "git status".

Next, go back to the main repository and run "git submodule update --init" again.

查看更多
虎瘦雄心在
3楼-- · 2020-02-07 14:04

For git <= 2.13 these two commands combined should reset your repos with recursive submodules:

git submodule foreach --recursive git reset --hard
git submodule update --recursive --init
查看更多
Deceive 欺骗
4楼-- · 2020-02-07 14:09

do 4 steps sequential:

git submodule foreach git reset --hard HEAD
git submodule update
git submodule foreach "git checkout master; git pull"
git submodule foreach git clean -f
查看更多
beautiful°
5楼-- · 2020-02-07 14:09

Since Git 2.14 (Q3 2017), you don't have to go into each submodule to do a git reset (as in git submodule foreach git reset --hard)

That is because git reset itself knows now how to recursively go into submodules.

See commit 35b96d1 (21 Apr 2017), and commit f2d4899, commit 823bab0, commit cd279e2 (18 Apr 2017) by Stefan Beller (stefanbeller).
(Merged by Junio C Hamano -- gitster -- in commit 5f074ca, 29 May 2017)

builtin/reset: add --recurse-submodules switch

git-reset is yet another working tree manipulator, which should be taught about submodules.

When a user uses git-reset and requests to recurse into submodules, this will reset the submodules to the object name as recorded in the superproject, detaching the HEADs.

Warning: the difference between:

  • git reset --hard --recurse-submodule and
  • git submodule foreach git reset --hard

is that the former will also reset your main parent repo working tree, as the latter would only reset the submodules working tree.
So use with caution.

查看更多
地球回转人心会变
6楼-- · 2020-02-07 14:13

Well for me, having

git reset --hard

just reset the submodule to the state where it checked out, not necessary to the main's repo referenced commit/state. I'll still have "modified contents" like OP said. So, in order to get the submodule back to the corrects commit, I run:

git submodule update --init

Then when I do git status, it's clean on the submodule.

查看更多
登录 后发表回答