2011-09-15 13 views
12

Sto scrivendo un hook pre-commit per Git che esegue pyflakes e controlla le tabulazioni e gli spazi finali nei file modificati (code on Github). Vorrei rendere possibile ignorare il gancio con la richiesta di conferma da parte dell'utente come segue:Come è possibile utilizzare raw_input() in un hook Git Python?

answer = raw_input('Commit anyway? [N/y] ') 
if answer.strip()[0].lower() == 'y': 
    print >> sys.stderr, 'Committing anyway.' 
    sys.exit(0) 
else: 
    print >> sys.stderr, 'Commit aborted.' 
    sys.exit(1) 

Questo codice genera un errore:

Commit anyway? [N/y] Traceback (most recent call last): 
    File ".git/hooks/pre-commit", line 59, in ? 
    main() 
    File ".git/hooks/pre-commit", line 20, in main 
    answer = raw_input('Commit anyway? [N/y] ') 
EOFError: EOF when reading a line 

E 'anche possibile utilizzare raw_input() o un funzione simile in Git hooks e se sì, cosa sto facendo di sbagliato?

risposta

15

Si potrebbe utilizzare:

sys.stdin = open('/dev/tty') 
answer = raw_input('Commit anyway? [N/y] ') 
if answer.strip().lower().startswith('y'): 
    ... 

git commit chiamate python .git/hooks/pre-commit:

% ps axu 
... 
unutbu 21801 0.0 0.1 6348 1520 pts/1 S+ 17:44 0:00 git commit -am line 5a 
unutbu 21802 0.1 0.2 5708 2944 pts/1 S+ 17:44 0:00 python .git/hooks/pre-commit 

Guardando all'interno /proc/21802/fd (su questa casella di linux) mostra lo stato dei descrittori di file per il processo con PID 21802 (processo pre-commit):

/proc/21802/fd: 
    lrwx------ 1 unutbu unutbu 64 2011-09-15 17:45 0 -> /dev/null 
    lrwx------ 1 unutbu unutbu 64 2011-09-15 17:45 1 -> /dev/pts/1 
    lrwx------ 1 unutbu unutbu 64 2011-09-15 17:45 2 -> /dev/pts/1 
    lr-x------ 1 unutbu unutbu 64 2011-09-15 17:45 3 -> /dev/tty 
    lr-x------ 1 unutbu unutbu 64 2011-09-15 17:45 5 -> /dev/null 

Così, pre-commit è stato generato con sys.stdin che punta a /dev/null. sys.stdin = open('/dev/tty') reindirizza sys.stdin a un filehandle aperto da cui è possibile leggere raw_input.

+0

Questo funziona perfettamente. Grazie. – badzil

-1

In shell è possibile:

read ANSWER < /dev/tty 
+0

Come è questo Python? – badzil