Skip to content

Commit ad928f6

Browse files
authored
Merge pull request #480 from mxr/git-file-mode
Check git mode on Windows
2 parents 3d379a9 + 5195ba3 commit ad928f6

File tree

2 files changed

+124
-20
lines changed

2 files changed

+124
-20
lines changed

pre_commit_hooks/check_executables_have_shebangs.py

Lines changed: 48 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,39 +2,68 @@
22
import argparse
33
import shlex
44
import sys
5+
from typing import List
56
from typing import Optional
67
from typing import Sequence
8+
from typing import Set
79

10+
from pre_commit_hooks.util import cmd_output
811

9-
def check_has_shebang(path: str) -> int:
12+
EXECUTABLE_VALUES = frozenset(('1', '3', '5', '7'))
13+
14+
15+
def check_executables(paths: List[str]) -> int:
16+
if sys.platform == 'win32': # pragma: win32 cover
17+
return _check_git_filemode(paths)
18+
else: # pragma: win32 no cover
19+
retv = 0
20+
for path in paths:
21+
if not _check_has_shebang(path):
22+
_message(path)
23+
retv = 1
24+
25+
return retv
26+
27+
28+
def _check_git_filemode(paths: Sequence[str]) -> int:
29+
outs = cmd_output('git', 'ls-files', '--stage', '--', *paths)
30+
seen: Set[str] = set()
31+
for out in outs.splitlines():
32+
metadata, path = out.split('\t')
33+
tagmode = metadata.split(' ', 1)[0]
34+
35+
is_executable = any(b in EXECUTABLE_VALUES for b in tagmode[-3:])
36+
has_shebang = _check_has_shebang(path)
37+
if is_executable and not has_shebang:
38+
_message(path)
39+
seen.add(path)
40+
41+
return int(bool(seen))
42+
43+
44+
def _check_has_shebang(path: str) -> int:
1045
with open(path, 'rb') as f:
1146
first_bytes = f.read(2)
1247

13-
if first_bytes != b'#!':
14-
quoted = shlex.quote(path)
15-
print(
16-
f'{path}: marked executable but has no (or invalid) shebang!\n'
17-
f" If it isn't supposed to be executable, try: "
18-
f'`chmod -x {quoted}`\n'
19-
f' If it is supposed to be executable, double-check its shebang.',
20-
file=sys.stderr,
21-
)
22-
return 1
23-
else:
24-
return 0
48+
return first_bytes == b'#!'
49+
50+
51+
def _message(path: str) -> None:
52+
print(
53+
f'{path}: marked executable but has no (or invalid) shebang!\n'
54+
f" If it isn't supposed to be executable, try: "
55+
f'`chmod -x {shlex.quote(path)}`\n'
56+
f' If it is supposed to be executable, double-check its shebang.',
57+
file=sys.stderr,
58+
)
2559

2660

2761
def main(argv: Optional[Sequence[str]] = None) -> int:
2862
parser = argparse.ArgumentParser(description=__doc__)
2963
parser.add_argument('filenames', nargs='*')
3064
args = parser.parse_args(argv)
3165

32-
retv = 0
33-
34-
for filename in args.filenames:
35-
retv |= check_has_shebang(filename)
36-
37-
return retv
66+
return check_executables(args.filenames)
3867

3968

4069
if __name__ == '__main__':

tests/check_executables_have_shebangs_test.py

Lines changed: 76 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,19 @@
1+
import os
2+
import sys
3+
14
import pytest
25

6+
from pre_commit_hooks import check_executables_have_shebangs
37
from pre_commit_hooks.check_executables_have_shebangs import main
8+
from pre_commit_hooks.util import cmd_output
9+
10+
skip_win32 = pytest.mark.skipif(
11+
sys.platform == 'win32',
12+
reason="non-git checks aren't relevant on windows",
13+
)
414

515

16+
@skip_win32 # pragma: win32 no cover
617
@pytest.mark.parametrize(
718
'content', (
819
b'#!/bin/bash\nhello world\n',
@@ -17,14 +28,14 @@ def test_has_shebang(content, tmpdir):
1728
assert main((path.strpath,)) == 0
1829

1930

31+
@skip_win32 # pragma: win32 no cover
2032
@pytest.mark.parametrize(
2133
'content', (
2234
b'',
2335
b' #!python\n',
2436
b'\n#!python\n',
2537
b'python\n',
2638
'☃'.encode(),
27-
2839
),
2940
)
3041
def test_bad_shebang(content, tmpdir, capsys):
@@ -33,3 +44,67 @@ def test_bad_shebang(content, tmpdir, capsys):
3344
assert main((path.strpath,)) == 1
3445
_, stderr = capsys.readouterr()
3546
assert stderr.startswith(f'{path}: marked executable but')
47+
48+
49+
def test_check_git_filemode_passing(tmpdir):
50+
with tmpdir.as_cwd():
51+
cmd_output('git', 'init', '.')
52+
53+
f = tmpdir.join('f')
54+
f.write('#!/usr/bin/env bash')
55+
f_path = str(f)
56+
cmd_output('chmod', '+x', f_path)
57+
cmd_output('git', 'add', f_path)
58+
cmd_output('git', 'update-index', '--chmod=+x', f_path)
59+
60+
g = tmpdir.join('g').ensure()
61+
g_path = str(g)
62+
cmd_output('git', 'add', g_path)
63+
64+
# this is potentially a problem, but not something the script intends
65+
# to check for -- we're only making sure that things that are
66+
# executable have shebangs
67+
h = tmpdir.join('h')
68+
h.write('#!/usr/bin/env bash')
69+
h_path = str(h)
70+
cmd_output('git', 'add', h_path)
71+
72+
files = (f_path, g_path, h_path)
73+
assert check_executables_have_shebangs._check_git_filemode(files) == 0
74+
75+
76+
def test_check_git_filemode_failing(tmpdir):
77+
with tmpdir.as_cwd():
78+
cmd_output('git', 'init', '.')
79+
80+
f = tmpdir.join('f').ensure()
81+
f_path = str(f)
82+
cmd_output('chmod', '+x', f_path)
83+
cmd_output('git', 'add', f_path)
84+
cmd_output('git', 'update-index', '--chmod=+x', f_path)
85+
86+
files = (f_path,)
87+
assert check_executables_have_shebangs._check_git_filemode(files) == 1
88+
89+
90+
@pytest.mark.parametrize(
91+
('content', 'mode', 'expected'),
92+
(
93+
pytest.param('#!python', '+x', 0, id='shebang with executable'),
94+
pytest.param('#!python', '-x', 0, id='shebang without executable'),
95+
pytest.param('', '+x', 1, id='no shebang with executable'),
96+
pytest.param('', '-x', 0, id='no shebang without executable'),
97+
),
98+
)
99+
def test_git_executable_shebang(temp_git_dir, content, mode, expected):
100+
with temp_git_dir.as_cwd():
101+
path = temp_git_dir.join('path')
102+
path.write(content)
103+
cmd_output('git', 'add', str(path))
104+
cmd_output('chmod', mode, str(path))
105+
cmd_output('git', 'update-index', f'--chmod={mode}', str(path))
106+
107+
# simulate how identify choses that something is executable
108+
filenames = [path for path in [str(path)] if os.access(path, os.X_OK)]
109+
110+
assert main(filenames) == expected

0 commit comments

Comments
 (0)