1

I'm learning how to use GIT and Bitbucket. Bitbucket Admin (not me) created a remote repository.

In this repository, I have committed my changes 'A' to Master branch ( this is now root/parent/first commit in repository ).

Now, I have committed another change 'B' to Master branch. How can I rearrange the commits in remote and local repository and erase all previous history of initial commit ?

In Bitbucket, it should look like below:

Before : In Master branch

B "New Commit"

A "Initial Commit"


After: In Master branch

A "Initial Commit"

B "New Commit"

Commit 'B' was supposed to be the first/initial commit but I accidentally pushed my changes in wrong direction.

Is it possible to correct this using git commands ?

  • https://stackoverflow.com/search?q=%5Bgit%5D+rebase+root+commit – torek Dec 26 '18 at 17:49
  • Possible duplicate of [Change first commit of project with Git?](https://stackoverflow.com/questions/2246208/change-first-commit-of-project-with-git) – Mad Physicist Dec 27 '18 at 06:04

2 Answers2

0

The best general answer here is probably that you should do a git revert to functionally undo the first commit A:

git revert <SHA-1 of A commit>

To find out the commit hash for A, just type git log and search for the hash of the very first commit. It will look something like 3kd983ngl74ok.

This will add a new commit to your master branch which functionally undoes whatever the A commit added. So, your master branch will now look like:

master: A -- B -- R

where R is the new revert commit. But, the master branch will behave as if A never happened.

This is the safest option assuming you have already published your branch on the repository.

Another possibility here would be to do an interactive rebase and surgically remove the A commit from the history. But, this would be more work, more complex, and would also open the possibility of bad things happening when you force push master to the remote.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

I have resolved this issue using orphan branch. I have used following commands:

From your local repository (master branch), create a orphan branch

git checkout --orphan orphan_name

Remove all files

git rm -rf .

Add new changes

git add .

Commit the change

git commit -a -m "Initial Commit"

Push the change

git push origin orphan_name

Checkout the master branch again

git checkout master

Overwrite "master" with "orphan_name":

git reset --hard orphan_name

Force the push to your remote repository:

git push -f origin master

Delete the orphan branch

git push --delete origin orphan_name

I know it is a risk in doing this in published branch / public repo. But it was helpful to rearrange the root commit with orphan branch commit.