How is it possible to use raw_input() in a Python Git hook?

后端 未结 2 657
面向向阳花
面向向阳花 2020-12-30 04:55

I am writing a pre-commit hook for Git that runs pyflakes and checks for tabs and trailing spaces in the modified files (code on Github). I would like to make it possible to

相关标签:
2条回答
  • 2020-12-30 05:27

    You could use:

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

    git commit calls 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
    

    Looking inside /proc/21802/fd (on this linux box) shows the state of the file descriptors for the process with PID 21802 (the pre-commit process):

      /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
    

    Thus, pre-commit was spawned with sys.stdin pointing at /dev/null. sys.stdin = open('/dev/tty') redirects sys.stdin to an open filehandle from which raw_input can read.

    0 讨论(0)
  • 2020-12-30 05:29

    In shell you can:

    read ANSWER < /dev/tty
    
    0 讨论(0)
提交回复
热议问题