12

I am trying to execute a pre commit git hook in python to check if files have line lengths less than 80 chars. However i get a no such file/directory error. i am on fedora and have set the #!usr/bin/python.help would be appreciated

#!/usr/bin/env python
#-*- mode: python -*-

from subprocess import Popen, PIPE
import sys

def run(command):
    p = Popen(command.split(), stdout=PIPE, stderr=PIPE)
    p.wait()
    return p.returncode, p.stdout.read().strip().split(), p.stderr.read()


def precommit():
  _, files_modified, _= run("git diff-index --name-only HEAD")
  i=1
  for fname in files_modified:

    file = open(fname)
    while i==1:
       line = file.readline()
       if not line:
          break
       elif len(line)>80:
          print("Commit failed: Line greater than 80 characters")
          return 1
    return 0
sys.exit(precommit())
user2793781
  • 163
  • 1
  • 1
  • 6
  • Show us the `git` command you are running and the **precise** error message you receive. – Robᵩ Sep 19 '13 at 03:17
  • I run the git commit command and I get the error message no such file or directory.I run the git commit command error: cannot run .git/hooks/pre-commit: No such file or directory – user2793781 Sep 19 '13 at 03:57
  • Try running the `pre-commit` file directly: `$ ./git/hooks/pre-commit`. Do you get an error message? – Robᵩ Sep 19 '13 at 04:06
  • 1
    Please copy-paste the precise, complete error message. Don't summarize, don't retype it, just copy-paste it. – Robᵩ Sep 19 '13 at 04:07
  • bash: .git/hooks/pre-commit: /usr/bin/python^M: bad interpreter: No such file or directory When i try to run .git/hooks/pre-commit directly i get the above error message – user2793781 Sep 19 '13 at 04:12
  • 1
    1) Is python installed on your PATH? Try "which python" and confirm that it prints "/usr/bin/python". 2) Is it possible that your pre-commit file was saved with DOS line endings instead of Unix line endings? Try "file .git/hooks/pre-commit" and see if it says "CRLF line endings." – Robᵩ Sep 19 '13 at 04:12
  • Thank you for pasting the error message. – Robᵩ Sep 19 '13 at 04:12
  • .git/hooks/pre-commit: Python script, ASCII text executable, with CRLF line terminators Ok so i get this message. Python is in my path – user2793781 Sep 19 '13 at 04:14

2 Answers2

31

Your pre-commit file has extraneous carriage returns in it. This can happen if you edit the file in Windows and copy the file to a Linux computer.

Try these commands:

cp .git/hooks/pre-commit /tmp/pre-commit
tr -d '\r' < /tmp/pre-commit > .git/hooks/pre-commit

And then rerun your git command.

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
9

The easiest way for '\r' removal is:

dos2unix .git/hooks/pre-commit
Maciej Oziębły
  • 1,769
  • 15
  • 14