-1

I intialized a repo but now want to undo the first (and only) commit.

These three solutions for undoing a commit all error because the freshly created repo points to a ref that doesn't exist yet

So my question is how do I undo a commit in a repo that hasn't been pushed and hence hasn't got a ref yet?

Note: I have also tried git commit -amend without success

stevec
  • 41,291
  • 27
  • 223
  • 311

2 Answers2

1

If you have just one commit you want to remove, you can just remove the .git/logs/refs/heads/master file that recorded the commit log ID. Also remove file .git/refs/heads/master that recorded the commit for the master branch. You may also want to remove the .git/logs/HEAD file that stores the last commit ID. After removing those references the objects will eventually garbage-collected.

But probably it's easier and faster to remove the whole .git directory and git init again.

U. Windl
  • 3,480
  • 26
  • 54
1

Note: technically this doesn't undo the commit, but it's just as good—an empty repository has little function. To really empty out the repository, see below.

git commit --amend should work. Here is a demonstration:

$ git init
Initialized empty Git repository in .../.git/
$ echo test changing root commit > README
$ git add README 
$ git commit -m initial
[master (root-commit) 90e83ae] initial
 1 file changed, 1 insertion(+)
 create mode 100644 README
$ echo different readme > README
$ git add README 
$ git commit --amend --no-edit
[master 8e159b1] initial
 Date: Sat Mar 2 21:00:53 2019 -0800
 1 file changed, 1 insertion(+)
 create mode 100644 README
$ git log --all --decorate --oneline --graph
* 8e159b1 (HEAD -> master) initial

Note that the "different README" is what went in to this new root commit:

$ git show --pretty=oneline
8e159b1f0d397b31cb1be5168e77ba200269c62a (HEAD -> master) initial
diff --git a/README b/README
new file mode 100644
index 0000000..ef0411a
--- /dev/null
+++ b/README
@@ -0,0 +1 @@
+different readme

If you have files you don't want in the new root commit, use git rm (perhaps with --cached) to remove them.


If you really want to delete the master branch and its single commit, and then be on the master branch as you normally are in a new, empty repository, it takes a couple of extra steps, at least as long as you want to use normal (not plumbing) commands. Here are the steps:

  1. git branch -m master delete: rename the master branch out of the way
  2. git checkout --orphan master: get back on a branch named master that does not exist
  3. git branch -D delete: delete the unwanted branch
  4. git read-tree --empty: empty out the current index

The work-tree is undisturbed by this process.

torek
  • 448,244
  • 59
  • 642
  • 775