我如何用特定的版本克隆git存储库,就像我通常在Mercurial中做的那样:

hg clone -r 3 /path/to/repository

当前回答

在一个特定的分支或标签上只克隆一个特定的提交:

git clone --depth=1 --branch NAME https://github.com/your/repo.git

不幸的是,NAME只能是分支名称或标记名称(不能提交SHA)。

省略——depth标志来下载整个历史记录,然后签出分支或标记:

git clone --branch NAME https://github.com/your/repo.git

这适用于最新版本的git(我使用2.18.0版本)。

其他回答

不需要下载整个历史,也不需要调用git init:

git clone --depth=1 URL
git fetch --depth=1 origin SHA1
git checkout SHA1
git branch -D @{-1}  # if you want to tidy up the fetched branch

这有缺点,对CB百利的回答是,你仍然会下载1个不必要的修订。但从技术上讲,它是一个git克隆(OP想要的),并且它不强制您下载某个分支的整个历史。

DR -只需在源存储库中针对您想要克隆到的提交创建一个标记,并在fetch命令中使用该标记。您可以稍后从原始回购中删除标记以进行清理。

好吧,现在已经是2014年了,看起来查尔斯·贝利2010年的答案已经过时了,而且大多数(所有?)其他答案都涉及克隆,许多人都希望避免克隆。

下面的解决方案实现了OP和其他许多人正在寻找的东西,这是一种创建存储库副本(包括历史记录)的方法,但仅限于特定的提交。

以下是我在git 2.1.2版本中使用的命令,用于克隆一个本地回购(即。在另一个目录中的存储库)到某一点:

# in the source repository, create a tag against the commit you want to check out
git tag -m "Temporary tag" tmptag <sha1>

# create a new directory and change into that directory
cd somewhere_else;mkdir newdir;cd newdir

# ...and create a new repository
git init

# add the source repository as a remote (this can be a URL or a directory)
git remote add origin /path/to/original/repo

# fetch the tag, which will include the entire repo and history up to that point
git fetch origin refs/tags/tmptag

# reset the head of the repository
git reset --hard FETCH_HEAD

# you can now change back to the original repository and remove the temporary tag
cd original_repo
git tag -d tmptag

希望这个解决方案能继续工作几年!: -)

在一个特定的分支或标签上只克隆一个特定的提交:

git clone --depth=1 --branch NAME https://github.com/your/repo.git

不幸的是,NAME只能是分支名称或标记名称(不能提交SHA)。

省略——depth标志来下载整个历史记录,然后签出分支或标记:

git clone --branch NAME https://github.com/your/repo.git

这适用于最新版本的git(我使用2.18.0版本)。

对于单个文件,当提交号已知时,可以使用wget onliner:

wget https://raw.githubusercontent.com/torvalds/linux/896066ee1cf4d653057dac4e952f49c96ad16fa7/README

克隆一个git存储库,恰当地说,就是克隆整个存储库:没有办法只选择一个修订版本来克隆。然而,一旦你执行了git克隆,你可以通过执行checkout <rev>来检出一个特定的修订。