Skip to content

Commit 294159d

Browse files
committed
Merge pull request #30 from nicholasbishop/bishop_is_python_file
Separate code for testing if a file is Python into a new function
2 parents 72abd55 + 4d58978 commit 294159d

File tree

2 files changed

+31
-9
lines changed

2 files changed

+31
-9
lines changed

git_pylint_commit_hook/commit_hook.py

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,21 @@ def _get_list_of_committed_files():
4949
return files
5050

5151

52+
def _is_python_file(filename):
53+
"""Check if the input file looks like a Python script
54+
55+
Returns True if the filename ends in ".py" or if the first line
56+
contains "python" and "#!", returns False otherwise.
57+
58+
"""
59+
if filename.endswith('.py'):
60+
return True
61+
else:
62+
with open(filename, 'r') as file_handle:
63+
first_line = file_handle.readline()
64+
return 'python' in first_line and '#!' in first_line
65+
66+
5267
def check_repo(
5368
limit, pylint='pylint', pylintrc='.pylintrc', pylint_params=None):
5469
""" Main function doing the checks
@@ -70,16 +85,8 @@ def check_repo(
7085

7186
# Find Python files
7287
for filename in _get_list_of_committed_files():
73-
# Check the file extension
74-
if filename[-3:] == '.py':
75-
python_files.append((filename, None))
76-
continue
77-
78-
# Check the first line for a python shebang
7988
try:
80-
with open(filename, 'r') as file_handle:
81-
first_line = file_handle.readline()
82-
if 'python' in first_line and '#!' in first_line:
89+
if _is_python_file(filename):
8390
python_files.append((filename, None))
8491
except IOError:
8592
print 'File not found (probably deleted): {}\t\tSKIPPED'.format(

tests.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,3 +69,18 @@ def test_list_of_committed_files(self):
6969
# Add 'a'
7070
self.cmd('git add ' + a)
7171
self.assertEquals(commit_hook._get_list_of_committed_files(), [a])
72+
73+
def test_is_python_file(self):
74+
"""Test commit_hook._is_python_file"""
75+
76+
# Extension
77+
a = self.write_file('a.py', '')
78+
self.assertTrue(commit_hook._is_python_file(a))
79+
80+
# Empty
81+
a = self.write_file('b', '')
82+
self.assertFalse(commit_hook._is_python_file(a))
83+
84+
# Shebang
85+
self.write_file('b', '#!/usr/bin/env python')
86+
self.assertTrue(commit_hook._is_python_file(a))

0 commit comments

Comments
 (0)