Can GIT_COMMITTER_DATE be customized inside a git hook?

ぃ、小莉子 提交于 2019-12-01 19:23:11

问题


I'd like to manually control the git commit timestamp so that my GIT_COMMITTER_DATE always matches the GIT_AUTHOR_DATE. I've seen many solutions using filter-branch to rewrite history, but I'd rather be proactive about this and put the logic in a git hook so that it always matches going forward.

But I find that while these variables work fine if defined in the environment where git is invoked, they do not seem to have any effect when they are defined inside the pre-commit git hook. Eg:

# this works if run directly on cmd line, but not inside the pre-commit hook
export GIT_AUTHOR_DATE='Mon, 11 Aug 2014 11:25:16 -0400'
export GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"

Is there any way to dynamically adjust these values inside a git hook so that commits automatically have the desired timestamps? I'm on git version 1.8.5.2


回答1:


post-commit hook + git commit --amend

This is not super elegant, but it seems to work and sets both committer and author date:

.git/hooks/post-commit

#!/usr/bin/env bash
if [ -z "${GIT_COMMITTER_DATE:-}" ]; then
  d="$(date --iso-8601=seconds)"
  GIT_COMMITTER_DATE="$d" git commit --amend --date "$d" --no-edit
fi

Don't forget to:

chmod .git/hooks/post-commit

We check for GIT_COMMITTER_DATE to prevent it from entering into an infinite commit loop, and it also skips the hook if the user is already passing a specific time.

Here is a more sophisticated example that uses the date from previous commits through git log and date manipulations: Can I hide commits' time when I push to GitHub?

Remember that the committer date still leaks on git rebase, but that can be solved with a post-rewrite hook: git rebase without changing commit timestamps

Then there is also git am, which can be solved with --committer-date-is-author-date as mentioned at: git rebase without changing commit timestamps

The --amend --date part was asked at: Update git commit author date when amending

You could also set that to a global hook: Applying a git post-commit hook to all current and future repos but core.hooksPath prevents local hooks from running at all which might be a problem.

Tested on Git 2.19.



来源:https://stackoverflow.com/questions/32699631/can-git-committer-date-be-customized-inside-a-git-hook

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!