0

Recently I faced a unique issue wherein I have to include only the newest commits in a branch discarding all the old ones.

e.g. consider I have such a commit structure:

[main branch]
af474e3 (HEAD -> main) Updated modal UI
c0f9599 Added modal UI                    <-- This commit onwards is what our requirement is
e50c805 Updated button UI
de2ab3c Added button UI
9b1822f Initial commit

(I know this sounds silly but,) I want to get all the (latest) commits from that point onwards with all the commit information associated with it i.e. commit date, commit author etc.

The created branch must look like:

[new branch]
af474e3 (HEAD -> new, master) Updated modal UI
c0f9599 Added modal UI

I tried removing/squashing commits with interactive rebasing, it didn't work. Cherry-picking didn't work either.

Can this be achieved? Is there any easy way to achieve this?

bantya
  • 576
  • 11
  • 23
  • Do you want any of the changes that happen in the first 3 commits to still be there without having their own commit? (i.e. do you want to squash the first 4 commits into one?) If the answer is no, then realize it must be the case that the 4th and 5th commits that you want to keep do not edit or use any of the files created in the first 3 commits. – TTT Aug 11 '21 at 20:56
  • You mentioned you want to maintain the *commit* name and date, but, typically it's the *author* name and date that are preserved when re-writing commits, not the *commit* name and date. By default, when re-writing commits, the *commit* name and date will change to "you" and "now". Is that OK with you? Note the *author* name and date is what's typically shown when you look at the logs, so normally everyone allows the *commit* name and date to change to whomever last wrote the commit. – TTT Aug 11 '21 at 21:00
  • @TTT as you rightly said in the first comment, I realized that when I tried different approaches. I could not use earlier commits discarding older ones if earlier commits constituted same files which are modified in older commits. A lesson learnt hard way! – bantya Aug 12 '21 at 15:39
  • @TTT, I missed it to say in my question that I don't require the commit message to be the same. And yes, keeping the _commit message_ and _commit date_ is OK with me. – bantya Aug 12 '21 at 15:45
  • In that case I think you can select [eftshift0's answer](https://stackoverflow.com/a/68748769/184546), as I believe it does what you want. – TTT Aug 12 '21 at 18:37

1 Answers1

2

You want the branch to start on revision c0f9599 with files and contents like that revision?

git checkout --orphan new-branch c0f9599
git commit -C c0f9599 # use the same comment as c0f9599
git cherry-pick af474e3

There you go! (Of course, revision IDs will be different)

eftshift0
  • 26,375
  • 3
  • 36
  • 60
  • eftshift0, this worked like charm. I did not know about `checkout --orphan` option. Thanks for this. – bantya Aug 12 '21 at 15:50