このモジュールにリモート/ローカルブランチをチェックアウトまたは一覧表示するオプションが表示されません:https ://gitpython.readthedocs.io/en/stable/
6 に答える
使用できるブランチを一覧表示するには、次のようにします。
from git import Repo
r = Repo(your_repo_path)
repo_heads = r.heads # or it's alias: r.branches
r.heads
オブジェクトを返すgit.util.IterableList
(継承するlist
)git.Head
ので、次のことができます。
repo_heads_names = [h.name for h in repo_heads]
そしてチェックアウトするために例えば。master
:
repo_heads['master'].checkout()
# you can get elements of IterableList through it_list['branch_name']
# or it_list.branch_name
リモートブランチを印刷したいだけの場合:
# Execute from the repository root directory
repo = git.Repo('.')
remote_refs = repo.remote().refs
for refs in remote_refs:
print(refs.name)
あなたがした後
from git import Git
g = Git()
g
(そしておそらくあなたが気にかけているリポジトリを初期化する他のコマンド)すべての属性リクエストg
は多かれ少なかれ。の呼び出しに変換されますgit attr *args
。
したがって:
g.checkout("mybranch")
あなたがやりたいことをする必要があります。
g.branch()
ブランチを一覧表示します。ただし、これらは非常に低レベルのコマンドであり、git実行可能ファイルが返す正確なコードを返すことに注意してください。したがって、良いリストを期待しないでください。数行の文字列になり、1行の最初の文字にアスタリスクが付きます。
ライブラリでこれを行うためのより良い方法があるかもしれません。repo.py
たとえば、特別なコマンドactive_branch
があります。ソースを少し調べて、自分自身を探す必要があります。
同様の問題がありました。私の場合、ローカルで追跡されているリモートブランチのみを一覧表示したいと思いました。これは私のために働いた:
import git
repo = git.Repo(repo_path)
branches = []
for r in repo.branches:
branches.append(r)
# check if a tracking branch exists
tb = t.tracking_branch()
if tb:
branches.append(tb)
すべてのリモートブランチが必要な場合は、gitを直接実行することをお勧めします。
def get_all_branches(path):
cmd = ['git', '-C', path, 'branch', '-a']
out = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
return out
明確にするために、現在のリポジトリディレクトリからリモートブランチのリストを取得するには、次のようにします。
import os, git
# Create repo for current directory
repo = git.Repo(os.getcwd())
# Run "git branch -r" and collect results into array
remote_branches = []
for ref in repo.git.branch('-r').split('\n'):
print ref
remote_branches.append(ref)
基本的に、GitPythonでは、API内ではなくコマンドライン内でそれを行う方法を知っている場合は、repo.git.action("先頭に'git'と'action'を付けずにコマンド")を使用します。例:git log- -reverse => repo.git.log('--reverse')
この場合https://stackoverflow.com/a/47872315/12550269
だから私はこのコマンドを試してみます:
repo = git.Repo()
repo.git.checkout('-b', local_branch, remote_branch)
このコマンドは、新しいローカルブランチ名を作成しlocal_branch
(すでに持っている場合はrasieエラー)、リモートブランチを追跡するように設定できますremote_branch
それは非常にうまく機能します!