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


当前回答

如何编辑多个提交日期

其他答案对于编辑多个提交日期不太方便。几年之后,我又回到这个问题上来分享一个技巧。

更改最近4次提交的日期。

git rebase -i HEAD~4

编辑rebase如下,插入exec行以根据需要修改日期:

pick 4ca564e Do something
exec git commit --amend --no-edit --date "1 Oct 2019 12:00:00 PDT"
pick 1670583 Add another thing
exec git commit --amend --no-edit --date "2 Oct 2019 12:00:00 PDT"
pick b54021c Add some tests
exec git commit --amend --no-edit --date "3 Oct 2019 12:00:00 PDT"
pick e8f6653 Fix the broken thing
exec git commit --amend --no-edit --date "4 Oct 2019 12:00:00 PDT"

更新(2021年9月):

如果你想在rebase指令列表(Git 2.6+)中查看原始提交日期:

git config --add rebase.instructionFormat "[%ai] %s"

然后你会看到

pick 4f5a371f [2021-09-08 02:56:50 -0700] Add npm events
pick 67937227 [2021-09-09 03:05:42 -0700] Fixup

其他回答

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

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

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

基于theosp的答案,我写了一个名为git-cdc(用于更改日期提交)的脚本,并将其放在我的PATH中。

这个名字很重要:git-xxx在你的PATH中允许你输入:

git xxx
# here
git cdc ... 

该脚本在bash中,即使在Windows上(因为Git将从其msys环境中调用它)

#!/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"

有了它,你可以输入:

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

这将把HEAD(@~)之前提交的作者/提交日期重置为指定的日期。

git cdc @~ "2 days ago"

这将把HEAD(@~)之前提交的作者/提交日期重置为同一小时,但是是2天前。


Ilya Semenov在评论中提到:

对于OS X,您也可以安装GNU coreutils (brew install coreutils),将其添加到PATH (PATH="/usr/local/opt/coreutils/libexec/gnubin:$PATH"),然后使用"2天前"语法。

编辑作者日期和最近3次提交的提交日期:

git rebase -i HEAD~3 --committer-date-is-author-date --exec "git commit --amend --no-edit --date=now"

——exec命令附加在rebase中的每一行之后,您可以使用——date=…,投稿日期与作者日期一致。

将最后一次提交的日期设置为当前日期

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

将最后一次提交的日期设置为任意日期

GIT_COMMITTER_DATE="Mon 20 Aug 2018 20:19:19 BST" git commit --amend --no-edit --date "Mon 20 Aug 2018 20:19:19 BST"

将任意提交的日期设置为任意或当前日期

还原到之前所述的提交和停止修改:

Git rebase <commit-hash>^ -i 将pick替换为e (edit)并提交(第一个) 退出编辑器(在VIM中,ESC后跟:wq) :

GIT_COMMITTER_DATE="$(date)" git commit - modify -no-edit -date "$(date)" GIT_COMMITTER_DATE="Mon 20 Aug 2018 20:19:19 BST" git commit - modify -no-edit -date "Mon 20 Aug 2018 20:19:19 BST"

来源: https://codewithhugo.com/change-the-date-of-a-git-commit/

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

语法:

git redate -c 3

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