GitPython 在内部使用关键字参数转换:
def transform_kwarg(self, name: str, value: Any, split_single_char_options: bool) -> List[str]:
if len(name) == 1:
if value is True:
return ["-%s" % name]
elif value not in (False, None):
if split_single_char_options:
return ["-%s" % name, "%s" % value]
else:
return ["-%s%s" % (name, value)]
else:
if value is True:
return ["--%s" % dashify(name)]
elif value is not False and value is not None:
return ["--%s=%s" % (dashify(name), value)]
return []
生成的命令部分列表将被传递给subprocess.Popen
,因此您不需要在repo URL中添加--single-branch
。如果添加了该参数,将会向Popen传递一个奇怪的列表。例如:
['-v', '--branch=my-branch', 'https://github.com/me/my-project.git --single-branch', '/tmp/clone/here']
然而,有了这个新信息,你可以通过使用
kwargs
传递任何你喜欢的
git
CLI flags。你可能会问自己,“如何将破折号传递给像
single-branch
这样的关键字?”在Python中是不行的。你将在上面的代码中看到一个
dashify
函数,它将任何标志从
single_branch=True
转换为
single-branch
,然后转换为
--single-branch
。
完整示例:
以下是一个有用的示例,使用GitHub的个人访问令牌克隆单个浅层分支:
repo_url = "https://github.com/me/private-project.git"
branch = "wip-branch"
credentials = base64.b64encode(f"{GHE_TOKEN}:".encode("latin-1")).decode("latin-1")
Repo.clone_from(
url=repo_url,
c=f"http.{repo_url}/.extraheader=AUTHORIZATION: basic {credentials}",
single_branch=True,
depth=1,
to_path=f"/clone/to/here",
branch=branch,
)
Popen
接收到的命令列表如下:
['git', 'clone', '-v', '-c', 'http.https://github.com/me/private-project.git/.extraheader=AUTHORIZATION: basic XTE...UwNTo=', '--single-branch', '--depth=1', '--bare', '--branch=wip-branch', 'https://github.com/me/private-project.git', '/clone/to/here']
(提示:请不要将您的个人令牌作为URL的一部分发送,@符号之前。)
clone -b
的作用是,在克隆整个仓库后,检出特定的分支而不是默认分支(通常为master
)。所以,为什么不在克隆后直接进行分支检出,而要寻找一些奇怪的东西呢? - Mark Adelsbergergit clone --single-branch
- Michał Politowskiclone -b
并没有克隆特定的分支,它只是检出特定的分支。 - Mark Adelsberger