Skip to content

Commit 1d40cc2

Browse files
authored
Merge pull request pre-commit#893 from pre-commit/shebang
Pick a better python shebang for hook executable
2 parents 748c2ad + de94289 commit 1d40cc2

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

pre_commit/commands/install_uninstall.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
from pre_commit import git
1010
from pre_commit import output
11+
from pre_commit.languages import python
1112
from pre_commit.repository import repositories
1213
from pre_commit.util import cmd_output
1314
from pre_commit.util import make_executable
@@ -43,6 +44,16 @@ def is_our_script(filename):
4344
return any(h in contents for h in (CURRENT_HASH,) + PRIOR_HASHES)
4445

4546

47+
def shebang():
48+
if sys.platform == 'win32':
49+
py = 'python'
50+
else:
51+
py = python.get_default_version()
52+
if py == 'default':
53+
py = 'python'
54+
return '#!/usr/bin/env {}'.format(py)
55+
56+
4657
def install(
4758
runner, store, overwrite=False, hooks=False, hook_type='pre-commit',
4859
skip_on_missing_conf=False,
@@ -84,6 +95,8 @@ def install(
8495
before, rest = contents.split(TEMPLATE_START)
8596
to_template, after = rest.split(TEMPLATE_END)
8697

98+
before = before.replace('#!/usr/bin/env python', shebang())
99+
87100
hook_file.write(before + TEMPLATE_START)
88101
for line in to_template.splitlines():
89102
var = line.split()[0]

tests/commands/install_uninstall_test.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,9 @@
1717
from pre_commit.commands.install_uninstall import install_hooks
1818
from pre_commit.commands.install_uninstall import is_our_script
1919
from pre_commit.commands.install_uninstall import PRIOR_HASHES
20+
from pre_commit.commands.install_uninstall import shebang
2021
from pre_commit.commands.install_uninstall import uninstall
22+
from pre_commit.languages import python
2123
from pre_commit.runner import Runner
2224
from pre_commit.util import cmd_output
2325
from pre_commit.util import make_executable
@@ -45,6 +47,24 @@ def test_is_previous_pre_commit(tmpdir):
4547
assert is_our_script(f.strpath)
4648

4749

50+
def test_shebang_windows():
51+
with mock.patch.object(sys, 'platform', 'win32'):
52+
assert shebang() == '#!/usr/bin/env python'
53+
54+
55+
def test_shebang_otherwise():
56+
with mock.patch.object(sys, 'platform', 'posix'):
57+
assert 'default' not in shebang()
58+
59+
60+
def test_shebang_returns_default():
61+
with mock.patch.object(sys, 'platform', 'posix'):
62+
with mock.patch.object(
63+
python, 'get_default_version', return_value='default',
64+
):
65+
assert shebang() == '#!/usr/bin/env python'
66+
67+
4868
def test_install_pre_commit(tempdir_factory, store):
4969
path = git_dir(tempdir_factory)
5070
runner = Runner(path, C.CONFIG_FILE)

0 commit comments

Comments
 (0)