Git - 如何将整个目录还原为特定提交(删除任何添加的文件)

ade*_*ini 13 git

我想在git中恢复一个目录 - 恢复里面的所有文件,以及删除自提交以来添加的任何文件.结帐只是满足我的第一个要求,但不删除任何文件.

ade*_*ini 19

我想出了最简单的解决方案.

git rm /path/to/dir
git checkout <rev> /path/to/dir
git commit -m "reverting directory"
Run Code Online (Sandbox Code Playgroud)

然后删除所有未跟踪的文件.

git rm
Run Code Online (Sandbox Code Playgroud)

从工作树和索引https://git-scm.com/docs/git-rm中删除文件

git checkout 
Run Code Online (Sandbox Code Playgroud)

更新工作树中的文件以匹配索引或指定树中的版本.https://www.git-scm.com/docs/git-checkout

git commit
Run Code Online (Sandbox Code Playgroud)

记录对存储库的更改https://www.git-scm.com/docs/git-commit

  • @Jarad 修订 ID,提交 SHA-1 哈希,例如提交 `cd1ad88a785c8bc05b5e9704b26b860c44218db5` &lt;----- this (3认同)
  • 很好的解决方案!对于带有子目录的目录,需要 `git rm -rf /path/to/dir` (2认同)

sun*_*ffd 6

只删除文件夹及其在git上的内容

git rm -r --cached myFolder
Run Code Online (Sandbox Code Playgroud)

删除git和本地文件夹

git rm -r myFolder
Run Code Online (Sandbox Code Playgroud)

然后提交并再次推送

恢复到先前的提交

#reset to previous commit, replace with your commit hash code, you can find it from your commit history 
git reset {commit hash} 

#moves pointer back to previous head branch
git reset --soft HEAD@{1}

git commit -m "Reverted commit to blah"

#update your working copy
git reset --hard
Run Code Online (Sandbox Code Playgroud)

恢复为提交的一部分 在这种情况下,您需要恢复为特定的提交并添加补丁

#reset to previous commit, but don't commit the changes
$ git revert --no-commit {last commit hash}   

# unstage the changes
$ git reset HEAD .             

# add/remove stuff here
$ git add file
$ git rm -r myfolder/somefiles          

# commit the changes  
$ git commit -m "fixed something"

# check the files
$ git status

#discard unwanted changes
$ git reset --hard             
Run Code Online (Sandbox Code Playgroud)


小智 5

最上面的答案很好,但我想简化一下。

git rm -r /path/to/dir
git checkout <rev> /path/to/dir       <-- the <rev> is the git commit id
git commit -m "reverting directory"
Run Code Online (Sandbox Code Playgroud)

一切都完全相同,除了我的情况下的结账命令是:

git checkout 70157c4f57aa21307cd96f146f8e98b808e1aada ./WebRoot

我在命令行上位于名为 Memento 的目录中,并使用点来表示 git 提交信息将进入的新目录将位于 Memento 文件夹中。

我正在检查该文件夹的提交内容。