0

by mistake I deleted files that I actually just wanted to move to another directory. I have also committed and pushed this changed, so that these files are regarded as deleted. Is there a way to move these files to a directory afterwards and make them to be seen as "moved"?

This would help to keep the git history clean.

Thanks in advance.

N1l0c
  • 19
  • 2
  • you can revert the commit and then create another commit "moving" the files. But note that git doesn't really have a concept of moving files. Moving files just means that the same file exists in another place. – dan1st Nov 19 '21 at 08:54
  • Does this answer your question? [How do I revert a Git repository to a previous commit?](https://stackoverflow.com/questions/4114095/how-do-i-revert-a-git-repository-to-a-previous-commit) – Orace Nov 19 '21 at 10:41

2 Answers2

1

Assuming:

  1. Your branch is not shared, which lets you rewrite its history
  2. You want to avoid this "mistake" staying in history, like if you did it right the first time
  3. The "bad" commit is the last one you committed/pushed (i.e. There are no commits to preserve after this one)

THEN you could :

# restore your files in the working tree
git restore --source=HEAD^ -- path/to/file1 path/to/file2 path/to/dir/*

# at this point, move the files where you want them to be

# then record them into index
git add .

# and edit last (bad) commit to record the move instead of the deletion
git commit --amend

# finally, push to remote for the new branch history to replace the old one
git push --force
Orace
  • 7,822
  • 30
  • 45
Romain Valeri
  • 19,645
  • 3
  • 36
  • 61
0

You can revert the changes:

git revert HEAD

Then, move your files and commit again. Take into account that git takes into account that a file was moved only if the renameLimit is high enough (https://git-scm.com/docs/merge-config).

Sergio Lema
  • 1,491
  • 1
  • 14
  • 25