使用这个 git 命令,我可以获取远程存储库的所有可用标签,而无需克隆它:
git ls-remote --tags https://github.com/blender/blender.git
我想用
libgit2
复制这个。
我可以使用
git_tag_list
(https://libgit2.org/libgit2/#HEAD/group/tag/git_tag_list) 来获取标签列表,但它需要一个 git_repository
对象。我可以使用 git_repository_open
创建一个 git_repository
对象,但这只有在存储库已被克隆并存在于本地磁盘上时才有效。我似乎找不到任何方法来使用远程存储库 URL 创建 git_repository
对象。
libgit2 示例有一个
ls-remote
命令的实现,所以它一定是可能的:
static int use_remote(git_repository *repo, char *name)
{
git_remote *remote = NULL;
int error;
const git_remote_head **refs;
size_t refs_len, i;
git_remote_callbacks callbacks = GIT_REMOTE_CALLBACKS_INIT;
/* Find the remote by name */
error = git_remote_lookup(&remote, repo, name);
if (error < 0) {
error = git_remote_create_anonymous(&remote, repo, name);
if (error < 0)
goto cleanup;
}
/**
* Connect to the remote and call the printing function for
* each of the remote references.
*/
callbacks.credentials = cred_acquire_cb;
error = git_remote_connect(remote, GIT_DIRECTION_FETCH, &callbacks, NULL, NULL);
if (error < 0)
goto cleanup;
/**
* Get the list of references on the remote and print out
* their name next to what they point to.
*/
if (git_remote_ls(&refs, &refs_len, remote) < 0)
goto cleanup;
for (i = 0; i < refs_len; i++) {
char oid[GIT_OID_SHA1_HEXSIZE + 1] = {0};
git_oid_fmt(oid, &refs[i]->oid);
printf("%s\t%s\n", oid, refs[i]->name);
}
cleanup:
git_remote_free(remote);
return error;
}
/** Entry point for this command */
int lg2_ls_remote(git_repository *repo, int argc, char **argv)
{
int error;
if (argc < 2) {
fprintf(stderr, "usage: %s ls-remote <remote>\n", argv[-1]);
return EXIT_FAILURE;
}
error = use_remote(repo, argv[1]);
return error;
}
不幸的是,这个命令还需要一个
git_repository
对象,所以我有点不知所措。如果不先克隆,这目前是不可能的吗?
您可以利用
git_remote_create_anonymous()
创建远程对象并获取标签列表,而无需在本地克隆存储库。
这里是示例代码:
#include <git2.h>
#include <iostream>
#include <string>
int main() {
// Initialize the libgit2 library
git_libgit2_init();
git_remote *remote = nullptr;
const char *url = "https://github.com/libgit2/libgit2.git";
// Create an anonymous remote object with the specified URL
git_remote_create_anonymous(&remote, nullptr, url);
// Initialize the remote callbacks structure
git_remote_callbacks callbacks = GIT_REMOTE_CALLBACKS_INIT;
// Connect to the remote repository
git_remote_connect(remote, GIT_DIRECTION_FETCH, &callbacks, nullptr, nullptr);
const git_remote_head **refs;
size_t refs_len;
// Get the list of remote references
git_remote_ls(&refs, &refs_len, remote);
// Iterate through the references and print the tags
for (size_t i = 0; i < refs_len; ++i) {
std::string ref_name(refs[i]->name);
if (ref_name.find("refs/tags/") == 0) {
std::cout << "Tag: " << ref_name.substr(10) << std::endl;
}
}
// Free the resources and shut down the libgit2 library
git_remote_free(remote);
git_libgit2_shutdown();
return 0;
}
此代码将帮助您获取远程存储库的标签列表,而无需在本地克隆它。请注意,此代码仅检索可公开访问的存储库的标签,因为我们不提供身份验证功能。