633 points · by ddevault · 7y ago · 239 comments
I find that terminology terribly misleading and when I was learning git and rebase it confused the heck out of me.
No commits are harmed in the operation of `git rebase`. All the commits you had in the repo before the rebase are still in the repo. Git rebase creates a new sequence of commits and after doing its work relocates the branch name to the tip of the new sequence but you can easily access the previous commits if need be:
$ git co feature-branch
$ git rebase develop
$ git co -b before-rebase-feature-branch feature-branch@{1}Like you, I felt much more comfortable using git after learning this.
Yeah, completely unreachable commits have 30 days, even when you run git gc. The default reflog for a branch is even longer: 90 days!
I often try to reassure people new to git that "if you'll just commit often, there's basically no way you can lose work so that I can't help you get it back. Apart from deleting the whole repo folder. Don't delete the repo folder.".
I also have the habit of preventing non-fast-forward pushes on origin/master, which also helps when I can tell my team that they can't trash the origin even if they try.
They are still in the repo, but if no treeish item (eg. a branch) points to them, then they'll eventually get garbage collected.
Still, glad to see people are trying to elucidate git rebase. A small subset of its functionality is fundamental part of my workflow and I wouldn't know how I'd use Git without rebasing.
>git gc tries very hard not to delete objects that are referenced anywhere in your repository. In particular, it will keep not only objects referenced by your current set of branches and tags, but also objects referenced by the index, remote-tracking branches, refs saved by git filter-branch in refs/original/, or reflogs (which may reference commits in branches that were later amended or rewound). If you are expecting some objects to be deleted and they aren’t, check all of those locations and decide whether it makes sense in your case to remove those references.
https://www.git-scm.com/docs/gitrevisions#Documentation/gitr...
git branch local/foo
If you mess up too hard, check it out again.Why else are you going to go through the trouble of rebasing master if this isn't the goal you're shooting for? I'm a big proponent of commit history hygiene but even I can't defend rebasing master except for egregious things.
I think the only time I rebased master except for this was to fix a poorly executed mass file rename that broke git annotate.
$ git co feature-branch
$ git branch before-rebase-feature-branch
$ git rebase develop> HEAD names the commit on which you based the changes in the working tree. FETCH_HEAD records the branch which you fetched from a remote repository with your last git fetch invocation. ORIG_HEAD is created by commands that move your HEAD in a drastic way, to record the position of the HEAD before their operation, so that you can easily change the tip of the branch back to the state before you ran them.
https://www.git-scm.com/docs/gitrevisions#Documentation/gitr...
The same changes are still in the repo (edit: I should have said branch here), but not the same commits, because the parents and children change and therefore the hash of the commits.
It is very important to be aware that the history is changed, because the previous history can not be without issues merged with the new one, which is the main pain point and the most problems that arise from a rebase.
Each commit has a link to its parent, and represents the tip of a linked list. .git/objects is a heap of all commits (and other objects), and .git/refs contains a list commit IDs that define each head (e.g. master). git rebase will often introduce new versions of a commit to the heap and update the heads to reference new histories, but the old commits stick around and can be accessed through the reflog - with their full original history intact.
They kinda are, but that's like saying that deleted files are not deleted, but stick around for a while.
While technically true, for most practical purposes _rm <file>_ deletes the file. The fact that each and every "git 101" manual has to explain how to recover deleted commits, means something is wrong.
It's like saying: "Here's the key, and in case it doesn't work there's a pry bar in the garage". This is usually a pretty good indicator that the lock is broken.
I don’t understand what you mean. Why would you rebase a branch and then merge the rebased version with the old version of that branch? I don’t think that’s a common workflow, that is a specific case you should avoid.
Typical use of rebase to clean up the unpushed portion of a personal repo before pushing doesn’t normally cause any problems. The main thing that pops up for me is trying to re-order my own dependent commits when I forget that one commit touched the same code as another. Squashing them during the rebase is the easy fix.
> If you've made a mistake and in so doing lost commits which you needed, then git reflog is here to save the day.
Seeing that sentence in the article immediately makes me think the author has poor git practices or even understanding. reflog is useful at times, yes. But it is not what saves beginners from losing work while practicing their rebasing skills. What saves them is that they didn't rebase an important branch. They made a temp branch, pointing at the HEAD of their important branch perhaps, and they screwed up the temp branch.
If people would just make this one thing clearer to beginners, it would help a lot of people learn git more easily and with less fear.
In your local repo yes, for next 30 days. Then git will garbage collect them. But when you force push new pointers to GitHub, the GitHub repo will lose access to the unreferenced commits right away.
But of course those 30 days will give you plenty of time to go back, if you changed your mind about the rebase.
It creates new commits and moves the branch to the tip of the new sequence of commits. No existing commits are changed or deleted.
- Summarizing history: squashing "implemented subfeature A.A" and "implemented subfeature A.B" into "implemented feature A"
- Rewriting history: moving commits around, changing the base commit, and so on
In my opinion summarizing history is acceptable, you're making a creative decision that certain information will not be useful in the review/when trying to understand the code in the future.
Rewriting, on the other hand, is essentially lying. You're creating repository states that never existed, and which you have never tested. In the worst case, consider the following history:
* F: (master) Merge branch 'component2'
|\
| * E: (component2) Fixed component 2's integration with 1
| * D: (component2) Merge branch 'master' into component2
| |\
| |/
|/|
* | C: (master) Refactored component 1's API
| * B: (component2) Implemented component 2 that depends on 1
|/
* A: (master) Base
Yes, it could probably be completely linearized, but that would be a horrible idea. Commit B will leave the repository in a completely nonsensical state. Sure, you could squash in E to mitigate it (since, luckily, nothing else happened in component 2 in the meantime), but then you're still stuck explaining what will likely look like a bunch of really weird design decisions compared to if you had designed against component 1's new API immediately.Historical context matters. If in doubt, don't rebase. Never `git pull --rebase` blindly.
No one is advocating that you use rebase on your public branches or basically any branch that has been "published". We are talking about feature branches or spikes or branches that exist just on one developer's machine.
Whether you've published the true history earlier is irrelevant to that discussion.
* F: (master) Merge branch 'component2'
|\
| * E: (component2) Implemented component 2 (now with updated component1)
|/
* C: (master) Refactored component 1's API
|
* A: (master) Base
So we've lost B and D from your example, but who cares about those commits?That's on you if you don't test every commit. I don't care if you had failing tests (or even build) when you were writing your feature. I care that every one of your patches (and thus commit) does one logical thing, and that tests passes (making bisect useful).
You want your PR commit history to tell a coherent story. No one care if a writer had 15 bad draft of their story before publishing, and the same apply here.
This has been a common misunderstanding of git in the past, but thankfully is fading now. I was hoping it wouldn’t come back to haunt this thread. I don’t know where the extreme and hyperbolic idea of using git the way it was designed is “lying” and creating “false history” first came from, you aren’t the first person to suggest it, but it’s neither correct nor helpful to use that kind of language. This theoretical philosophical ideal that there’s only one true history is trading away things git was specifically created to do, as well as the practicalities of real world software development, in favor of a strange unrealistic and abstract notion that once git commit has been used the commit should never be touched again.
Everyone knows and agrees that rearranging already published commits is a bad idea. Not because it’s “lying”, but because it causes problems, costs other people time, and can even inflict irreconcilable merge conflicts on their work.
Cleaning up your own commits before you push using interactive rebase is not just a good idea, it’s the way git was designed, it’s what Linus does, and it’s kind to your team. This includes reordering commits and pulling with rebase.
> Historical context matters. If in doubt, don’t rebase. Never `git pull -- rebase` blindly.
Maybe you could back up your assertion with some examples of why it always matters, and why that justifies using words like ‘never’?
Your rhetoric is ignoring the real-world fact that on a large team, the majority of commits at any given time are orthogonal to each other, and that the parent commit you end up with is completely arbitrary.
Not only do I use pull -- rebase, I always git config --global pull.rebase true, and I frequently recommend others do the same.
Having merge commits in master every single time someone checks in is incredibly noisy and it inflicts friction on the entire team to force everyone to read the noisy log. I’ve always worked on teams that decided to take the more practical approach of one-off commits should not have a merge, regardless of when they happen, to keep history cleaner, and feature branches with more than a couple of commits or by more than one person should have a merge commit, to keep the master branch from having broken commits or unfinished features and so it’s always bisectable.
And the cherry on top is that you can't easily tell later if you are looking at rewritten history. So if the above kind of rewriting might have happened in your project, you will essentially not be able to trust git history anymore as a record of engineering decisions.
The full version of the command as
$ git rebase --onto new-base start end
takes the commit range (start,end] and re-commits them on top of the new-base commit. The commit range doesn't have to be a full branch and you don't even need to be on the branch to run the command this way. It's very intuitive and I nearly always use the full version now.I've also gotten into the habit of "pinning" my branch before I rebase so that I have it in its original form. If the branch name is my-branch, then the command
$ git branch my-branch{-hold,}
which is a handy (bash-specific?) shortcut of $ git branch my-branch-hold my-branch
leaves you on my-branch and creates a new branch label called my-branch-hold that points to the same place.EDIT: clarification of pre-rebase branching
git branch my-branch-mulliganForce pushing branches is what you do when you have pushed a branch that you expect to modify. Why would you do that? Because that's how Github and Bitbucket have taught people to conduct PR's.
If your immediate reaction is that "rebase is bad UX", ask yourself whether or not pull requests are good UX. I honestly think rebase is great, but that pull requests are extremely bad UX, and the UX blame is misplaced on rebase when where it really belongs is on pull requests.
I thought that Github and Bitbucket encouraged people to push up additional commits to fix issues in their PR. So, a typical PR will end up with a commit history like:
Implement a feature method
Add calls to new feature method
Update to version 1.2.3
fixing missing semi-colon
addressed comments
one more thing
now its working
People who force-push are the ones who are trying to keep a clean commit history (meaning you don't have those extra 4 commits). So, your point about a PR being bad UX versus a rebase is correct, but not for the reason you state.Ideally they'd use git commit --fixup=<sha> -p, and then git rebase --autosquash when the maintainer approves the merge, but few people care.
(And what I'm saying isn't really accurate any more since GitHub does show force-pushes in the pull request UI these days and one can run git range-diff on that. But this wasn't possible last year.)
The idea that git is good because it is difficult to use is just "git snobbery", as is the idea that it must be difficult because it's a DVCS.
There's nothing to stop git having two levels of the API, one exposed for tools to build off of with the full complexity and another for every day use.
I don’t think the argument is that the difficulty is a virtue, nobody is trying to be snobby, so try to avoid jumping to that conclusion.
Git just has some inherent complexity. Git does have a steep learning curve that is the root of a UX problem. But it’s not clear what better abstractions there are or how to simplify git. Lots of people have tried to make a higher level porcelain, and the issue isn’t going away. You are welcome to suggest & create a git wrapper that makes it simpler and less dangerous.
Perforce is easier to learn, so you might try using that instead. I use both and I’m becoming more and more frustrated with Perforce because git is so much more flexible and safer and easier to use once you learn how to use git.
And for anyone who doesn't know the primitives, I posted a brief summary on Mastodon the other day:
https://cmpwn.com/@sir/102038690003388821
Also recommend Pro Git's chapter on git internals.
Things could be better. There's an existence proof. It just lost the mindshare war and so now we're stuck with Git, which I still have to look up basic syntax for because its command set is contradictory and makes no sense. (Is it git <x>? git <y> --x? git <z> <a-b>? Something else entirely? Who knows!)
Git is good because it is extremely elegantly designed. There are blobs, trees, commits, and refs. When you understand them, you understand pretty much everything about git.
And yes, the interface is a mess.
GIT COMMANDS
We divide Git into high level ("porcelain") commands and low level
("plumbing") commands.But once outside that world, the user if faced with the problem that "rebase" is just a special case of "merge" and shared all the complexities and edge cases. And that's hard for fundamental reasons. Git has tools for this too, but their interface shares the complexity of the problem domain.
My last few workplaces were either not git, or relied on git pull w/o rebase. My current workplace has rebase as part of their flow, and I find that, like, 60% of my PRs require force push, which bothers me greatly. Everyone else just shrugs and considers it part of business, but I know what I WANT to do should be nicely aligned and not encounter that problem.
Unfortunately, every explanation I'm like "yes, yes, branching trees, I get it..." and then I'm suddenly in the "...and it says things are different and I don't know why". And because this always happens when I'm trying to get some fix in, I never have the time to study it to figure out what is really happening. It's just "--force and promise myself the next time will be different".
The only difference is that one's interactive and the other isn't. If you use `-i` and simply exit out of the editor, the effect is completely the same as not having used `-i`, isn't it? I think moving `rebase -i` to a completely new command could potentially make things more confusing. That new command would be an extension of `rebase` and so could be used interchangeably.
FWIW: the line noise you typed means "Make a list of the changes since three commits ago, let the user edit the list, then apply them". Other than -i step and the length of the list, this is basically a noop -- you're rebasing on an ancestor of HEAD! I mean, yeah, git lets you do that, but I don't know why you expect the syntax for irrelevant nonsense to be simple.
But let's humor you and try to use that syntax for something real. If you typed "my_version_tag~3" it might make sense -- you want to back up to the commit before whatever automation might have added for a release and put your current work on top of the earlier tree as if they had been developed as part of the release. And you have some junk in your current tree you don't want to expose to the customer to whom you are going to hand this test tree, so you want to remove it interactively.
That... sounds like a useful trick. But it's complicated. And the syntax is complicated. So what's a good syntax for the previous paragraph's action?
I generally prefer transparent systems to those that try to figure out what I really want to do.
I'd never use it on a public or shared branch, but `rebase --interactive` and `--exec` are some of my most-mused git aliases.
also: 'git push --force-with-lease' (worth repeating)
https://stackoverflow.com/questions/30542491/push-force-with...
Apparently it will think you know about the changes if you've fetched them, even if you've not merged them. And some systems auto fetch in the background.
Also, unless the diagram is confusing with the alignment, the "rebase to rebase" example seems to be implicitly assuming --onto, because the last common ancestor of 'master' and 'feature-2' includes 2 commits on that branch: the first of 'feature-1' and then the one that is only on 'feature-2'.
One thing I do in our team is provide git novices with some useful aliases, one of them being `fpush = push --force-with-lease`. It's saved a few people losing work along the years
Put those in your ~/.gitconfig:
[alias]
fu = "!f() { local msg=\"fixup! $(git log --oneline -n1 | cut -d ' ' -f2-)\"; git commit -am \"${msg}\" && git rebase -i --autosquash HEAD~2; }; f"
fuc = "!f() { local msg=\"$(git log --oneline -n1 | cut -d ' ' -f2-)\"; if [[ \"${msg}\" != "fixup!"* ]]; then msg=\"fixup! ${msg}\"; fi; git commit -am \"${msg}\"; }; f"
xx = "!f() { git reset --hard && git clean -f -d; }; f"
From now on:git fu = (git fix up) combines last commit and all staged changes into one commit with the last commit message
git fuc = (git fix up comment) commits all staged changes as a new commit with the last commit message, but prefixed with "fixup!". Except if the last commit message is already prefixed with "fixup!". Now you can work on the same thing but commit incremental steps. In the end you just do: git rebase -i master (or similar) and they will be all in one commit.
git xx = get rid off all unstaged/uncommited changes in current directory. Very destructive, very useful.
Last but not least. If you have a lot of "fixup!" or "squash!" commits and need to interactively rebase without autosquashing them do:
git rebase --no-autosquash -i master
fixup! Exact title of commit
We actually use that workflow during PR reviews on Github. That is, someone comments on a PR and the person who opened the PR will make a fixup commit with the appropriate title and reply to the comment stating that it was addressed and link the fixup commit by its abbreviated sha1 value.At the end of the PR review, the person who will merge the PR will run:
git fetch origin
git rebase -i --autosquash origin/master
git diff @{u}..
This basically updates the remote tracking branches (including origin/master), rebases the feature branch on top of the remote tracking branch for master, and then checks if any changes were introduced in the rebase process by running a diff against the remote tracking branch.If there is no diff or the diff only shows changes made on the upstream master branch since the feature branch was created, then they can run:
git push -f origin feature-branch-name
and then merge the PR.A clean git history is not a vanity project. It can be used as a tool in further code building.
As mentioned by another poster, the fact that a whole website is needed to explain the concept illustrates the design and UI failure.
This is an uphill battle that can't be won until a next-generation interface becomes usable by mortals. If that can't be done due to complexity, it's a lost cause for average developers paid for delivering business value.
With this in mind, acceptable curation of the history for me is squashing or separating commits and neither of these require rebase. But I wouldn't object if a colleague chose to use rebase to accomplish this.
I would, however, object to reordering commits or rebasing since this alters the chronicle.
Which I guess leaves me with my opinion on rebase:
You can, but you don't need to. If you are going to, be sure you understand what you are doing and don't alter the chronicle.
If you submit a PR to my project on GitHub and it consists of 20+ broken, non-atomic commits leading up to the final one, I'm going to ask you to clean them up and squash into one.
But maybe you use your history for something else that I haven't considered.
(--fixup type commits aside).
Practical benefits from not squashing history:
- Can bisect to find bug introduction.
- Can annotate/praise/blame to find who/when some change was made.
- Adam Tornhill's "Code as a Crime Scene" argues that it'd be beneficial to consume VCS history to provide health metrics on the codebase. (e.g. use VCS to check which sources have many contributors (thus potentially high defects), or check for "lost knowledge" from developers who have left).
- Can build/run an older version of the software.
But is there really a big advantage from putting time into maintaining a sequence of commits? EDIT: Ah, I see another comment point out that "maintaining a nice history" tends to mean fixing very borked commits. That makes sense. :-)
The fact that I had a bunch of stupid typos and broken tests that I didn't realize were broken before I committed doesn't need to be in the final history. What I really want for the preserved history is the conceptual chunks of changes I made along the way.
If you have a safe work atmosphere, and yor teammates reviewing the work can discover pitfalls in your project's workflow, you as a team can have discussions about it can improve your test stuff. And you can maybe go back through the history and see how many times this kind of normal human mistake with other branches and developers.
You can still diff through the PR as a unit before merging, without getting bogged down in low level commits.
Code and by extension history should be easy for humans to read. For that reason, the signal is very much worth keeping and polishing, but the noise is not. Documentation of false starts, appealing but ultimately problematic design choices, and “why” information belong in comments, commit messages, or design documents — explicit rather than implicitly littered around the history.
EDIT: I meant to include this link, which is a pretty brief yet thorough explanation of when/how/why to rebase: https://www.atlassian.com/git/tutorials/merging-vs-rebasing
Also, I've this gist on how to think about git: https://gist.github.com/nicowilliams/a6e5c9131767364ce2f4b39...
• In a number of code blocks, angle brackets are not escaped, and so text doesn’t appear in the end result.
• `<span style="color: maroon">#include</span> <stdio.h>` lacks the semicolon
• The paragraph immediately after the #conflicts heading lacks its <p>.
I also think it would be worthwhile mentioning in the first footnote a hazard of empty commits: that they will be dropped by default when rebasing.
Am I missing a config setting you explain somewhere?
You are probably thinking of 'git log', which uses the reverse order with the newest commit at the top.
Not sure why I was convinced otherwise, must be log's behaviour as you say. Had to test to believe it!
Still, rebasing is an important workflow to master even if you work on GitHub or on shared branches with others. If you mess up and force push to the wrong branch, you can always go back to the reflog[1] and check out the old version, then force push it.
[1] https://git-rebase.io/#reflog
And in the immortal words of Doug Gwyn(?): "UNIX was not designed to stop its users from doing stupid things, as that would also stop them from doing clever things."
In a rebase-oriented workflow, every commit has exactly one parent, and the commit history is entirely linearized. Merge commits have more than one parent, which means going backwards through the history means that you have to essentially navigate the branching structure to navigate the history. That makes it pretty hard to do!
A linear history is comparatively easier to reason about than a history with all of its branches. It's also, in a sense, less "true"! So it depends what you care about. Do you care about telling the exact story of everything that happened to everyone on the project, or do you care about the history of changes to the one shared copy?
Linear histories also make it easy to step backwards through the history one commit at a time. I personally just do `get checkout HEAD^` over and over, walking through the history in reverse, since most breakages are noticed within a few commits of their occurrence. I really like being able to do that. A lot of people think that's useless!
If you have one copy of the project that is considered authoritative, and all developers are synchronizing via that single authoritative copy, creating a clean and linear history is possible.
I didn't make it past this line. git is extremely good at keeping history immutable; it's also good at creating new, alternative histories and moving between them.
You mentioned "altered" history, which to me isn't much different from "edited" or "modified", though maybe that was just a slip and not your preference?
There does need to be some term for it. If I push a reordered branch, I clearly did more than nothing, even if we don't want to call that modifying history.
I do question if any term will work perfectly, or if there is any full solution other than one learning git to an intermediate level before discussing it. The problem, as I see it, is that there are (at least) two concepts of history, there is the DAG of commits, where ancestors are older, and there are branch-heads where you can change what they point to in unrestricted ways (pretty much the reflog). I'm not sure English has a really good metaphor that's going to capture everything.
Quoting from this document below.
# Rebase topic branch on the main development branch (optional).
git checkout TOPIC-BRANCH
git rebase master
# Edit commits, e.g., last 3 commits in topic branch (optional).
git checkout TOPIC-BRANCH
git rebase -i HEAD~3
# Force push rebased/edited commits to the pull request (optional).
git push -f origin TOPIC-BRANCH"Beginners to this workflow should always remember that a Git branch is not a container of commits, but rather a lightweight moving pointer that points to a commit in the commit history.
A---B---C
↑
(master)
When a new commit is made in a branch, its branch pointer simply moves
to point to the last commit in the branch. A---B---C---D
↑
(master)
A branch is merely a pointer to the tip of a series of commits. With
this little thing in mind, seemingly complex operations like rebase and
fast-forward merges become easy to understand and use."Suddenly everything makes sense now!
This works really well but I rarely see people talk about it. It means you don't have to use something complicated like github or gitlab to keep up with rebases. It works for everyone.