This question pertains not only to how to accomplish this task, but to whether doing so is good or bad practice with Git.
Consider that locally I do most work on the main branch, but I have created a topical branch I will call feature_branch. In the process of working on feature_branch and switching back and forth to do other work on the main branch, it turns out that I have made more than one commit on feature_branch, but between each commit, I have done no push. My questions are:
-
Would you consider this bad practice? Would it not be wiser to stick with one commit per branch per push? In what cases would it be good to have multiple commits on a branch before a push is made?
-
How should I best accomplish bringing the multiple commits on
feature_branchinto themainbranch for a push? Is it a nuisance to not worry about it and just do the push where multiple commits get pushed, or is it less annoying to somehow merge the commits into one and then push? Again, how to do this?
For your first question, no, there’s nothing wrong with pushing multiple commits at once. Many times, you may want to break your work down into a few small, logical commits, but only push them up once you feel like the whole series is ready. Or you might be making several commits locally while disconnected, and you push them all once you’re connected again. There’s no reason to limit yourself to one commit per push.
I generally find that it’s a good idea to keep each commit a single, logical, coherent change, that includes everything it needs to work (so, it does not leave your code in a broken state). If you have a two commits, but they would cause the code to be broken if you only applied the first one, it might be a good idea to squash the second commit into the first. But if you have two commits where each one makes a reasonable change, pushing them as separate commits is fine.
If you do want to squash several commits together, you can use
git rebase -i. If you’re onfeature_branch, you would rungit rebase -i main. This will open an editor window, with a bunch of commits listed prefixed bypick. You can change all but the first tosquash, which will tell Git to keep all of those changes, but squash them into the first commit. After you’ve done that, check outmainand merge infeature_branch:Alternatively, if you just want to squash everything in
feature_branchintomain, you could just do the following:Which one you choose is up to you. Generally, I wouldn’t worry about having multiple smaller commits, but sometimes you don’t want to bother with extra minor commits, so you just squash them into one.