0

We are using Azure DevOps Git repo in our organization. We have recently started with GIT.

I have checked out one local branch named "feature-123". I did few changes which I committed to local branch. But I was not done with the feature development and I had to switch to some other urgent bug fix. For that, I checked out new local branch named 'bug-999' in which I want to handle the urgent bug. I fixed the bug and pushed "bug-999" to remote. But I see that my commits from the "feature-123" are also pushed.

So, commits in my first local branch are carried to the new local branch and when I pushed, they went all the way to remote.

Questions:

  1. How to handle this case?
  2. If I want to push a specific commit (excluding previous commits), how can i do that?
Learner
  • 4,661
  • 9
  • 56
  • 102
  • 2
    If you started branch `bug-999` from `feature-123` it contains all the commits of `feature-123`. – axiac Apr 10 '21 at 08:20
  • 2
    Does this answer your question? [Preferred Github workflow for updating a pull request after code review](https://stackoverflow.com/a/15055649/761202) (there's maybe a better duplicate). I considered writing an answer but, whilst the circumstances are slightly different the answer is the same. `git rebase` and `git push -f` are the two tools to use to correct the situation. Avoiding it in the first place just means good git (branch) habits. – AD7six Apr 10 '21 at 14:24

1 Answers1

2

This problem has arisen because your bugfix branch was created from the feature branch. Hence, by default, it will have all the commits that your feature branch had already. Branch in git is just a pointer to the commit. Hence, when you created your bugfix branch, git assigned one more pointer to the most recent commit of the feature branch. Now whenever you add a commit in bugfix branch, that pointer just moves ahead keeping all the previous commits intact.

TLDR: Base your new branch (bugfix in this case) from the main branch and not the feature branch.

Here's are the steps:

Let's say you have 2 branches viz. main & feature1. The feature1 branch is branched out of the main branch. You are on feature1 branch currently and you did some changes. But you realize that there's an urgent bug that needs to be fixed on main. Here's what you can do -

  1. Stage & Commit your changes on feature1 branch OR stash them using git stash
  2. Checkout the main branch using git checkout main
  3. Branch off the bugfix branch using git checkout bugfixBranchName
  4. Do your changes and commit them

This makes sure that your newly created bugfix branch is based out of main branch, hence the commits made in feature1 branch will not be there in the bugfix branch.

Now coming to your second question, this question will help you answer that.

Krantisinh
  • 1,579
  • 13
  • 16