2010-03-18 13 views

risposta

7

Dopo aver fatto

from git import Git 
g = Git() 

(e possibilmente qualche altro comando per avviare g nel repository che ti interessa) tutte le richieste di attributo su g sono più o meno trasformate in una chiamata di git attr *args.

Pertanto:

g.checkout("mybranch") 

dovrebbe fare quello che vuoi.

g.branch() 

elencherà i rami. Tuttavia, si noti che questi sono comandi di livello molto basso e restituiranno il codice esatto restituito dagli eseguibili git. Pertanto, non aspettarti una bella lista. Sarò solo una stringa di più righe e con una riga con un asterisco come primo carattere.

Potrebbe esserci un modo migliore per farlo nella libreria. Ad esempio, nel repo.py è un comando speciale active_branch. Dovrai passare attraverso la fonte un po 'e cercare te stesso.

+0

quando ho eseguito r = Git.clone ("git ...") r.checkout ("sviluppare") non funziona .. AttributeError: 'str' oggetto non ha attributo 'cassa' – Mike

+0

ok sembra che ho bisogno di eseguire ag = Git ("dir ") quindi posso effettuare il checkout – Mike

+0

Potrebbe essere. Ho appena clonato con 'g' e poi ha funzionato. – Debilski

4

Per elencare i rami attualmente è possibile utilizzare:

from git import Repo 
r = Repo(your_repo_path) 
repo_heads = r.heads # or it's alias: r.branches 

r.heads rendimenti git.util.IterableList (eredita dopo list) di git.Head oggetti, in modo da poter:

repo_heads_names = [h.name for h in repo_heads] 

E alla cassa ad es. master:

repo_heads['master'].checkout() 
# you can get elements of IterableList through it_list['branch_name'] 
# or it_list.branch_name 

modulo menzionato nella questione GitPython che moved da gitorious a Github.

1

Ho avuto un problema simile. Nel mio caso volevo solo elencare i rami remoti tracciati localmente. Questo ha funzionato per me:

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) 

Nel caso in cui sono necessarie tutte le filiali remote, preferirei correre direttamente git:

def get_all_branches(path): 
    cmd = ['git', '-C', path, 'branch', '-a'] 
    out = subprocess.check_output(cmd, stderr=subprocess.STDOUT) 
    return out 
+1

Se hai già un'istanza di Repo, puoi chiamare i comandi git direttamente come: '' 'repo.git.branch ('- a')' '' – dusktreader

0

Giusto per rendere evidente - per ottenere un elenco di filiali remote dagli attuali directory repo:

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)