10 ms·
How to Squash and Rebase in Git
- avgcorrection 5y agogit(1): there is more than one way to do it
- lelandfe 5y ago> Create a backup branch and push it up to GitHub/Gitlab/etc. This backup branch will have all your work nice and safe in case you need to start over. The way I teach programmers to do this is to make use of cheap branches and to instead work on a temporary branch, and eventually use ‘git reset --hard branchName’ to turn your original branch into a mirror of the temporary one when ready. This is a helpful mindset to get into; you can just throw it away in a worst case.
- avgcorrection 5y agoFor rebasing specifically I often don’t make a temporary branch. I’ll use the reflog and reset to the commit hash if something gets messed up. Those “backup” branches really aren’t that for me. They’re just named commits which makes it easier to figure out where I was. But they are sometimes necessary since the reflog isn’t always nice and easy to read. And pushing that branch to a remote? That’s unnecessary unless you want to delete the whole repo and clone it again in case you “mess it up”. Well, I guess that could be useful in a tutorial.
- lelandfe 5y agoBear in mind we’re teaching folks how to rebase - reflog can be an intimidating dive for a first blush discussion
- dvlsg 5y ago`git reset --hard ORIG_HEAD` is often enough to "undo" a rebase that went haywire. `git rebase --abort` can be helpful too, if you run into some unexpected merge conflicts along the way.
- tyleo 5y agoIs this the same as `merge —squash`? I’m pretty sure it just creates a single commit on the target branch rather than a merge commit.
- nwatson 5y agoYeah, this is easier ... and broken down ... Work on a temporary branch, get stuff all working there, keep merging changes elsewhere into the temporary branch to stay up to date with your PR target branch. Push the temporary branch early and often and don't worry too much about its commit messages (will never be part of official history) except as they pertain to your understanding of the evolution. Then create a new branch (for PR) off the one you'll eventually PR to, and `merge --squash` your temporary branch into the branch for PR with an awesome commit message. Submit the PR. Kill your temporary branch when no longer useful. Modify the strategy a bit if you want to break up the PR into multiple coarse commits ... 100 temporary-branch commits, 3 new-material commits in for-PR branch, and 4 back-merges of PR target branch to for-PR branch into temporary branch. This keeps a full context of your changes vs upstream changes.
- whywhathow1990 5y agoexactly what I have been doing
- bin_bash 5y agoI recently started using `git commit --fixup` which I really like. It lets you take the current changes and apply them to a commit which is not the most recent (in a fairly roundabout way). It's good for when I have a stack of diffs and want to make changes to multiple commits at once. (Note this is a pretty advanced technique, if you're not super comfortable with `git rebase -i` I wouldn't bother even trying to understand `--fixup`) https://fle.github.io/git-tip-keep-your-branch-clean-with-fixup-and-autosquash.html https://fle.github.io/git-tip-keep-your-branch-clean-with-fi...
- aayjaychan 5y agoif you do this often and want some automation, `git absorb` [1] may be worth a look. it will try to find lines that can be unambiguously attributed to a diff based on when the line and its surrounding lines are last modified, and then generate fix-up commits or amend existing ones. [1]: https://github.com/tummychow/git-absorb https://github.com/tummychow/git-absorb
- ninkendo 5y agoFixing up merge conflicts multiple times when rebasing is indeed a huge pain (has anyone actually used git rerere? If I ever find myself in this situation I always just squash first instead.) However I typically squash by just doing a soft `git reset` to the merge-base (the last commit in common with my branch and the one I'm building my work from) and making a new commit. It avoids touching the working tree at all, which avoids breaking my build cache and confusing my IDE. If I instead want to do a squash-rebase onto the _latest_ of the upstream branch, I do the same as the above, except I `git merge` first (to resolve any merge conflicts in one shot.) Then the merge-base is just the upstream head. This is way easier than doing `rebase -i` and squashing, because you don't have to fix the merge conflicts over and over again for every commit you're trying to squash... just fix the merge conflicts once during the merge, and the "reset and commit" trick is going to create one clean commit in the end anyway.
- secondcoming 5y agoMan, this is way too complex for me.
- mpawelski 5y agoThe wording might seems complex (I still had to think about what is "upstream" and "merge-base" since I'm not using this terms very often but the main idea the author proposed is quite simple and brilliant if you know "how git works" and what "git reset" does. I don't do it but I like it a lot :) Probably many git users works like this because it all makes sense. The commands will look like that if you want to just squash your changes: git reset --soft $(git merge-base HEAD origin/master) git commit -m 'squashed commit` and like this if you want to squash and rebase on "upstream" (most likely "master" on "origin" remote), andrewmackrodt already wrote it in another comment: git fetch git merge origin/main git reset --soft origin/main git commit -m 'HN-1337 Awesome new feature' I like this approach (haven't tested it yet!) because as author wrote it doesn't unnecessary change much files in you current working directory, and IDEs sometimes get crazy when you do rebase. Currently, I usually try to write my individual commits to be logical changes grouped together and if I see there are some WIP commits or commits that don't look like one logical change, then I just squash this commits (not whole branch). This helps a little in avoiding unnecessary merge conflicts in rebase, but it's not always perfect solution. I still need to figure out what this "git rerere" magic does though...
- yboris 5y agoSemi-related: my favorite dev tool is diff2html I aliased `diff` to open up my browser showing me the full diff of what I'm working on - super useful! https://diff2html.xyz/ https://diff2html.xyz/
- thebruce87m 5y agoHow does this differ from “git difftool” with something like Meld installed?
- unicornmama 5y ago10+ years and I still don’t understand why developers and orgs think it’s necessary to squash and rebase.
- barbazoo 5y agoFor me it's a combination of commiting often and keeping the history readable. To achieve both I have to a) squash commits before merging otherwise I end up with dozens of intermediate commits and b) rebase, otherwise I end up with a history that looks like the Tokyo subway system.
- afidrya 5y agoDownside of squashing as opposed to making a merge commit (without fast forward) or merging by rebasing, however, is losing granularity. Later it'll be hard to roll back a small part of PR while keeping rest of the changes. Also it'll be harder to go back and review changes when troubleshooting issues because formatting changes were squashed together with business logic changes. With merges at least there are still original commits available, and it'll be possible to either rollback everything or a single commit.
- sodapopcan 5y agoI could be wrong, I feel like OP is talking about the workflow where the entire branch is squashed before it is integrated into the main branch, not squashing intermediary commits into more logical ones (which is what I think you are talking about).
- mportela 5y agoAFAIK it's usually to keep the git history clean but doing it manually is so painful. In my company, we enabled GitHub's "Squash and Merge" option (1) so we have the best of both worlds: a clean history and an 1-click squash process. (1) https://github.blog/2016-04-01-squash-your-commits/ https://github.blog/2016-04-01-squash-your-commits/
- julenx 5y ago
- AcerbicZero 5y agoAbout half the time I get stuck during squashing and rebasing I end up trashing everything, re-cloning the repo and just doing one commit with all my changes from the other branch. Much easier than trying to figure out what series of errors or issues git is having. Fundamentally, this is my fault - I don’t have a good mental model of git, and even when I do have a solid understanding of what I’m attempting to achieve the actual repos/situations I find myself in rarely line up with the examples to any useful degree.
- fulafel 5y agoYou could just preserve the history (= don't use rebase, just merge), it has benefits too in addition to making your immediate life easier and safer.
- mhitza 5y ago'git reflog' is your friend as it keeps a history of local operations, then you can do a 'git reset --hard HEAD@{X}' where X is the point in your reflog before the rebase started.
- omegalulw 5y agoWhile this is true, it's also more of a crutch. You should practice to predict, before your rebase, what conflicts your are gonna hit. And aborting a rebase is a significantly safer option. I would only recommend reflog when you rebased (on) the wrong commit and you want to undo a successful rebase.
- slumpa 5y agoBefore I rebase, I always create a "backup" branch (`git branch backup`). Then if I mess up, I can always reset back to it (`git reset --hard backup`). Maybe better than trashing and re-cloning :-)
- notapenny 5y agoAs long as your source and target branch are present on the remote (i.e. github/lab/whatever) you probably don't need to trash the entire repo. Just `git --rebase abort` and if you're halfway through a rebase just delete your local source branch and re-fetch it from the remote. That's my process anyway if I somehow lose track of what I'm doing. Or sometimes as a reference I just open the remote branch in github/lab/whatever directly so I have a little cheat sheet, since the "current/incoming" somehow always confuses me.
- fs111 5y agoIf you find yourself solving the same conflicts over and over again, consider turning on rerere: https://git-scm.com/docs/git-rerere https://git-scm.com/docs/git-rerere
- billsix 5y agoI use a “squash” alias to make it simpler for me https://github.com/billsix/dotfiles/blob/master/.gitconfig https://github.com/billsix/dotfiles/blob/master/.gitconfig
- PaulDavisThe1st 5y agoFor ardour, we almost never squash commits because we prefer our (always linear) git history to show the actually "story" of a branch's development. There are two exceptions. 1. branch developer suffered from several "thinkos" along the way, the branch doesn't contain that many changes, and there's simply no benefit to seeing the contrast between the initial (mistaken) changes and the final result. 2. the branch commits create a situation where git bisect can't be properly used because intermediate commits will not compile. Squash is one option here, though it is often preferable to just re-branch and re-work commits to avoid both the bisect problem and the squash. With a 21 year development history, we have found it invaluable to be able to trace the "thought processes" behind a series of commits, and squash would rob us of that.
- jawns 5y agoI find that forcing developers to record and publish every little mistake they made along the way has bigger downsides than the upsides of being able to follow along with their thought processes as a branch or PR evolves. Similarly, I don't really care how many times you merged main in the course of developing on a branch. Those commits are just noise to me. As long as only a single developer is working on a branch at once, I'm very comfortable with them treating commits as a work in progress, then doing an interactive rebase before merging to main to clean things up. Even in the case where multiple devs are working on a feature branch, as long as they're coordinating properly (and using safeguards such as `git push --force-with-lease`), I find more value in having tidy, organized commits at merge time than a full history of the development process.
- bastardoperator 5y agoYou have no way of knowing if a developer squashed locally...
- PaulDavisThe1st 5y agoCorrect. Rules for this stuff are pointless, but guidelines to generally follow are not.
- 5y ago
- mavsman 5y agoAmazing that we don't yet have a source control solution that's simpler than git. It should not be a barrier to entry for our profession.
- BeetleB 5y agomercurial is calling you.
- avgcorrection 5y agoIf a person dislikes Git then the best they can do now is to use another VCS locally and only interface with Git remotely. Although they might be forced to use a lot of Git features if their boss wants people to actively rebase their own pull requests.
- chucky 5y ago> Did you ever need to do git rebase --continue over and over again just to get your own branch up to date? Not really. The secret is to rebase fairly often, at the very least daily (depending on the size of the organization you work in, this could be more often). I often see complaints like this from junior devs. They work in isolation on their branch for a week, and then they complain about how hard it is when they try to do a rebase on top of the 100+ commits that happened while they were out there doing their own thing. Another common issue comes from not understanding how rebase works well enough. You are supposed to adjust just the changes of this commit, not take anything else into account. If you start making unrelated changes when rebasing, your commits will soon conflict with each other, which means you'll run into a lot of very confusing conflicts. It's fine to squash before a rebase if you are not interested in the history of your branch. But if you are, it's just not an acceptable solution.
- jenweber 5y agoThanks everyone for sharing your workflows! I’m totally linking this thread in the article. Git history management can be tricky business, and most teams have their own norms, as this discussion shows. What matters most of all is that everyone on your team learns and feels supported with your chosen git processes, including junior devs, and that you have some consensus on it. For anyone who is overwhelmed by the options and syntax, one of my friends swears by Fork, for those who prefer a GUI over doing git by hand. It has its own learning curve, but works better for some devs.
- alkonaut 5y agoIf I get a PR to review I want the set of commits to be clean and represent logical changes. No “oops” commits. What’s more, I also want only commits that relate to the feature implemented on the branch. Preferably no merges from the parent branch. To get zero oops commits requires squashing in the branch. Note that this is independent of whether the branch is merged or squashed when the PR is completed. Squashing 10 branch commits to 3 is the important step. If those 3 are squashed to a single on the target branch is less important and is a tradeoff. As a developer I’ll not care to maintain build/testable code on feature branches, which is my main reason for usually squashing to the target branch. For larger changes I merge (after cleaning up and interactively rebasing), but git bisect will have to use —first-parent to work.
- omegalulw 5y ago> If I get a PR to review I want the set of commits to be clean and represent logical changes. No “oops” commits. +100. Though every time this comes up on HN you would be surprised by how much some people just vehemently disagree. I will also add another requirement - all unit tests should pass at each commit in the PR. That way, you can use the rebase strategy to merge and you would still be able to bisect.
- alkonaut 5y agoPassing unit tests on each commit is only a realistic goal if developers can run all tests locally in less than (say) an hour. If the test suite is ten hours and you have ten commits on a branch then it quickly becomes silly to bog down your build servers (or cloud bills) with building and testing the intermediate commits over 90h. Using your own machine to do it (blocking it from doing other work) is obviously not a good idea either.
- omegalulw 5y ago> If the test suite is ten hours and you have ten commits on a branch then it quickly becomes silly to bog down your build servers That's a fair point, but I would say that if you encourage your devs to make each commit logical, meaningful and self contained, this is worth the extra cost. Also, you don't need to run ALL unit tests - just the ones affected by commit you are testing. This of course requires a build system with good dependency analysis.
- nathell 5y agoI used to squash my feature branches before merging, but I switched to rebasing. Here’s why: https://blog.danieljanus.pl/2021/07/01/commit-groups/ https://blog.danieljanus.pl/2021/07/01/commit-groups/