118

是否可以浅克隆存储库中的特定提交,即深度为 1?就像是

git clone http://myrepo.git 728a4d --depth 1

获取与 SHA 提交时一样的存储库状态728a4d...

这样做的动机是避免必须克隆整个存储库,然后在我们只对特定提交时存储库的状态感兴趣时检查该特定提交。

4

4 回答 4

117

从 Git 2.5.0(需要在客户端和服务器端uploadpack.allowReachableSHA1InWant=true可用)开始,您可以在服务器端设置以启用特定 SHA1 的获取:

git init
git remote add origin <url>
git fetch --depth 1 origin <sha1>
git checkout FETCH_HEAD

请注意,我没有找到git clone直接执行此操作的语法。

于 2017-03-31T08:36:32.417 回答
30

注意:我的示例无助于通过提交哈希进行克隆,但有助于克隆标签并拥有轻量级存储库。

如果你必须在你的“克隆”中只有一个提交并且你将使用提交哈希,那么简短的回答是 NO

我使用这个命令构造(在v2.13.2.windows.1上测试)作为标签:

git clone --depth 1 git@github.com:VENDOR/REPO.git --branch 1.23.0 --single-branch

完整示例:

$ git clone --depth 1 git@github.com:Seldaek/monolog.git --branch 1.23.0 --single-branch
Cloning into 'monolog'...
remote: Counting objects: 201, done.
remote: Compressing objects: 100% (188/188), done.
remote: Total 201 (delta 42), reused 32 (delta 5), pack-reused 0
Receiving objects: 100% (201/201), 190.30 KiB | 0 bytes/s, done.
Resolving deltas: 100% (42/42), done.
Note: checking out 'fd8c787753b3a2ad11bc60c063cff1358a32a3b4'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b <new-branch-name>

$ cd monolog

.git目录大小(267K2.6M使用 full clone):

$ du -h --max-depth=0 .git
267K    .git

我想指出,--branch可以带一个标签/分支。

https://git-scm.com/docs/git-clone#git-clone---branchltnamegt

--branch还可以在结果存储库中的该提交处获取标签并分离 HEAD。

UPD

简而言之,它可以采用“refs”。您可以在这里阅读更多内容:git 错误消息“服务器不允许请求未公布的对象”是什么意思?

此外,没有以下技巧:

git fetch --depth 1 origin <COMMIT_HASH>

感谢@BenjiWiebe 指出我的错误。

于 2018-02-12T14:19:24.793 回答
7

尝试while在 bash 中使用:

git clone --depth=1 $url
i=1; while ! git show $sha1; do git fetch --depth=$((i+=1)); done

这非常慢,因为它单独获取每个提交;您可以增加增量(以批量获取提交并提高网络性能),但这仍然是一种蛮力方法。

于 2016-09-12T04:41:12.650 回答
4

直接的答案是:你不能直接使用 git clone 来做到这一点。
为什么?可以在这里找到详细的解释:为什么没有 Git 克隆特定的提交选项?

你还能做什么?

如何将存储库克隆到特定提交?(完全克隆)

# Create empty repository to store your content
git clone <url>
git reset <sha-1> --hard

更多信息:

如何克隆单个分支?

git clone <url> --branch <branch_name> --single-branch <folder_name>

如何仅从给定分支克隆最新提交?

git clone <url> --depth=1 --branch <branch_name> --single-branch <folder_name>

如何浅克隆深度为 1 的特定提交?

正如@sschuberth 评论的那样:--depth暗示--single-branch.

使用 fetch 命令代替克隆:

# fetch a commit (or branch or tag) of interest
# In this case you will have the full history of this commit
git fetch origin <sha1>
于 2015-07-07T21:08:44.660 回答