How can one change the timestamp of an old commit in Git?

后端 未结 21 2625
慢半拍i
慢半拍i 2020-11-22 08:36

The answers to How to modify existing, unpushed commits? describe a way to amend previous commit messages that haven\'t yet been pushed upstream. The new messages inherit t

21条回答
  •  臣服心动
    2020-11-22 09:06

    Here is a convenient alias that changes both commit and author times of the last commit to a time accepted by date --date:

    [alias]
        cd = "!d=\"$(date -d \"$1\")\" && shift && GIT_COMMITTER_DATE=\"$d\" \
                git commit --amend --date \"$d\""
    

    Usage: git cd

    Examples:

    git cd now  # update the last commit time to current time
    git cd '1 hour ago'  # set time to 1 hour ago
    

    Edit: Here is a more-automated version which checks that the index is clean (no uncommitted changes) and reuses the last commit message, or fails otherwise (fool-proof):

    [alias]
        cd = "!d=\"$(date -d \"$1\")\" && shift && \
            git diff-index --cached --quiet HEAD --ignore-submodules -- && \
            GIT_COMMITTER_DATE=\"$d\" git commit --amend -C HEAD --date \"$d\"" \
            || echo >&2 "error: date change failed: index not clean!"
    

提交回复
热议问题