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


当前回答

使用带有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'

其他回答

下面是一个方便的别名,它将上一次提交的提交时间和作者时间都更改为date接受的时间——date:

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

使用方法:git cd <date_arg>

例子:

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

编辑: 下面是一个更自动化的版本,它检查索引是否干净(没有未提交的更改),并重用最后的提交消息,否则会失败(万无一失):

[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!"

如果你想在标准的Windows命令行中执行接受的答案(https://stackoverflow.com/a/454750/72809),你需要以下命令:

git filter-branch -f --env-filter "if [ $GIT_COMMIT = 578e6a450ff5318981367fe1f6f2390ce60ee045 ]; then export GIT_AUTHOR_DATE='2009-10-16T16:00+03:00'; export GIT_COMMITTER_DATE=$GIT_AUTHOR_DATE; fi"

注:

可以将命令拆分为多行(Windows支持用斜杠符号^拆分行),但我没有成功。 您可以编写ISO日期,从而节省大量查找合适的星期几的时间,避免在元素顺序方面遇到麻烦。 如果您希望Author和Committer日期相同,则只需引用前面设置的变量即可。

非常感谢Colin Svingen的博客文章。尽管他的代码对我不起作用,但它帮助我找到了正确的解决方案。

每次提交都与两个日期相关联,提交者日期和作者日期。你可以用以下方法查看这些日期:

git log --format=fuller

如果你想改变最近6次提交的作者日期和提交者日期,你可以简单地使用交互式rebase:

git rebase -i HEAD~6

.

pick c95a4b7 Modification 1
pick 1bc0b44 Modification 2
pick de19ad3 Modification 3
pick c110e7e Modification 4
pick 342256c Modification 5
pick 5108205 Modification 6

# Rebase eadedca..5108205 onto eadedca (6 commands)
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
# d, drop = remove commit

对于您想要更改日期的所有提交,将pick替换为edit(或只是e),然后保存并退出编辑器。

你现在可以通过指定作者日期和ISO-8601格式的提交日期来修改每次提交:

GIT_COMMITTER_DATE="2017-10-08T09:51:07" git commit --amend --date="2017-10-08T09:51:07"

第一个日期是提交日期,第二个日期是作者日期。

然后进行下一次提交:

git rebase --continue

重复该过程,直到修改所有提交。用git状态检查你的进程。

除了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

两者都可以

如果是上一次提交。

git rebase  -i HEAD~2
git commit --amend --date=now

如果你已经推送到orgin并且可以强制使用:

git push --force 

如果你不能强制推送,如果它被推送,你就不能改变提交!.