forked from Crimso777/Factorio-Access
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathlaunch_factorio.py
More file actions
1307 lines (1099 loc) · 44.2 KB
/
launch_factorio.py
File metadata and controls
1307 lines (1099 loc) · 44.2 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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Factorio Windows Launcher - Development and debugging tool for FactorioAccess.
Key features:
- Launch Factorio with timeout support
- Capture and analyze crash logs
- Run tests and linting
- Format code with stylua
"""
import argparse
import subprocess
import sys
import os
import time
import shutil
from pathlib import Path
from typing import Optional, List, Tuple, Dict, Any
import threading
import queue
import json
import tempfile
import re
import glob
# Constants
FACTORIO_REL_PATH = Path("../../bin/x64/factorio.exe")
DEFAULT_TIMEOUT = 300
LUA_EXE = "lua52.exe"
class LogsNotFoundError(Exception):
"""Raised when critical logs cannot be found during debugging."""
pass
def validate_factorio_exe() -> Path:
"""Validate and return the Factorio executable path."""
factorio_path = (Path(__file__).parent / FACTORIO_REL_PATH).resolve()
if not factorio_path.exists():
raise FileNotFoundError(
f"Factorio executable not found at: {factorio_path}\n"
f"Current working directory: {Path.cwd()}"
)
return factorio_path
def stream_process_output(
cmd: List[str],
timeout: Optional[int] = None,
capture: bool = True,
unbuffered: bool = True,
) -> Tuple[int, float]:
"""
Stream output from a subprocess with timeout support.
Uses threading to prevent blocking on pipe reads and handle timeouts properly.
Returns:
Tuple of (exit_code, elapsed_time)
"""
start_time = time.time()
output_queue = queue.Queue()
def output_reader(pipe, pipe_name: str):
"""Thread worker to read from stdout/stderr pipes."""
try:
for line in iter(pipe.readline, ""):
if line:
output_queue.put((pipe_name, line))
pipe.close()
except Exception as e:
output_queue.put(("error", f"Error reading {pipe_name}: {e}"))
# Setup subprocess
popen_args = {
"bufsize": 0 if unbuffered else -1,
"encoding": "utf-8",
"errors": "replace",
"env": os.environ.copy(),
}
if capture:
popen_args.update(
{
"stdout": subprocess.PIPE,
"stderr": subprocess.PIPE,
}
)
print(f"[INFO] Launching: {' '.join(cmd)}")
if timeout:
print(f"[INFO] Timeout: {timeout} seconds")
try:
process = subprocess.Popen(cmd, **popen_args)
if capture:
# Start reader threads
stdout_thread = threading.Thread(
target=output_reader, args=(process.stdout, "stdout")
)
stderr_thread = threading.Thread(
target=output_reader, args=(process.stderr, "stderr")
)
stdout_thread.daemon = True
stderr_thread.daemon = True
stdout_thread.start()
stderr_thread.start()
# Stream output in real-time
while True:
try:
pipe_name, line = output_queue.get(timeout=0.1)
if pipe_name == "stdout":
sys.stdout.write(line)
sys.stdout.flush()
elif pipe_name == "stderr":
sys.stderr.write(line)
sys.stderr.flush()
except queue.Empty:
# Check if process finished
if process.poll() is not None:
break
# Check timeout
elapsed = time.time() - start_time
if timeout and elapsed > timeout:
print(f"\n[ERROR] Timeout reached ({timeout}s), terminating...")
process.terminate()
time.sleep(2)
if process.poll() is None:
process.kill()
return -1, elapsed
# Drain remaining output
while not output_queue.empty():
try:
pipe_name, line = output_queue.get_nowait()
if pipe_name == "stdout":
sys.stdout.write(line)
elif pipe_name == "stderr":
sys.stderr.write(line)
except queue.Empty:
break
else:
# Simple wait without capture
try:
process.wait(timeout=timeout)
except subprocess.TimeoutExpired:
elapsed = time.time() - start_time
print(f"\n[ERROR] Timeout reached ({timeout}s), terminating...")
process.terminate()
time.sleep(2)
if process.poll() is None:
process.kill()
return -1, elapsed
elapsed = time.time() - start_time
return process.returncode, elapsed
except OSError as e:
elapsed = time.time() - start_time
if e.errno == 2:
print(f"[ERROR] Could not find executable: {cmd[0]}")
else:
print(f"[ERROR] OS error launching process: {e}")
return -1, elapsed
except Exception as e:
elapsed = time.time() - start_time
print(f"[ERROR] Unexpected error: {e}")
return -1, elapsed
def launch_factorio(
args: List[str],
timeout: Optional[int] = None,
capture_output: bool = True,
) -> Tuple[int, float]:
"""Launch Factorio with specified arguments."""
factorio_path = validate_factorio_exe()
cmd = [str(factorio_path)] + args
return stream_process_output(cmd, timeout, capture_output)
def find_factorio_type_definitions() -> Optional[str]:
"""Find Factorio type definitions for lua-language-server."""
# First, try to read from .vscode/settings.json
vscode_settings_path = Path(".vscode/settings.json")
if vscode_settings_path.exists():
try:
with open(vscode_settings_path, "r") as f:
settings = json.load(f)
user_third_party = settings.get("Lua.workspace.userThirdParty", [])
if user_third_party:
# userThirdParty points to sumneko-3rd, we need factorio/library inside it
lib_path = Path(user_third_party[0]) / "factorio" / "library"
if lib_path.exists():
return str(lib_path)
except (json.JSONDecodeError, IOError):
pass # Fall through to glob approach
# Fallback: glob for workspace storage
search_paths = [
# VSCode on Windows
os.path.expanduser(
"~\\AppData\\Roaming\\Code\\User\\workspaceStorage\\*\\justarandomgeek.factoriomod-debug\\sumneko-3rd\\factorio\\library"
),
# Manual installation
"C:\\factorio-lua-types\\library",
os.path.expanduser("~\\factorio-lua-types\\library"),
]
for pattern in search_paths:
expanded = os.path.expanduser(pattern)
matches = glob.glob(expanded)
if matches:
return matches[0]
return None
def create_or_update_luarc(config_path: str) -> None:
"""Create .luarc.json configuration for lua-language-server."""
luarc_path = Path(config_path)
factorio_lib = find_factorio_type_definitions()
config = {
"$schema": "https://raw.githubusercontent.com/sumneko/vscode-lua/master/setting/schema.json",
"runtime": {
"version": "Lua 5.2",
"path": ["?.lua", "?/init.lua", "scripts/?.lua"],
"pathStrict": False,
},
"workspace": {
"library": [],
"checkThirdParty": False,
"ignoreDir": [".vscode", ".git"],
},
"diagnostics": {
"enable": True,
"workspaceDelay": 1,
"globals": [
# Custom mod globals
"players",
"printout",
"get_selected_ent",
"direction_lookup",
"cursor_highlight",
"sync_build_cursor_graphics",
"get_direction_of_that_from_this",
"clear_obstacles_in_rectangle",
"ENT_TYPES_YOU_CAN_BUILD_OVER",
],
"disable": [
"lowercase-global",
"deprecated",
"need-check-nil",
"redefined-local",
],
"severity": {
"unused-local": "Information",
"undefined-global": "Warning",
"undefined-field": "Information",
"redundant-parameter": "Information",
"cast-local-type": "Warning",
"assign-type-mismatch": "Information",
},
},
"completion": { "enable": False },
"codeLens": { "enable": False },
"format": {"enable": False},
"telemetry": {"enable": False},
"hint": {"enable": False, "setType": False},
"type": {
"weakNilCheck": True,
"weakUnionCheck": True,
}
}
if factorio_lib:
config["workspace"]["library"].append(factorio_lib)
print(f"[INFO] Found Factorio type definitions at: {factorio_lib}")
else:
print(
"[WARNING] Factorio type definitions not found. Some API completions may be missing."
)
print(
"[HINT] Install the factoriomod-debug VSCode extension for better type checking."
)
with open(luarc_path, "w") as f:
json.dump(config, f, indent=2)
print(f"[INFO] Updated {luarc_path}")
def check_lua_annotations() -> Tuple[int, List[str]]:
"""
Check for incorrect LuaLS annotation formats.
Correct format: ---@
Incorrect formats: -- @, --- @, --@, etc.
Returns:
Tuple of (exit_code, error_list)
"""
mod_path = Path(__file__).parent.resolve()
errors = []
files_checked = 0
# Find all Lua files
lua_files = glob.glob(str(mod_path / "**/*.lua"), recursive=True)
for file_path in lua_files:
files_checked += 1
try:
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
# Check each line for annotation issues
for line_num, line in enumerate(content.splitlines(), 1):
stripped = line.strip()
if not stripped or "@" not in stripped:
continue
# Check if line contains annotation-like pattern
if re.match(r"^\s*-+\s*@", line):
# Check if it's NOT the correct format
if not re.match(r"^\s*---@", line):
rel_path = Path(file_path).relative_to(mod_path)
errors.append(
f"{rel_path}:{line_num}: Incorrect annotation format: {line.strip()}"
)
errors.append(
f" Should be: ---@{line.strip()[line.find('@') + 1 :]}"
)
except Exception as e:
errors.append(f"Error checking {file_path}: {str(e)}")
if not errors:
print(f"[INFO] All annotations correct in {files_checked} Lua files")
return (1 if errors else 0, errors)
def check_non_top_level_requires() -> Tuple[int, List[str]]:
"""
Check for non-top-level require() statements.
require() statements should only appear at module level (no indentation),
not inside functions or other blocks.
Returns:
Tuple of (exit_code, error_list)
"""
mod_path = Path(__file__).parent.resolve()
errors = []
files_checked = 0
# Files/patterns to skip (test infrastructure, CLI tools, etc.)
skip_patterns = [
"*-tests.lua",
"*-cli.lua",
"run-tests.lua",
"test-*.lua",
]
# Find all Lua files
lua_files = glob.glob(str(mod_path / "**/*.lua"), recursive=True)
for file_path in lua_files:
# Skip test infrastructure files
file_name = Path(file_path).name
if any(glob.fnmatch.fnmatch(file_name, pattern) for pattern in skip_patterns):
continue
files_checked += 1
try:
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
# Check each line for non-top-level requires
for line_num, line in enumerate(content.splitlines(), 1):
# Skip comments
if line.strip().startswith("--"):
continue
# Check if line contains require(
if "require(" in line:
# Check if line has leading whitespace (indicating it's inside a block)
if line and line[0] in (' ', '\t'):
rel_path = Path(file_path).relative_to(mod_path)
errors.append(
f"{rel_path}:{line_num}: Non-top-level require() found"
)
errors.append(f" {line.rstrip()}")
errors.append(
" require() statements should only appear at module level (no indentation)"
)
except Exception as e:
errors.append(f"Error checking {file_path}: {str(e)}")
if not errors:
print(f"[INFO] No non-top-level requires found in {files_checked} Lua files")
return (1 if errors else 0, errors)
def filter_luals_output(output: str) -> str:
"""Filter out lua-language-server progress lines.
LuaLS outputs progress lines like:
Initializing ...
>=================== 001/274
>>================== 014/274
>>>>>=============== 066/274 [Found 1 problems in 1 files]
Diagnosis completed, no problems found
It also outputs lines that are just whitespace (from progress bar overwrites).
We want to keep only the meaningful diagnostic output.
"""
# Pattern matches progress lines: optional >, =, spaces, and NNN/NNN format
# Also matches "Initializing ..." and similar status lines
progress_pattern = re.compile(
r"^\s*[>= ]*\d{3}/\d{3}.*$|" # Progress bars like ">====== 001/274" or with "[Found X problems...]"
r"^\s*Initializing\s*\.{3}\s*$|" # "Initializing ..."
r"^\s+$" # Lines that are only whitespace
)
lines = output.splitlines()
filtered_lines = []
for line in lines:
# Skip progress lines and whitespace-only lines
if progress_pattern.match(line):
continue
filtered_lines.append(line)
return "\n".join(filtered_lines)
def run_lua_linter(lua_ls_path: Optional[str] = None) -> int:
"""Run lua-language-server on the mod files.
Captures output, filters progress lines, and displays meaningful diagnostics.
Returns exit code (0 = success, -1 = timeout/error).
"""
mod_path = Path(__file__).parent.resolve()
if lua_ls_path is None:
# Try to find lua-language-server
possible_paths = [
"lua-language-server.exe",
os.path.expanduser(
"~\\.vscode\\extensions\\sumneko.lua-*\\server\\bin\\lua-language-server.exe"
),
os.path.expanduser(
"~\\AppData\\Roaming\\Code\\User\\globalStorage\\sumneko.lua\\server\\bin\\lua-language-server.exe"
),
]
for pattern in possible_paths:
if pattern == "lua-language-server.exe":
if shutil.which(pattern):
lua_ls_path = pattern
break
else:
matches = glob.glob(pattern)
if matches:
lua_ls_path = matches[0]
break
if not lua_ls_path:
print("lua-language-server not found. Install the sumneko.lua VSCode extension.", file=sys.stderr)
return -1
# Create temporary .luarc.json config (don't pollute the mod directory)
with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as tmp:
config_file = tmp.name
create_or_update_luarc(config_file)
# Run lua-language-server with temp config, capturing output
cmd = [lua_ls_path, "--check", mod_path, "--configpath", config_file]
try:
result = subprocess.run(
cmd,
cwd=str(mod_path),
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
)
# Filter and display stdout
if result.stdout:
filtered_stdout = filter_luals_output(result.stdout)
if filtered_stdout.strip():
print(filtered_stdout)
# Filter and display stderr
if result.stderr:
filtered_stderr = filter_luals_output(result.stderr)
if filtered_stderr.strip():
print(filtered_stderr, file=sys.stderr)
return result.returncode
except Exception as e:
print(f"Error running lua-language-server: {e}", file=sys.stderr)
return -1
finally:
# Clean up temp config file
try:
os.unlink(config_file)
except:
pass
def run_stylua(
stylua_path: Optional[str] = None, check_only: bool = False
) -> Tuple[int, str, str]:
"""Run stylua formatter on Lua files."""
mod_path = Path(__file__).parent.resolve()
if stylua_path is None:
stylua_path = shutil.which("stylua")
if not stylua_path:
return -1, "", "stylua not found in PATH. Please install stylua."
cmd = [stylua_path]
if check_only:
cmd.append("--check")
cmd.append(str(mod_path))
try:
result = subprocess.run(
cmd,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=30,
)
return result.returncode, result.stdout, result.stderr
except subprocess.TimeoutExpired:
return -1, "", "stylua timed out after 30 seconds"
except Exception as e:
return -1, "", f"Error running stylua: {e}"
def run_lua_tests(test_suite: str = "all") -> Tuple[int, str, str]:
"""Run Lua unit tests (syntrax and/or data structures)."""
if not shutil.which(LUA_EXE):
return (
-1,
"",
f"{LUA_EXE} not found. Please ensure Lua 5.2 is installed and in PATH.",
)
stdout_parts = []
stderr_parts = []
exit_code = 0
# Determine which tests to run
test_files = []
if test_suite in ["syntrax", "all"]:
test_files.append("syntrax-tests.lua")
if test_suite in ["ds", "all"]:
test_files.append("ds-tests.lua")
if test_suite in ["railutils", "all"]:
test_files.append("railutils-tests.lua")
for test_file in test_files:
if not Path(test_file).exists():
stderr_parts.append(f"Test file {test_file} not found")
continue
cmd = [LUA_EXE, test_file]
try:
result = subprocess.run(
cmd,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=30,
)
stdout_parts.append(result.stdout)
stderr_parts.append(result.stderr)
if result.returncode != 0:
exit_code = result.returncode
except Exception as e:
stderr_parts.append(f"Error running {test_file}: {e}")
exit_code = -1
return exit_code, "\n".join(stdout_parts), "\n".join(stderr_parts)
def find_script_output_dir() -> Optional[Path]:
"""Find Factorio's script-output directory."""
# Script output is relative to Factorio executable
factorio_dir = Path(__file__).parent.parent.parent
script_output = factorio_dir / "script-output"
if script_output.exists():
return script_output
# Try alternative location
alt_output = factorio_dir / "data" / "script-output"
if alt_output.exists():
return alt_output
return None
def capture_crash_info(exit_code: int, fail_hard: bool = True) -> Dict[str, Any]:
"""
Capture crash information from logs.
Args:
exit_code: Exit code from Factorio
fail_hard: If True, raise exception when critical logs are missing
Returns:
Dictionary with crash information
"""
crash_info = {
"exit_code": exit_code,
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
"factorio_log": None,
"mod_log": None,
"speech_log": None,
}
logs_found = False
missing_logs = []
# Find Factorio log
factorio_dir = Path(__file__).parent.parent.parent
log_path = factorio_dir / "factorio-current.log"
if log_path.exists():
try:
with open(log_path, "r", encoding="utf-8", errors="ignore") as f:
lines = f.readlines()
# Look for error patterns
error_found = False
for i, line in enumerate(lines):
if any(
pattern in line.lower()
for pattern in [
"error",
"exception",
"crash",
"stack traceback",
]
):
# Capture context around error
start = max(0, i - 20)
crash_info["factorio_log"] = "".join(lines[start:])[
-10000:
] # Last 10KB max
error_found = True
break
if not error_found:
# No error found, just get last 100 lines
crash_info["factorio_log"] = "".join(lines[-100:])
logs_found = True
except Exception as e:
crash_info["factorio_log"] = f"Failed to read log: {e}"
else:
missing_logs.append(f"factorio-current.log at {log_path}")
# Find mod logs
script_output_dir = find_script_output_dir()
if script_output_dir:
# Mod log
mod_log_path = script_output_dir / "factorio-access.log"
if mod_log_path.exists():
try:
with open(mod_log_path, "r", encoding="utf-8", errors="ignore") as f:
crash_info["mod_log"] = f.read()[-10000:] # Last 10KB
logs_found = True
except Exception as e:
crash_info["mod_log"] = f"Failed to read mod log: {e}"
# Speech log (critical for debugging)
speech_log_path = script_output_dir / "factorio-access-speech.log"
if speech_log_path.exists():
try:
with open(
speech_log_path, "r", encoding="utf-8", errors="ignore"
) as f:
crash_info["speech_log"] = f.read()[-5000:] # Last 5KB
logs_found = True
except Exception as e:
crash_info["speech_log"] = f"Failed to read speech log: {e}"
else:
missing_logs.append(f"factorio-access-speech.log at {speech_log_path}")
else:
missing_logs.append("script-output directory")
# Fail if no logs found and fail_hard is True
if fail_hard and not logs_found:
error_msg = (
"[CRITICAL] Cannot find any logs! Debugging is impossible without logs.\n"
)
error_msg += "Missing:\n"
for log in missing_logs:
error_msg += f" - {log}\n"
error_msg += "\nRun with --show-paths to see where logs are expected."
raise LogsNotFoundError(error_msg)
return crash_info
def save_crash_report(crash_info: Dict[str, Any]) -> Path:
"""Save crash report to JSON file."""
timestamp = time.strftime("%Y%m%d_%H%M%S")
crash_file = Path(f"factorio_crash_{timestamp}.json")
with open(crash_file, "w", encoding="utf-8") as f:
json.dump(crash_info, f, indent=2)
return crash_file
def detect_module_loading_errors(output_file: str = None) -> Optional[Dict[str, Any]]:
"""Detect Factorio module loading errors from output.
Args:
output_file: Path to temporary output file (if buffering was used)
Returns:
Dict with error information if module loading failed, None otherwise
"""
# Check the temporary output file if provided
if output_file and os.path.exists(output_file):
try:
with open(output_file, "r", encoding="utf-8", errors="ignore") as f:
content = f.read()
# Look for module loading errors
# Pattern: Error Util.cpp:81: __ModName__/path: module ... not found
module_error = re.search(
r"Error\s+\w+\.cpp:\d+:\s+(.+?):\s*module\s+(.+?)\s+not found",
content
)
if module_error:
return {
"error_type": "module_not_found",
"location": module_error.group(1),
"module": module_error.group(2),
"full_error": module_error.group(0)
}
# Also check for other loading errors
generic_error = re.search(
r"Error\s+\w+\.cpp:\d+:\s+(.+)",
content
)
if generic_error:
return {
"error_type": "loading_error",
"full_error": generic_error.group(0),
"details": generic_error.group(1)
}
except Exception:
pass
return None
def parse_test_results(log_path: str) -> Optional[Dict[str, Any]]:
"""Parse test results from log file."""
log_path = Path(log_path)
if not log_path.exists():
return None
try:
with open(log_path, "r", encoding="utf-8", errors="ignore") as f:
content = f.read()
summary = {
"total": 0,
"passed": 0,
"failed": 0,
"success_rate": 0.0,
"duration": "unknown",
"failures": [],
}
# Parse TestFramework output format (PASS/FAIL or checkmarks)
# Try both Unicode checkmarks and ASCII text
passed_tests = re.findall(r"TestFramework: (?:✓|PASS:) (.+?)(?:\n|$)", content)
# Look for failed tests - they appear after ERROR
failed_tests = re.findall(
r"\[ERROR\] TestFramework: (?:✗|FAIL:) (.+?):", content
)
summary["passed"] = len(passed_tests)
summary["failed"] = len(failed_tests)
summary["failures"] = failed_tests[:10] # Limit to first 10
summary["total"] = summary["passed"] + summary["failed"]
if summary["total"] > 0:
summary["success_rate"] = (summary["passed"] / summary["total"]) * 100
return summary
except Exception:
return None
def parse_factorio_args() -> argparse.Namespace:
"""Parse command line arguments."""
parser = argparse.ArgumentParser(
description="Factorio Windows Launcher for FactorioAccess development",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
# Commands group
commands = parser.add_argument_group("commands")
commands.add_argument(
"--show-paths", action="store_true", help="Show important paths for debugging"
)
commands.add_argument(
"--capture-logs", action="store_true", help="Capture current logs for debugging"
)
commands.add_argument(
"--debug-logs", action="store_true", help="Show detailed debug information"
)
commands.add_argument("--lint", action="store_true", help="Run Lua linter")
commands.add_argument(
"--format", action="store_true", help="Apply code formatting with stylua"
)
commands.add_argument(
"--format-check", action="store_true", help="Check code formatting"
)
commands.add_argument("--run-tests", action="store_true", help="Run all tests")
# Tool paths
tools = parser.add_argument_group("tool paths")
tools.add_argument("--lua-ls-path", help="Path to lua-language-server executable")
tools.add_argument("--stylua-path", help="Path to stylua executable")
# Factorio options
factorio = parser.add_argument_group("factorio options")
factorio.add_argument(
"--factorio-path",
default="../../bin/x64/factorio.exe",
help="Path to Factorio executable",
)
factorio.add_argument("--timeout", type=int, help="Timeout in seconds")
factorio.add_argument("--mod-directory", help="Mod directory path")
factorio.add_argument("--config", help="Config file path")
factorio.add_argument("--executable-path", help="Executable path for Factorio")
factorio.add_argument("--create", help="Create new save")
factorio.add_argument("--load-game", help="Load save game")
factorio.add_argument("--benchmark", help="Run benchmark")
factorio.add_argument("--mp-connect", help="Connect to multiplayer server")
# Test options
test_options = parser.add_argument_group("test options")
test_options.add_argument(
"--lua-tests",
choices=["all", "syntrax", "ds", "railutils"],
default="all",
help="Which Lua tests to run",
)
test_options.add_argument(
"--verbose", action="store_true", help="Verbose output for tests"
)
# Output options
output = parser.add_argument_group("output options")
output.add_argument(
"--no-capture", action="store_true", help="Don't capture Factorio output"
)
output.add_argument("--buffered", action="store_true", help="Use buffered output")
output.add_argument(
"--json-status", action="store_true", help="Output status as JSON"
)
output.add_argument(
"--last-lines",
type=int,
default=100,
help="Number of log lines to show on error",
)
# Other options
parser.add_argument(
"--dry-run", action="store_true", help="Show command without executing"
)
parser.add_argument("--shell", action="store_true", help="Use shell execution")
parser.add_argument(
"extra_args", nargs="*", default=[], help="Extra arguments to pass to Factorio"
)
return parser.parse_args()
def main():
"""Main entry point."""
args = parse_factorio_args()
# Handle show-paths
if args.show_paths or args.debug_logs:
factorio_dir = Path(__file__).parent.parent.parent
mod_dir = Path(__file__).parent
script_output = find_script_output_dir()
print("=" * 60)
print("FACTORIO ACCESS LAUNCHER - PATH INFORMATION")
print("=" * 60)
print(f"Factorio directory: {factorio_dir}")
print(f"Mod directory: {mod_dir}")
print(f"Working directory: {Path.cwd()}")
factorio_exe = factorio_dir / "bin" / "x64" / "factorio.exe"
if factorio_exe.exists():
print(f"Factorio executable: {factorio_exe} [EXISTS]")
else:
print(f"Factorio executable: {factorio_exe} [NOT FOUND]")
if script_output:
print(f"Script output directory: {script_output}")
# Check for specific files
for log_file in [
"factorio-access-speech.log",
"factorio-access.log",
"factorio-access-test.log",
]:
log_path = script_output / log_file
if log_path.exists():
print(f" - {log_file}: {log_path}")
else:
print(f" - {log_file}: Not found")
else:
print("Script output directory: Not found")
print("=" * 60)
return 0
# Handle capture-logs
if args.capture_logs:
print("[INFO] Capturing Factorio logs from manual run...")
try:
crash_info = capture_crash_info(1, fail_hard=True)
except LogsNotFoundError as e:
print(str(e))
return 2
# Save the report
crash_report_path = save_crash_report(crash_info)
print(f"[INFO] Log capture saved to: {crash_report_path}")
# Show recent speech log entries
if crash_info.get("speech_log"):
print("\n[INFO] === Last lines of speech log ===")
lines = crash_info["speech_log"].split("\n")[-50:]
print("\n".join(lines))
return 0
# Handle linting
if args.lint:
mod_path = Path(__file__).parent.resolve()
# First check annotations
print(f"[INFO] Checking LuaLS annotations in {mod_path}")
ann_exit_code, ann_errors = check_lua_annotations()
if ann_errors:
print(f"Found {len(ann_errors) // 2} incorrect annotation(s):")
for error in ann_errors:
print(error)
# Check for non-top-level requires
print(f"\n[INFO] Checking for non-top-level require() statements in {mod_path}")
req_exit_code, req_errors = check_non_top_level_requires()
if req_errors:
print(f"Found {len(req_errors) // 3} non-top-level require(s):")
for error in req_errors: