自動化地使用dulwich進行`git checkout .`

2024-05-27 13:11:10 发布

您现在位置:Python中文网/ 问答频道 /正文

有这个密码吗

from dulwich.objects import Blob, Tree, Commit, parse_timezone
from dulwich.repo import Repo
from time import time

repo = Repo.init("myrepo", mkdir=True)
blob = Blob.from_string("my file content\n")
tree = Tree()
tree.add("spam", 0100644, blob.id)
commit = Commit()
commit.tree = tree.id


author = "Flav <foo@bar.com>"
commit.author = commit.committer = author
commit.commit_time = commit.author_time = int(time())
tz = parse_timezone('+0200')[0]
commit.commit_timezone = commit.author_timezone = tz
commit.encoding = "UTF-8"
commit.message = "initial commit"

o_sto = repo.object_store
o_sto.add_object(blob)
o_sto.add_object(tree)
o_sto.add_object(commit)

repo.refs["HEAD"] = commit.id

我在历史记录中完成了提交,但是创建的文件正在等待删除(git status是这样说的)。在

一个git checkout .修复了它。在

我的问题是:如何用dulwich编程git checkout .?在


Tags: fromimportgitaddidtreeobjecttime
3条回答

现在可以使用方法^{cd1>},因为release 0.8.4。在

它将树同时写入索引文件和文件系统(工作副本),这是一种非常基本的签出形式。在

见注释

existing index is wiped and contents are not merged in a working dir. Suiteable only for fresh clones

我可以用下面的代码让它工作

from dulwich import index, repo
#get repository object of current directory
repo = repo.Repo('.')
indexfile = repo.index_path()
#we want to checkout HEAD
tree = repo["HEAD"].tree

index.build_index_from_tree(repo.path, indexfile, repo.object_store, tree)
from dulwich.repo import Repo

repo = Repo.init('myrepo', mkdir=True)
f = open('myrepo/spam', 'w+')
f.write('my file content\n')
f.close()
repo.stage(['spam'])
repo.do_commit('initial commit', 'Flav <foo@bar.com>')

通过查看dulwich/tests/test_repository.py:371找到。德威治很强大,但不幸的是,医生有点欠缺。在

可能还需要考虑改用GitFile。在

Git status说它被删除是因为工作副本中不存在该文件,这就是为什么签出它可以修复状态。在

看起来在德威还没有对高级工作拷贝类和函数的支持。你必须处理树和斑点,并解包对象。在

好吧,接受挑战:我可以和德威进行基本结账:

#get repository object of current directory
repo = Repo('.')
#get tree corresponding to the head commit
tree_id = repo["HEAD"].tree
#iterate over tree content, giving path and blob sha.
for entry in repo.object_store.iter_tree_contents(tree_id):
  path = entry.in_path(repo.path).path
  dulwich.file.ensure_dir_exists(os.path.split(path)[0])
  with open(path, 'wb') as file:
    #write blob's content to file
    file.write(repo[entry.sha].as_raw_string()) 

它不会删除必须删除的文件,也不会关心索引等。
另请参见Mark Mikofski's github project,以获取基于此的更完整的代码。在

相关问题 更多 >