亲爱的社区成员,
我正在开发一个代码分析系统,并想用 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)
快速断言显示输出不同。可能是什么原因?
在@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))