Home > Software engineering >  How to recreate git commit history but with applying pre-commit hook?
How to recreate git commit history but with applying pre-commit hook?

Time:10-27

I'm trying to rewrite git repository history and apply new pre-commit hook:

  1. Take every commit
  2. Apply pre-commit hook
  3. Keep the original metadata (author, date, message)
  4. Resolve conflicts manually, if any (the hook can alter the commit)
  5. Commit to a new repo

The end state is a new repo with a different commit history.

What I already found:

  • cherry-pick doesn't run pre-commit hook.
  • I can do
git cherry-pick --no-commit
git commit --no-edit

But it doesn't preserve the commit date. Also, not sure how to do that for each commit in history (unless I write a e.g. Python script for that).

Any ideas on how to do that efficiently?

CodePudding user response:

Use the --exec flag to git rebase, possibly with a custom GIT_SEQUENCE_EDITOR to skip the interactive prompt with the pick list. So something like:

GIT_SEQUENCE_EDIT=cat git rebase --root --exec .git/hooks/pre-commit

This will add exec .git/hooks/pre-commit after every pick <commit> in the pick list. If the pre-commit hooks fails, that will interrupt the rebase:

Executing: .git/hooks/pre-commit
warning: execution failed: .git/hooks/pre-commit
You can fix the problem, and then run

  git rebase --continue

You can manually resolve the issues, and then git rebase --continue.

  • Related