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

后端 未结 21 2614
慢半拍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:44

    Building on theosp's answer, I wrote a script called git-cdc (for change date commit) that I put in my PATH.

    The name is important: git-xxx anywhere in your PATH allows you to type:

    git xxx
    # here
    git cdc ... 
    

    That script is in bash, even on Windows (since Git will be calling it from its msys environment)

    #!/bin/bash
    # commit
    # date YYYY-mm-dd HH:MM:SS
    
    commit="$1" datecal="$2"
    temp_branch="temp-rebasing-branch"
    current_branch="$(git rev-parse --abbrev-ref HEAD)"
    
    date_timestamp=$(date -d "$datecal" +%s)
    date_r=$(date -R -d "$datecal")
    
    if [[ -z "$commit" ]]; then
        exit 0
    fi
    
    git checkout -b "$temp_branch" "$commit"
    GIT_COMMITTER_DATE="$date_timestamp" GIT_AUTHOR_DATE="$date_timestamp" git commit --amend --no-edit --date "$date_r"
    git checkout "$current_branch"
    git rebase  --autostash --committer-date-is-author-date "$commit" --onto "$temp_branch"
    git branch -d "$temp_branch"
    

    With that, you can type:

    git cdc @~ "2014-07-04 20:32:45"
    

    That would reset author/commit date of the commit before HEAD (@~) to the specified date.

    git cdc @~ "2 days ago"
    

    That would reset author/commit date of the commit before HEAD (@~) to the same hour, but 2 days ago.


    Ilya Semenov mentions in the comments:

    For OS X you may also install GNU coreutils (brew install coreutils), add it to PATH (PATH="/usr/local/opt/coreutils/libexec/gnubin:$PATH") and then use "2 days ago" syntax.

提交回复
热议问题