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

后端 未结 21 2615
慢半拍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 08:52

    The following bash function will change the time of any commit on the current branch.

    Be careful not to use if you already pushed the commit or if you use the commit in another branch.

    # 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"
    }
    

提交回复
热议问题