I have this problem, i'm working in a new feature for my code, but accidentally i wrote my code in dev branch and commited my changes (i had to create a new branch).
I need to put those changes in feature_branch and revert dev to the previous commit.
I was thinking on create a branch from dev and then revert dev but i'm not doing well.
CodePudding user response:
A few important points:
- Commits in git are immutable
- Commits point to zero or more "parents", and history is always examined by following these backwards
- Branches are just a pointer to a particular commit, and from there other commits can be reached
- Branches can be freely moved to point to any commit you want
So, your history looks something like this (the backwards arrows represent the "parents" recorded in each commit):
A <--B <--C <--D
^
|
(develop)
And you want it to look like this:
A <--B <--C <--D
^ ^
| |
(develop) (feature_branch)
So, firstly, with your altered develop checked out, run git branch feature_branch
, giving this:
A <--B <--C <--D
^
|
(develop, feature_branch)
Then find the actual commit hash of commit C (where develop should be pointing) using git log
, and use git reset --hard the_commit_hash_you_found
to point develop back at that commit. (Important: This will wipe out any uncommitted changes. Commit them or use git stash
before you begin!)
A <--B <--C <--D
^ ^
| |
(develop) (feature_branch)
An important note: If you have pushed the version of develop with the changes to a shared server, or anyone else has based anything on it, there is more to do. But if you've just done this locally and not pushed anywhere, the above is all you need.
CodePudding user response:
if i understand
you could try with git stash
:
you git stash
on dev
you git checkout
on the branch you want to work
you git stash pop
CodePudding user response:
If I understand correctly then you have made two commits to dev branch instead of a feature branch. Now you would like to create a new feature branch containing all your feature commits. And you want to remove those commits from dev branch.
At this point you can create a new branch from you dev. It will have all your feature commits in the new branch. Run the following command from your dev branch.
git checkout -b {newFeatureBrnach}
Now to revert your commit from dev branch, first you will need to find the hash for those commits. Go back to your dev branch:
git checkout {devBranch}
List all the recent commits
git log
Find your commits in the log and note down the hash. Then you can use revert to remove those commits.
git revert {hash}
You would have to run it twice to revert both of your commits.
Note that git revert will make more new commits on your dev branch to reverse your changes. If you want to completely remove your commits from the history you will have to use git rebase
and force push to the remote branch. This is not advisable if multiple people are working on the repo.