2

I would like to restore a whole directory (recursively) from the history of my git repository (exactly like this question).

I know that the right git command is:

git checkout [tree-ish] -- path/to/the/folder

But I have a problem: to restore an existing directory to the state of a commit, the content of the directory should be deleted first. In other case, existing files that didn't exist in the old commit won't be removed. So, to obtain exactly what I want I have to do the following command:

rm -Rf path/to/the/folder
git checkout [tree-ish] -- path/to/the/folder/

(See this answer and comments).

I'd like to know if there is a git-only command to achieve the same behaviour of the two commands above, in order to avoid making a rm manually.

EDIT: I do not want to remove untracked files or clean after the checkout, I do not have them. I want to restore a folder exactly like it was some commit ago, removing added files, restoring removed files and so on.

Community
  • 1
  • 1
Rowandish
  • 2,655
  • 3
  • 31
  • 52
  • 2
    You can do "`git clean -xdf`" after `git checkout`. – Leon Oct 20 '16 at 13:16
  • Possible duplicate of [How to remove local (untracked) files from the current Git branch?](http://stackoverflow.com/questions/61212/how-to-remove-local-untracked-files-from-the-current-git-branch) – Scott Weldon Oct 20 '16 at 18:25
  • No, I don't do the rm to remove untracked file in my repo, I have to do it before the checkout in order to have a "real" checkout: I'd like to restore my folder in exactly the state of some commit ago. If I do not remove my folder before the checkout command, I'll be in a hybrid situation in which existing files that didn't exist in the old commit are still in the folder – Rowandish Oct 21 '16 at 08:50
  • 1
    @Rowandish I see now. So you want the effect of `git checkout ` (without any paths) but for a given path/subdirectory, right? – Leon Oct 21 '16 at 10:29
  • And what is the reason that you want to avoid the `rm`? – Leon Oct 21 '16 at 10:36
  • @Leon Exactly. I'd like to remove the rm beacause I access to my repo programmaticaly (LibGit2Sharp) and, If such git command exists, I can try to implement in LibGit2Sharp. If it is not possible I can do the rm without any kind of problems ;) – Rowandish Oct 21 '16 at 14:49
  • @Rowandish I couldn't find a git-only way of doing this. – Leon Oct 21 '16 at 15:13
  • @Leon Many thanks the same! :) – Rowandish Oct 24 '16 at 07:25

1 Answers1

1

If you want only to avoid manually deleting files then you can create git-command-name file

 #!/bin/bash
 # main, path as argument...
 rm -Rf path/to/the/folder 
 git checkout [tree-ish] -- path/to/t

Put it into user/bin and git will recognised it as git command that you can call with

git command-name [path/to/the/folder]

Zildyan
  • 1,261
  • 9
  • 11