How do I make a Git commit in the past?

2020-01-24 10:08发布

I'm converting everything over to Git for my own personal use and I found some old versions of a file already in the repository. How do I commit it to the history in the correct order according the the file's "date modified" so I have an accurate history of the file?

I was told something like this would work:

git filter-branch --env-filter="GIT_AUTHOR_DATE=... --index-filter "git commit path/to/file --date " --tag-name-filter cat -- --all  

9条回答
放荡不羁爱自由
2楼-- · 2020-01-24 10:33

In my case over time I had saved a bunch of versions of myfile as myfile_bak, myfile_old, myfile_2010, backups/myfile etc. I wanted to put myfile's history in git using their modification dates. So rename the oldest to myfile, git add myfile, then git commit --date=(modification date from ls -l) myfile, rename next oldest to myfile, another git commit with --date, repeat...

To automate this somewhat, you can use shell-foo to get the modification time of the file. I started with ls -l and cut, but stat(1) is more direct

git commit --date="`stat -c %y myfile`" myfile

查看更多
看我几分像从前
3楼-- · 2020-01-24 10:41

The following is what I use to commit changes on foo to N=1 days in the past:

git add foo
git commit -m "Update foo"
git commit --amend --date="$(date -v-1d)"

If you want to commit to a even older date, say 3 days back, just change the date argument: date -v-3d.

That's really useful when you forget to commit something yesterday, for instance.

UPDATE: --date also accepts expressions like --date "3 days ago" or even --date "yesterday". So we can reduce it to one line command:

git add foo ; git commit --date "yesterday" -m "Update"
查看更多
迷人小祖宗
4楼-- · 2020-01-24 10:41

To make a commit that looks like it was done in the past you have to set both GIT_AUTHOR_DATE and GIT_COMMITTER_DATE:

GIT_AUTHOR_DATE=$(date -d'...') GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE" git commit -m '...'

where date -d'...' can be exact date like 2019-01-01 12:00:00 or relative like 5 months ago 24 days ago.

To see both dates in git log use:

git log --pretty=fuller

This also works for merge commits:

GIT_AUTHOR_DATE=$(date -d'...') GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE" git merge <branchname> --no-ff
查看更多
我想做一个坏孩纸
5楼-- · 2020-01-24 10:48

You can always change a date on your computer, make a commit, then change the date back and push.

查看更多
劳资没心,怎么记你
6楼-- · 2020-01-24 10:50

I know this question is quite old, but that's what actually worked for me:

git commit --date="10 day ago" -m "Your commit message" 
查看更多
家丑人穷心不美
7楼-- · 2020-01-24 10:50

Or just use a fake-git-history to generate it for a specific data range.

查看更多
登录 后发表回答