Skip to content

Commit 54331dc

Browse files
committed
get lua version from luarocks itself
1 parent 3f8be74 commit 54331dc

File tree

3 files changed

+28
-145
lines changed

3 files changed

+28
-145
lines changed

pre_commit/languages/lua.py

Lines changed: 24 additions & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import contextlib
22
import os
3-
import re
3+
import sys
44
from typing import Generator
55
from typing import Sequence
66
from typing import Tuple
@@ -11,7 +11,6 @@
1111
from pre_commit.envcontext import Var
1212
from pre_commit.hook import Hook
1313
from pre_commit.languages import helpers
14-
from pre_commit.parse_shebang import find_executable
1514
from pre_commit.prefix import Prefix
1615
from pre_commit.util import clean_path_on_failure
1716
from pre_commit.util import cmd_output
@@ -21,95 +20,38 @@
2120
healthy = helpers.basic_healthy
2221

2322

24-
def _find_lua(language_version: str) -> str: # pragma: win32 no cover
25-
"""Find a lua executable.
26-
27-
Lua doesn't always have a plain `lua` executable.
28-
Some OS vendors will ship the binary as `lua#.#` (e.g., lua5.3)
29-
so discovery is needed to find a valid executable.
30-
"""
31-
if language_version == C.DEFAULT:
32-
choices = ['lua']
33-
for path in os.environ.get('PATH', '').split(os.pathsep):
34-
try:
35-
candidates = os.listdir(path)
36-
except OSError:
37-
# Invalid path on PATH or lacking permissions.
38-
continue
39-
40-
for candidate in candidates:
41-
# The Lua executable might look like `lua#.#` or `lua-#.#`.
42-
if re.search(r'^lua[-]?\d+\.\d+', candidate):
43-
choices.append(candidate)
44-
else:
45-
# Prefer version specific executables first if available.
46-
# This should avoid the corner case where a user requests a language
47-
# version, gets a `lua` executable, but that executable is actually
48-
# for a different version and package.path would patch LUA_PATH
49-
# incorrectly.
50-
choices = [f'lua{language_version}', 'lua-{language_version}', 'lua']
51-
52-
found_exes = [exe for exe in choices if find_executable(exe)]
53-
if found_exes:
54-
return found_exes[0]
55-
56-
raise ValueError(
57-
'No lua executable found on the system paths '
58-
f'for {language_version} version.',
59-
)
23+
def _get_lua_version() -> str: # pragma: win32 no cover
24+
"""Get the Lua version used in file paths."""
25+
_, stdout, _ = cmd_output('luarocks', 'config', '--lua-ver')
26+
return stdout.strip()
6027

6128

62-
def _get_lua_path_version(
63-
lua_executable: str,
64-
) -> str: # pragma: win32 no cover
65-
"""Get the Lua version used in file paths."""
66-
# This could sniff out from _VERSION, but checking package.path should
67-
# provide an answer for *exactly* where lua is looking for packages.
68-
_, stdout, _ = cmd_output(lua_executable, '-e', 'print(package.path)')
69-
sep = os.sep if os.name != 'nt' else os.sep * 2
70-
match = re.search(fr'{sep}lua{sep}(.*?){sep}', stdout)
71-
if match:
72-
return match[1]
73-
74-
raise ValueError('Cannot determine lua version for file paths.')
75-
76-
77-
def get_env_patch(
78-
env: str, language_version: str,
79-
) -> PatchesT: # pragma: win32 no cover
80-
lua = _find_lua(language_version)
81-
version = _get_lua_path_version(lua)
29+
def get_env_patch(d: str) -> PatchesT: # pragma: win32 no cover
30+
version = _get_lua_version()
31+
so_ext = 'dll' if sys.platform == 'win32' else 'so'
8232
return (
83-
('PATH', (os.path.join(env, 'bin'), os.pathsep, Var('PATH'))),
33+
('PATH', (os.path.join(d, 'bin'), os.pathsep, Var('PATH'))),
8434
(
8535
'LUA_PATH', (
86-
os.path.join(env, 'share', 'lua', version, '?.lua;'),
87-
os.path.join(env, 'share', 'lua', version, '?', 'init.lua;;'),
36+
os.path.join(d, 'share', 'lua', version, '?.lua;'),
37+
os.path.join(d, 'share', 'lua', version, '?', 'init.lua;;'),
8838
),
8939
),
9040
(
91-
'LUA_CPATH', (
92-
os.path.join(env, 'lib', 'lua', version, '?.so;;'),
93-
),
41+
'LUA_CPATH',
42+
(os.path.join(d, 'lib', 'lua', version, f'?.{so_ext};;'),),
9443
),
9544
)
9645

9746

98-
def _envdir(prefix: Prefix, version: str) -> str: # pragma: win32 no cover
99-
directory = helpers.environment_dir(ENVIRONMENT_DIR, version)
47+
def _envdir(prefix: Prefix) -> str: # pragma: win32 no cover
48+
directory = helpers.environment_dir(ENVIRONMENT_DIR, C.DEFAULT)
10049
return prefix.path(directory)
10150

10251

10352
@contextlib.contextmanager # pragma: win32 no cover
104-
def in_env(
105-
prefix: Prefix,
106-
language_version: str,
107-
) -> Generator[None, None, None]:
108-
with envcontext(
109-
get_env_patch(
110-
_envdir(prefix, language_version), language_version,
111-
),
112-
):
53+
def in_env(prefix: Prefix) -> Generator[None, None, None]:
54+
with envcontext(get_env_patch(_envdir(prefix))):
11355
yield
11456

11557

@@ -120,19 +62,17 @@ def install_environment(
12062
) -> None: # pragma: win32 no cover
12163
helpers.assert_version_default('lua', version)
12264

123-
envdir = _envdir(prefix, version)
65+
envdir = _envdir(prefix)
12466
with clean_path_on_failure(envdir):
125-
with in_env(prefix, version):
67+
with in_env(prefix):
12668
# luarocks doesn't bootstrap a tree prior to installing
12769
# so ensure the directory exists.
12870
os.makedirs(envdir, exist_ok=True)
12971

130-
make_cmd = ['luarocks', '--tree', envdir, 'make']
131-
# Older luarocks (e.g., 2.4.2) expect the rockspec as an argument.
132-
filenames = prefix.star('.rockspec')
133-
make_cmd.extend(filenames[:1])
134-
135-
helpers.run_setup_cmd(prefix, tuple(make_cmd))
72+
# Older luarocks (e.g., 2.4.2) expect the rockspec as an arg
73+
for rockspec in prefix.star('.rockspec'):
74+
make_cmd = ('luarocks', '--tree', envdir, 'make', rockspec)
75+
helpers.run_setup_cmd(prefix, make_cmd)
13676

13777
# luarocks can't install multiple packages at once
13878
# so install them individually.
@@ -146,5 +86,5 @@ def run_hook(
14686
file_args: Sequence[str],
14787
color: bool,
14888
) -> Tuple[int, bytes]: # pragma: win32 no cover
149-
with in_env(hook.prefix, hook.language_version):
89+
with in_env(hook.prefix):
15090
return helpers.run_xargs(hook, hook.cmd, file_args, color=color)

tests/languages/lua_test.py

Lines changed: 0 additions & 55 deletions
This file was deleted.

tests/repository_test.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
from pre_commit.hook import Hook
1818
from pre_commit.languages import golang
1919
from pre_commit.languages import helpers
20-
from pre_commit.languages import lua
2120
from pre_commit.languages import node
2221
from pre_commit.languages import python
2322
from pre_commit.languages import ruby
@@ -1142,18 +1141,17 @@ def test_lua_hook(tempdir_factory, store):
11421141

11431142
@skipif_cant_run_lua # pragma: win32 no cover
11441143
def test_local_lua_additional_dependencies(store):
1145-
lua_entry = lua._find_lua(C.DEFAULT)
11461144
config = {
11471145
'repo': 'local',
11481146
'hooks': [{
11491147
'id': 'local-lua',
11501148
'name': 'local-lua',
1151-
'entry': lua_entry,
1149+
'entry': 'luacheck --version',
11521150
'language': 'lua',
1153-
'args': ['-e', 'require "inspect"; print("hello world")'],
1154-
'additional_dependencies': ['inspect'],
1151+
'additional_dependencies': ['luacheck'],
11551152
}],
11561153
}
11571154
hook = _get_hook(config, store, 'local-lua')
11581155
ret, out = _hook_run(hook, (), color=False)
1159-
assert (ret, _norm_out(out)) == (0, b'hello world\n')
1156+
assert b'Luacheck' in out
1157+
assert ret == 0

0 commit comments

Comments
 (0)