如何将浅表克隆推到新的仓库?

时间:2018-06-22 16:32:21

标签: git

我希望摆脱很多回购协议的旧历史,所以我做了一个浅表克隆,仅获得了最后50次提交:

git clone --depth=50 https://my.repo

这行得通,但是当我创建一个新的Gitlab存储库并尝试将其推送时,我得到一个错误:

git remote remove origin
git remote add origin https://my.repo
git push -u origin --all
[...]
 ! [remote rejected] master -> master (shallow update not allowed)

但是我只希望这50次提交成为我新回购协议的历史记录。我怎么能告诉git它应该只将这50次提交作为新仓库中的唯一提交?

2 个答案:

答案 0 :(得分:4)

这就是我最终要做的-效果很好。请注意,我正在从旧主机(Bitbucket)移到新主机(Gitlab)。我的评论位于命令上方:

# First, shallow-clone the old repo to the depth we want to keep
git clone --depth=50 https://...@bitbucket.org/....git

# Go into the directory of the clone
cd clonedrepo

# Once in the clone's repo directory, remove the old origin
git remote remove origin

# Store the hash of the oldest commit (ie. in this case, the 50th) in a var
START_COMMIT=$(git rev-list master|tail -n 1)

# Checkout the oldest commit; detached HEAD
git checkout $START_COMMIT

# Create a new orphaned branch, which will be temporary
git checkout --orphan temp_branch

# Commit the initial commit for our new truncated history; it will be the state of the tree at the time of the oldest commit (the 50th)
git commit -m "Initial commit"

# Now that we have that initial commit, we're ready to replay all the other commits on top of it, in order, so rebase master onto it, except for the oldest commit whose parents don't exist in the shallow clone... it has been replaced by our 'initial commit'
git rebase --onto temp_branch $START_COMMIT master

# We're now ready to push this to the new remote repo... add the remote...
git remote add origin https://gitlab.com/....git

# ... and push.  We don't need to push the temp branch, only master, the beginning of whose commit chain will be our 'initial commit'
git push -u origin master

在那之后,我做了一个新仓库的新克隆,我只得到了master分支,其中包含最近的50次提交-正是我想要的! :-)提交历史记录已从250MB增加到50MB。哇!

答案 1 :(得分:0)

您不能将浅表克隆推送到新的遥控器中。您必须先unshallow个克隆。使用--unshallow参数从旧的远程计算机进行抓取:

git fetch --unshallow old

,您应该可以推送到新的遥控器。请注意,您需要先添加回旧的遥控器才能从中获取。

那不是你想要的。要从完整克隆中删除历史记录,您需要使用git rebase有效删除旧历史记录。还有其他方法,但是由于您只希望最后50次提交,因此这是最简单的解决方案。假设master分支:

git rebase --onto master~y master~x master

其中x是要保留的第一次提交的编号,而y是要删除的第一次提交的编号。此时,您可以仅保留您要保留的历史记录到新遥控器。请注意,您将需要自己在git log中枚举提交编号,因为它需要一个索引(从1开始)而不是提交哈希。

请注意,因为重写历史记录在Git中可能是危险的事情,并且还需要考虑其他含义。除非您也要删除旧的历史记录,否则请确保不要将更改推送到旧的远程记录。

来源:https://www.clock.co.uk/insight/deleting-a-git-commit