尊敬的社区成员:
我在一个代码分析系统上工作,想用Dulwich模块替换对CLI Git应用程序的调用。作为第一步,我需要将"git ls-files“命令替换为Dulwich等效项。我是通过以下方式完成的:
import os
import stat
import subprocess
from tempfile import TemporaryDirectory
from dulwich import porcelain
from dulwich.repo import Repo
from dulwich.objects import Commit, Tree
def _flatten_git_tree(r, object_sha, prefix=b'', sep=b'/'):
result=[]
git_object=r.get_object(object_sha)
if git_object.type_name==b'tree':
for item in git_object.iteritems():
if stat.S_ISREG(item.mode):
result.append(sep.join([prefix, item.path]))
if stat.S_ISDIR(item.mode):
result.extend(_flatten_git_tree(r, item.sha, prefix+sep+item.path, sep))
if git_object.type_name==b'commit':
result.extend(_flatten_git_tree(r, git_object.tree, prefix, sep))
return result
def _run_git_cmd(git_arguments):
return subprocess.Popen(git_arguments, stdout=subprocess.PIPE).communicate()[0]
with TemporaryDirectory() as temp_dir:
git_clone_url=r"https://github.com/dulwich/dulwich.git"
repo=porcelain.clone(git_clone_url, temp_dir, checkout=True)
dulwich_ls_files=_flatten_git_tree(repo, repo.head())
git_ls_files=_run_git_cmd(['git', '-C', os.path.join(temp_dir, 'dulwich'), 'ls-files'])
git_ls_files=git_ls_files.decode('utf-8').splitlines()
assert len(dulwich_ls_files)==len(git_ls_files)
Quick assert显示输出不同。可能的原因是什么?
在@jelmer的帮助下回答我自己的问题。问题的原因在于我所评论的那一行。现在输出匹配。
import os
import subprocess
from tempfile import TemporaryDirectory
from dulwich import porcelain
from dulwich.repo import Repo
def _run_git_cmd(git_arguments):
return subprocess.Popen(git_arguments, stdout=subprocess.PIPE).communicate()[0]
with TemporaryDirectory() as temp_dir:
git_clone_url=r"https://github.com/dulwich/dulwich.git"
repo=porcelain.clone(git_clone_url, temp_dir)
dulwich_ls_files=[path.decode('utf-8') for path in sorted(repo.open_index())]
#git_ls_files=_run_git_cmd(['git', '-C', os.path.join(temp_dir, 'dulwich'), 'ls-files'])
git_ls_files=_run_git_cmd(['git', '-C', temp_dir, 'ls-files'])
git_ls_files=git_ls_files.decode('utf-8').splitlines()
print(len(dulwich_ls_files), len(git_ls_files))
发布于 2018-06-19 18:16:30
如下所示:
from dulwich.repo import Repo
r = Repo('.')
index = r.open_index()
for path in sorted(index):
print(path)
https://stackoverflow.com/questions/50912696
复制相似问题