用dulwich以编程方式`git checkout .`

时间:2011-07-10 10:28:24

标签: python git dulwich

拥有此代码

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 .

3 个答案:

答案 0 :(得分:8)

Git状态表示已将其删除,因为该文件在工作副本中不存在,这就是检查它的原因。

看起来似乎还没有对dulwich中的高级工作副本类和函数的支持。你必须处理树木和斑点以及拆开物品。

好的,接受了挑战:我可以与德威进行基本的结账:

#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以获取更完整的代码。

答案 1 :(得分:3)

现在可以使用方法dulwich.index.build_index_from_tree() release 0.8.4开始。

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

见注释

  

擦除现有索引并且不合并内容   在一个工作的目录。仅适用于新鲜克隆

我可以使用以下代码

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)

答案 2 :(得分:0)

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