0

I know that I can go back in history to earlier commits using git reset --hard <commit>. However, this only lets me roll back to the first commit (not before the first commit).

I want to do this, since I created a Git repository and committed a lot of wrong files and directories. Simply deleting the repository and starting over is not an option here, since repositories are created by an admin.

How can I reset my Git repository to the state before the first commit?

Shuzheng
  • 9,468
  • 11
  • 67
  • 148
  • 1
    Technically, this (`git checkout --orphan`, set up index, make new root commit, proceed) isn't quite resetting to the state-before-the-first-commit as all the *existing* commits continue to exist. However, it's probably what you want. Once all *names* for the old commits that you don't like are gone, those commits themselves will eventually be garbage-collected. – torek Nov 26 '19 at 17:34

3 Answers3

3

As an alternative to amending the first commit, you can also create a fully new branch using git checkout --orphan and then reset master to that one:

git checkout --orphan new_master
# add files
git commit -m "new initial commit"
git checkout master
git reset --hard new_master
git branch -D new_master
Joachim Sauer
  • 291,719
  • 55
  • 540
  • 600
3
git checkout --orphan temp      # Start a new history with a dummy initial branch
# Prepare your first commit...
git commit                      # As usual, this will actually create the temp branch
git checkout -B master          # Bring master onto this new commit
git push --force origin master  # Update the remote, dropping the old history
git branch -d temp              # Delete the temporary branch
Quentin
  • 60,592
  • 7
  • 125
  • 183
2

You can do whatever changes you want, and amend to the last commit:

# do changes
git commit --amend
# enter a new commit message if you wish

If you want to merge two commits, you can use git rebase -i --root which allows you to handle the very first commit with the next ones.

Maroun
  • 91,013
  • 29
  • 181
  • 233