-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpy_lua_helper.py
More file actions
452 lines (419 loc) · 17.8 KB
/
Copy pathpy_lua_helper.py
File metadata and controls
452 lines (419 loc) · 17.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
import os
import tempfile
import subprocess
import shutil
import re
from typing import List, Dict
import logging
logger = logging.getLogger(__name__)
class PyLuaHelper:
"""
Python helper for loading Lua configuration files by running them with Lua interpreter and exporting requested tables to Python dictionaries.
"""
def __init__(
self,
lua_config_script: str,
export_vars: List[str] = None,
pre_script: str = None,
post_script: str = None,
extra_strings: List[str] = None,
work_dir: str = None,
temp_dir: str = None,
min_lua_version: str = None,
max_lua_version: str = None,
lua_binary: str = None,
lua_args: List[str] = None,
):
"""
Initialize PyLuaHelper with configuration options.
Args:
lua_config_script: Path to the main Lua configuration script
export_vars: List of global variable names to export from Lua
pre_script: Lua script to execute before main script
post_script: Lua script to execute after main script
extra_strings: Extra strings to add to loader.extra table
work_dir: Working directory for Lua scripts
result_name: Name of the dictionary to store exported variables
temp_dir: Base directory for temporary files
min_lua_version: Minimum required Lua version
max_lua_version: Maximum allowed Lua version
lua_binary: Path to specific Lua binary (optional, will be auto-detected if not provided)
lua_args: Additional arguments to pass to Lua script (will be placed to loader.args)
"""
self._lua_config_script = os.path.abspath(lua_config_script)
self._export_vars = export_vars or []
self._pre_script = pre_script
self._post_script = post_script
self._extra_strings = extra_strings or []
self._work_dir = work_dir or os.path.dirname(self._lua_config_script)
self._temp_dir = temp_dir
self._min_lua_version = min_lua_version or "5.1.0"
self._max_lua_version = max_lua_version or "5.5.999"
self._lua_binary = lua_binary
self._lua_args = lua_args or []
self._lua_actual_version = None
# Validate required files exist
if not os.path.exists(self._lua_config_script):
raise FileNotFoundError(
f"Main config file not found: {self._lua_config_script}"
)
# Initialize internal state
self._variables: Dict[str, str] = {}
self._metadata: Dict[str, str] = {}
# Initialize temporary directory
self._setup_temp_dir()
try:
# Detect Lua binary
if not self._lua_binary:
self._detect_lua_binary()
# Execute the Lua loader
self._run_lua_loader()
# Parse results
self._parse_results()
finally:
# Clean up temp directory
self._cleanup()
def _setup_temp_dir(self):
"""Setup temporary directory for storing exported variables."""
if self._temp_dir:
if not os.path.exists(self._temp_dir):
raise ValueError(f"Temp directory does not exist: {self._temp_dir}")
self._temp_dir = os.path.abspath(self._temp_dir)
self._temp_dir = tempfile.mkdtemp(prefix="lua-helper-", dir=self._temp_dir)
else:
# Detect temp directory if not provided, platform dependent
if os.name == "nt": # Windows
# Windows temp directory selection logic
temp_dirs = [
os.environ.get("TEMP"),
os.environ.get("TMP"),
os.environ.get("SYSTEMROOT") + "\\Temp",
os.path.expanduser("~"), # user profile directory
"C:\\",
]
# Remove None values from the list
temp_dirs = [d for d in temp_dirs if d is not None]
# Try to create temp directory in candidate locations
for base_dir in temp_dirs:
try:
# Try to create temp directory in this location
self._temp_dir = tempfile.mkdtemp(
prefix="lua-helper-", dir=base_dir
)
break
except (OSError, IOError):
# Failed to create in this location, try next
continue
else:
# If we get here, all locations failed
raise RuntimeError(
"Unable to create temporary directory in any candidate location on Windows"
)
else:
# Locations for linux and other OS:
temp_dirs = [
os.environ.get("TMPDIR"),
"/tmp",
os.environ.get("XDG_RUNTIME_DIR"),
]
# Remove None values from the list
temp_dirs = [d for d in temp_dirs if d is not None]
# Selection for linux and other OS, try to choose tmp dir mounted on tmpfs:
for target in temp_dirs:
if target and os.path.exists(target):
try:
# Check if it's mounted on tmpfs
result = subprocess.run(
["df", "-P", "-t", "tmpfs", target],
capture_output=True,
text=True,
)
if result.returncode == 0:
self._temp_dir = target
break
except Exception:
continue
if not self._temp_dir:
self._temp_dir = "/tmp"
# Create unique temp directory
self._temp_dir = tempfile.mkdtemp(
prefix="lua-helper-", dir=self._temp_dir
)
# Define temp files for data exchange
self._meta_file = os.path.join(self._temp_dir, "meta.tmp")
self._data_file = os.path.join(self._temp_dir, "data.tmp")
self._index_file = os.path.join(self._temp_dir, "index.tmp")
def _detect_lua_binary(self):
"""Detect appropriate Lua binary based on version requirements."""
if self._lua_binary:
# Use explicitly provided binary
if not os.path.exists(self._lua_binary):
raise FileNotFoundError(f"Lua binary not found: {self._lua_binary}")
if self._validate_lua_version(self._lua_binary):
self._lua_binary = os.path.abspath(self._lua_binary)
return
else:
raise ValueError(
f"Lua binary does not meet version requirements: {self._lua_binary}"
)
# Probe for available Lua binaries
lua_hints = [
os.path.join(os.path.dirname(__file__), "lua"),
"lua",
"lua5.4",
"lua54",
"lua5.3",
"lua53",
"lua5.2",
"lua52",
"lua5.1",
"lua51",
]
bin_suffix = ""
if os.name == "nt":
bin_suffix = ".exe"
for hint in lua_hints:
try:
lua_path = shutil.which(f"{hint}{bin_suffix}")
if lua_path and self._validate_lua_version(lua_path):
self._lua_binary = os.path.abspath(lua_path)
return
except Exception:
continue
raise RuntimeError("Failed to detect compatible Lua interpreter")
def _validate_lua_version(self, lua_binary: str) -> bool:
"""Validate Lua binary version against requirements and return actual version."""
try:
result = subprocess.run(
[lua_binary, "-v"], capture_output=True, text=True, timeout=5
)
version_match = re.match(
r"^Lua\s+(\d+)\.(\d+)\.(\d+)", result.stderr or result.stdout
)
if not version_match:
return False
act_version = [int(x) for x in version_match.groups()]
min_version = [int(x) for x in self._min_lua_version.split(".")]
max_version = [int(x) for x in self._max_lua_version.split(".")]
# Check version range
for i, (act, min_v, max_v) in enumerate(
zip(act_version, min_version, max_version)
):
if not (min_v <= act <= max_v):
return False
# Store the actual version if validation passes
self._lua_actual_version = act_version
return True
except Exception:
return False
def _run_lua_loader(self):
"""Execute the Lua loader script with appropriate parameters."""
# Build command line arguments
cmd = [self._lua_binary, os.path.join(os.path.dirname(__file__), "loader.lua")]
# Add version info
cmd.extend(
[
"-ver",
str(self._lua_actual_version[0]),
str(self._lua_actual_version[1]),
str(self._lua_actual_version[2]),
]
)
# Add configuration parameters
cmd.extend(["-c", self._lua_config_script])
# Add export variables
for var in self._export_vars:
cmd.extend(["-e", var])
# Add pre script
if self._pre_script:
cmd.extend(["-pre", self._pre_script])
# Add post script
if self._post_script:
cmd.extend(["-post", self._post_script])
# Add extra strings
for extra in self._extra_strings:
cmd.extend(["-ext", extra])
# Add work directory
cmd.extend(["-w", self._work_dir])
# Add temp directory
cmd.extend(["-t", self._temp_dir])
# Add -- separator
cmd.append("--")
# Add additional Lua arguments
cmd.extend(self._lua_args)
# Execute the command
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=180)
print(result.stdout, end="")
print(result.stderr, end="")
if result.returncode != 0:
raise RuntimeError(
f"Lua loader failed with error code {result.returncode}"
)
except subprocess.TimeoutExpired:
raise RuntimeError("Lua loader timed out")
def _parse_text_fields(self, file_path: str):
"""
Parses a binary file containing UTF-8 text fields generated by loader.lua
Args:
file_path (str): The path to the binary file.
Returns:
list: A list of strings containing the parsed UTF-8 fields.
"""
fields = []
with open(file_path, "rb") as f:
file_content = f.read()
# Locate the start marker, set initial position
header_marker = b"start\xff\x00"
start_pos = file_content.find(header_marker)
if start_pos == -1:
raise ValueError(f"Failed to locate start marker at {file_path}")
current_pos = start_pos + len(header_marker)
# Read UTF8 text fields, separated with special sequence
separator = b"\xff\x00"
while True:
# Find the next separator
sep_pos = file_content.find(separator, current_pos)
if sep_pos != -1:
# Extract the bytes for the current field
field_bytes = file_content[current_pos:sep_pos]
field_str = field_bytes.decode("utf-8")
fields.append(field_str)
# Move pointer past the separator
current_pos = sep_pos + len(separator)
else:
# No separator found, this is the last field (no terminator at the end)
if current_pos < len(file_content):
raise ValueError(
f"Surplus data at the end of file, at pos: {current_pos}"
)
break
return fields
def _parse_results(self):
"""Parse exported variables from temporary files."""
# Read exported data
exports = self._parse_text_fields(self._index_file)
meta = self._parse_text_fields(self._meta_file)
data = self._parse_text_fields(self._data_file)
for index, value in enumerate(exports):
self._variables[value] = data[index]
self._metadata[value] = meta[index]
def _cleanup(self):
"""Clean up temporary directory."""
if self._temp_dir and os.path.exists(self._temp_dir):
try:
shutil.rmtree(self._temp_dir)
except Exception:
pass
def __getitem__(self, key: str) -> str:
"""Get item from exported variables dictionary."""
return self._variables.get(key, "")
def __contains__(self, key: str) -> bool:
"""Check if variable is available."""
return key in self._metadata and self._metadata[key] != ""
def __iter__(self):
"""Iterate over exported variable names."""
return iter(self._variables)
def __len__(self) -> int:
"""Get number of exported variables."""
return len(self._variables)
def keys(self) -> List[str]:
"""Get list of exported variable names."""
return list(self._variables.keys())
def values(self) -> List[str]:
"""Get list of exported variable values."""
return list(self._variables.values())
def items(self) -> List[tuple]:
"""Get list of (name, value) tuples."""
return list(self._variables.items())
def is_table(self, key: str) -> bool:
"""Check variable is a table, return true or false"""
if key in self._metadata:
match = re.match(r"^table.*", self._metadata[key])
if match:
return True
return False
def get_type(self, key: str) -> str:
"""Get variable type"""
if self.is_table(key):
return "table"
if key in self._metadata and re.match(r"^string.*", self._metadata[key]):
return "string"
return self._metadata.get(key, "none")
def get(self, key: str, default: str = None) -> str:
"""Get variable value with default."""
# cannot get value of table directly, so, return default
if self.is_table(key):
return default
return self._variables.get(key, default)
def get_int(self, key: str, default: int = None) -> int:
"""Get variable value as integer with defaults on type conversion error."""
try:
value_type = self.get_type(key)
if value_type == "number":
return int(self._variables.get(key, default))
raise ValueError(f"Invalid value type: {value_type}")
except ValueError:
if default is not None:
return int(default)
raise
def get_float(self, key: str, default: float = None) -> float:
"""Get variable value as float with defaults on type conversion error."""
try:
value_type = self.get_type(key)
if value_type == "number":
return float(self._variables.get(key, default))
raise ValueError(f"Invalid value type: {value_type}")
except ValueError:
if default is not None:
return float(default)
raise
def get_bool(self, key: str, default: bool = None) -> bool:
"""Get variable value as bool with defaults on type conversion error."""
try:
value_type = self.get_type(key)
if value_type == "boolean":
value = self._variables.get(key)
if value == "true":
value = True
elif value == "false":
value = False
return bool(value)
raise ValueError(f"Invalid value type: {value_type}")
except ValueError:
if default is not None:
return bool(default)
raise
def get_list(self, key: str) -> List:
"""Get indexed elements of table as list of strings if variable is a table and indexed (keyless) elements present, empty list if no elements present or variable is not a table"""
result = []
for i in self.get_table_seq(key):
result.append(self.get(f"{key}.{i}"))
return result
def get_table_start(self, key: str) -> int:
"""Get start indexed element index of table if variable is a table and indexed (keyless) elements present, 0 if no indexed elements present"""
if key in self._metadata:
match = re.match(r"^table:(.*):(.*)", self._metadata[key])
if match:
return int(match.group(1))
return 0
def get_table_end(self, key: str) -> int:
"""Get end position of table if variable is a table, last indexable element is less than this number"""
if key in self._metadata:
match = re.match(r"^table:(.*):(.*)", self._metadata[key])
if match:
return int(match.group(2))
return 0
def get_table_seq(self, key: str) -> List[int]:
"""Get sequence of table indices if variable is a table with indexed elements."""
start = self.get_table_start(key)
end = self.get_table_end(key)
if start == 0:
return []
return list(range(start, end))
def __repr__(self) -> str:
"""String representation."""
return f"PyLuaHelper({len(self._variables)} variables)"
def __str__(self) -> str:
"""String representation."""
return f"PyLuaHelper with {len(self._variables)} exported variables"