python - 使用 pygit2 (libgit2) 将 blob 或树添加到创建的存储库?

标签 python git libgit2

我正在尝试使用 pygit2 库。

我似乎卡在了第一步。它的文档没有解释如何创建 blob 并将其添加到树中。它主要围绕如何使用现有的 git 存储库,但我想创建一个并将 blob、提交……添加到我的存储库中。是否可以直接从文件创建 blob,或者我应该读取文件内容并设置 blob.data?

from pygit2 import Repository
from pygit2 import init_repository

bare = False
repo = init_repository('test', bare)

如何创建 blob 或树并将其添加到存储库?

最佳答案

python 绑定(bind)不允许您直接从文件创建 blob,因此您必须将文件读入内存并使用 Repository.write(pygit2.GIT_OBJ_BLOB, filecontents)创建 blob。

然后您可以使用TreeBuilder 创建树,例如

import pygit2 as g

repo = g.Repository('.')
# grab the file from wherever and store in 'contents'
oid = repo.write(g.GIT_OBJ_BLOB, contents)
bld = repo.TreeBuilder()
# attributes is whether it's a file or dir, 100644, 100755 or 040000
bld.insert('file.txt', oid, attributes)
treeoid = bld.write()

关于python - 使用 pygit2 (libgit2) 将 blob 或树添加到创建的存储库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10409378/

相关文章:

ios - 当我想将新文件提交到 git 时,如何使用 libgit2 获取 SHA 值

python - 如何生成彼此不相交的正方形(位置随机,大小相等,随机旋转)?

python - 这有可能吗?从一个python shell发送命令/对象到另一个?

Git 子分支或类似的概念

git - 如何解决已在第一个分支中删除并在第二个分支中重命名的文件的 merge 冲突?

git - 如何禁用 git gpg 签名

c++ - 有没有办法如何在 C++ 中使用 libgit2 计算远程存储库上的提交?

cmake - 如何通过 cmake 包含 libgit2

python - 正则表达式:匹配所有内容,直到 `:` 或 `(`

Python随机函数