如何修改现有的、未推送的提交?描述一种修改尚未推送到上游的先前提交消息的方法。新消息继承原始提交的时间戳。这似乎合乎逻辑,但有没有办法也重新设定时间呢?


当前回答

除了Matt Montag的回答:

如果需要在rebase命令后将时间戳重置为当前时间

git rebase -i HEAD~2

您可以使用这些选项之一

pick 4ca564e Do something
exec git commit --amend --no-edit --date=now
pick 1670583 Add another thing
exec git commit --amend --no-edit --reset-author

两者都可以

其他回答

我为此写了一个脚本和Homebrew包。超级容易安装,你可以在GitHub PotatoLabs/git-redate页面上找到它。

语法:

git redate -c 3

你只需要运行git redate,你就可以在vim中编辑最近5次提交的所有日期(还有一个-c选项来决定你想要返回多少次提交,它默认是5)。如果你有任何问题,评论或建议,请告诉我!

使用带有env过滤器的git filter-branch,该过滤器为您希望修复的提交的特定散列设置GIT_AUTHOR_DATE和GIT_COMMITTER_DATE。

这将使该哈希值和所有未来哈希值无效。

例子:

如果你想改变提交119f9ecf58069b265ab22f1f97d2b648faf932e0的日期,你可以这样做:

git filter-branch --env-filter \
    'if [ $GIT_COMMIT = 119f9ecf58069b265ab22f1f97d2b648faf932e0 ]
     then
         export GIT_AUTHOR_DATE="Fri Jan 2 21:38:53 2009 -0800"
         export GIT_COMMITTER_DATE="Sat May 19 01:01:01 2007 -0700"
     fi'

在一个命令中处理所有这些建议的更好方法是

LC_ALL=C GIT_COMMITTER_DATE="$(date)" git commit --amend --no-edit --date "$(date)"

这将把最后一次提交的提交日期和作者日期设置为“现在”。

如果你想获得另一个提交的确切日期(假设你重新编辑了一个提交,并希望它具有原始的预重新编辑版本的日期):

git commit --amend --date="$(git show -s --format=%ai a383243)"

这将更正HEAD提交的日期,使其与提交a383243的日期完全一致(如果有歧义,则包括更多数字)。它还会弹出一个编辑器窗口,以便您可以编辑提交消息。

这是作者日期,这是你通常关心的-查看提交者日期的其他答案。

下面的bash函数将更改当前分支上任何提交的时间。

如果您已经推送了提交,或者在另一个分支中使用提交,请注意不要使用。

# rewrite_commit_date(commit, date_timestamp)
#
# !! Commit has to be on the current branch, and only on the current branch !!
# 
# Usage example:
#
# 1. Set commit 0c935403 date to now:
#
#   rewrite_commit_date 0c935403
#
# 2. Set commit 0c935403 date to 1402221655:
#
#   rewrite_commit_date 0c935403 1402221655
#
rewrite_commit_date () {
    local commit="$1" date_timestamp="$2"
    local date temp_branch="temp-rebasing-branch"
    local current_branch="$(git rev-parse --abbrev-ref HEAD)"

    if [[ -z "$date_timestamp" ]]; then
        date="$(date -R)"
    else
        date="$(date -R --date "@$date_timestamp")"
    fi

    git checkout -b "$temp_branch" "$commit"
    GIT_COMMITTER_DATE="$date" git commit --amend --date "$date"
    git checkout "$current_branch"
    git rebase "$commit" --onto "$temp_branch"
    git branch -d "$temp_branch"
}