Search code examples
gitgit-commitgit-rewrite-history

git mimic old commit from other repository


Why

At our company we started using some open source code and started patching it. I now want to make these changes public, so I want to apply these changes with the correct authors and author dates (I don't want to take credit for the work I didn't do).

Question

  • in company-repo, I have commit 123456789 which I want to mimic
  • in new-repo, I prepared a commit (using git add -p).

Now I want to create a commit which mimics commit 123456789 from company-repo, but create this commit inside new-repo.

ideas

  • git commit -C can take the git commit message from another commit, but this fails (could not lookup commit)
  • since this is across two different repositories maybe creating a patch? But since filenames have changed that will be complicated
  • just parsing the information needed and reusing? What should be copied? Timestamps, commit message, others?

Solution

  • I don't know if there is an easier way to do this, but I would parse the author, message and timestamp and reuse those when committing.

    Set these two variables correctly:

    OLDREPO=/path/to/company-repo
    HASH=123456789 # hash of commit to mimic
    

    then you can extract the values from the old commit:

    DATE=$(git --git-dir=$OLDREPO/.git/ show --no-patch --no-notes --pretty='%cd' $HASH)
    AUTHOR=$(git --git-dir=$OLDREPO/.git/ show --no-patch --no-notes --pretty='%an <%ae>' $HASH)
    MESSAGE="$(git --git-dir=$OLDREPO/.git/ show --no-patch --no-notes --pretty='%B' $HASH)"
    

    and use them for your new commit:

    git commit --author="$AUTHOR" --date="$DATE" -m "$MESSAGE"
    

    NOTE: I did not set GIT_COMMITTER_DATE on purpose. Technically the commit is created today, while the author wrote his code a long time ago.