git rebase - add original commit hash to commit messages

So, here is my solution:

git rebase <branch> \
-ix "git rev-parse --short HEAD > tmp &&  \
echo 'from: $<branch_shortid>' > tmp && \
git commit --amend -F tmp"

Make sure that branch_shortid is correct and was generated on the branch you wish to rebase content from.

Disclaimer: I am not sure if this will work in all cases, esspecially if you have some strange or complicated referencing systems going on. I ran this on a very simple git repo generated by:

$ git init 
$ echo "a" > a.txt && git add . && git commit -m "first commit"
$ git checkout -b "feature1" 
$ echo "b" > b.txt && git add . && git commit -m "second commit"
$ echo "c" > c.txt && git add . && git commit -m "third commit"
$ feature1id=$(git rev-parse --short HEAD)
$ git checkout master
$ git rebase feature1 \
  -ix "git rev-parse --short HEAD > tmp &&  \
  echo 'from: $feature1_id' > tmp && \
  git commit --amend -F tmp"

Here is corresponding output:

enter image description here


Discussion:

As pointed out earlier, I think that you using git reflog is a better solution for investigating from which commit on which branch was merged onto the desired one.

The point of rebasing is to apply commits onto the top of another branch, as if that were commit structure in the first place:

Rebasing produces a linear history.


It ain't pretty but it get's the job done;

git rebase --exec='git log --pretty="format:%B" -n 1 > tmp;
    grep -o "\w\{40\}" .git/rebase-merge/done | tail -n 1 >> tmp; 
    git commit --amend -F tmp; 
    rm tmp;' master

To explain each part of the --exec script;

  • Put the commit message we just completed into tmp;
  • Grab the hash of the commit we just rebased from .git/rebase-merge/done and append it to tmp.
  • Ammend the commit we just made using tmp as the commit message.
  • Remove the tmp file.

I'm sure you can hack that into a format you'll find pleasing.

Log of original work;

commit 1ebdfc2fd26b0eed9f131197dc3274f6d5048e97
Author: Adam
Date:   Thu Jan 24 16:33:09 2019 +0000

    Content C

commit 632f1a4e1ab5d47c9e4c3ca3abd02a207a5dda09
Author: Adam
Date:   Thu Jan 24 16:33:06 2019 +0000

    Content B

commit a7e0d1eb2e412ec51865ccd405ea513c7677c150
Author: Adam
Date:   Thu Jan 24 16:33:04 2019 +0000

    Content A

Log of rebased work;

commit 79d7ece06185b21631248a13416e5ca5c23e55b2
Author: Adam
Date:   Thu Jan 24 16:33:09 2019 +0000

    Content C
    1ebdfc2fd26b0eed9f131197dc3274f6d5048e97

commit d2fe6267165fa05f5fe489a6321b0b1742d1a74c
Author: Adam
Date:   Thu Jan 24 16:33:06 2019 +0000

    Content B
    632f1a4e1ab5d47c9e4c3ca3abd02a207a5dda09

commit da72fab2008e74f6a8e247f93619943805ebf86e
Author: Adam
Date:   Thu Jan 24 16:33:04 2019 +0000

    Content A
    a7e0d1eb2e412ec51865ccd405ea513c7677c150

Tags:

Git

Rebase