Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git rebase Keep latest commit date

Tags:

git

I've been working on a feature branch which is ready to be push to remote. It has 5 or so commits some are very quick commits which do not deserve it's own commit. I would like the feature to be one commit in total before I push it to remote for review.

I would normally do:

git rebase -i HEAD~5

Then fold the commits into the previous commit. This will give me one commit as I would like however, the commit date is the date of the first commit. I would like one commit with the commit date as the last commit.

How do I fold the commits into the last commit instead of the first commit?

like image 941
user7692855 Avatar asked Mar 29 '26 23:03

user7692855


1 Answers

You can set any arbitrary date you like on any new commit.

When you combine commits together with rebase -i, you're not actually changing the old commits, you are instead making one new commit, after which you simply stop using the old commits:

(before rebase -i)

A--B--C--D--E--F--G--H--I   <-- master

(after rebase -i)

           E--F--G--H--I   [abandoned]
          /
A--B--C--D--J   <-- master

where J is the new "all things combined" commit.

The bad news is that git rebase -i is designed to retain the author date-stamp on the commit into which other commits are squashed or fixup-ed. So it already uses the "set arbitrary date" feature to force J to have E's date. The interactive rebase command has no flag to change this.1

But there's a simple workaround: having made new commit J as the new-and-improved variant of E-F-G-H-I, you can simply use the same general idea to abandon J in favor of even-newer, more-improved K, which is just like J except that it has the date you desire.

To do this, after rebasing, run git commit --amend --date=... (supply whatever date you like for the ... part). You can change the author as well; see the git commit documentation. This will make new commit K to replace J, just as J replaced E-F-G-H-I, leaving you with:

           E--F--G--H--I   [abandoned]
          /
A--B--C--D--K   <-- master
          \
           J   [abandoned]

The commits that you have abandoned will, if nothing else lets you find them, eventually (somewhere after 30 days or so) lose their last methods of finding them—their IDs are retained in reflogs for some expiration period in case you want them back—and once they're truly unreferenced, the garbage collection pass (as run by git gc --auto which in turn is run for you by various other Git commands) will remove them for real.


1The non-interactive, git am based git rebase has a flag, but doesn't have the squash feature.

like image 145
torek Avatar answered Apr 02 '26 04:04

torek