![](/img/trans.png)
[英]How to query the log of a specific git repo branch using gitpython?
[英]How to clone from specific branch from Git using Gitpython
我試圖在 python 函數中使用 GitPython 從 git 克隆一個存儲庫。 我在我的 python 函數和我的代碼片段中使用 GitPython 庫從 git 克隆,如下所示:
從 git 導入回購
Repo.clone_from(' http://user:password@github.com/user/project.git ', /home/antro/Project/')
它從主分支克隆。 如何使用 GitPython 從其他分支克隆或任何其他庫可用於從單個分支克隆? 請告訴我。
我通過在命令行中提及分支來了解克隆
git clone -b 分支http://github.com/user/project.git
只需傳遞分支名稱參數,例如:-
repo = Repo.clone_from(
'http://user:password@github.com/user/project.git',
'/home/antro/Project/',
branch='master'
)
來自toanant的回答。
這對我--single-branch
選項
repo = Repo.clone_from(
'http://user:password@github.com/user/project.git --single-branch',
'/home/antro/Project/',
branch='master'
)
對於--single-branch選項,您只需將single_branch
參數傳遞給Repo.clone_from()
方法:
Repo.clone_from(repo, path, single_branch=True, b='branch')
GitPython 在底層使用關鍵字 args 轉換:
# cmd.py
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
,所以你不希望添加--single-branch
到回購網址。 如果你這樣做,一個奇怪的列表將傳遞給 Popen。 例如:
['-v', '--branch=my-branch', 'https://github.com/me/my-project.git --single-branch', '/tmp/clone/here']
但是,有了這些新信息,您可以僅使用kwargs
傳遞您喜歡的任何git
CLI 標志。 然后你可能會問自己,“我如何將破折號傳遞給像single-branch
這樣的關鍵字?” 這在 Python 中是行不通的。 您將在上面的代碼中看到一個dashify
函數,它將任何標志從例如single_branch=True
為single-branch
,然后轉換為--single-branch
。
這是使用來自 GitHub 的個人訪問令牌克隆單個淺分支的有用示例:
repo_url = "https://github.com/me/private-project.git"
branch = "wip-branch"
# Notice the trailing : below
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']
(PSA:請不要實際上將您的個人令牌作為@
之前的 URL 的一部分發送。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.