Repository navigation
Expand file tree
/
Copy pathunitycli.sh
More file actions
1785 lines (1605 loc) · 52.6 KB
/
Copy pathunitycli.sh
File metadata and controls
1785 lines (1605 loc) · 52.6 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 bash
# Exit immediately if a command exits with a non-zero status,
# but we handle Unity exit codes manually.
set -u
# Change working directory to the project root
if [ -n "${UNITY_CLI_PROJECT_ROOT:-}" ]; then
cd "$UNITY_CLI_PROJECT_ROOT" || exit 1
fi
# Detect the host once. The script is always run by Bash, including on
# Windows through Git Bash/MSYS/Cygwin, so uname is more reliable here than
# mutable environment variables.
detect_platform() {
case "$(uname -s 2>/dev/null || true)" in
Darwin)
echo "macos"
;;
Linux)
echo "linux"
;;
MINGW*|MSYS*|CYGWIN*)
echo "windows"
;;
*)
echo "unknown"
;;
esac
}
PLATFORM="$(detect_platform)"
if [ "$PLATFORM" = "unknown" ]; then
echo "Error: Unsupported host platform. Run unitycli.sh from Bash on Linux, macOS, or Windows Git Bash." >&2
exit 1
fi
is_windows_platform() {
[ "$PLATFORM" = "windows" ]
}
# Convert paths between the POSIX view used by Bash and the native Windows
# view used by Win32 programs. On Unix this is intentionally a no-op.
to_shell_path() {
local path="$1"
if is_windows_platform && command -v cygpath >/dev/null 2>&1; then
cygpath -u "$path" 2>/dev/null || printf '%s\n' "$path"
else
printf '%s\n' "$path"
fi
}
to_native_path() {
local path="$1"
if is_windows_platform && command -v cygpath >/dev/null 2>&1; then
cygpath -m -a "$path" 2>/dev/null || printf '%s\n' "$path"
else
printf '%s\n' "$path"
fi
}
PROJECT_PATH="$(pwd)"
PROJECT_NATIVE_PATH="$(to_native_path "$PROJECT_PATH")"
export UNITY_CLI_PROJECT_NATIVE="$PROJECT_NATIVE_PATH"
find_powershell() {
local command_name
for command_name in powershell.exe powershell pwsh.exe pwsh; do
if command -v "$command_name" >/dev/null 2>&1; then
command -v "$command_name"
return 0
fi
done
return 1
}
decode_base64() {
local decoder
if ! command -v base64 >/dev/null 2>&1; then
return 1
fi
if base64 -d </dev/null >/dev/null 2>&1; then
decoder="-d"
elif base64 -D </dev/null >/dev/null 2>&1; then
decoder="-D"
else
return 1
fi
base64 "$decoder"
}
# Cleanup background tail on exit
tail_pid=""
cleanup() {
if [ -n "$tail_pid" ]; then
kill "$tail_pid" 2>/dev/null
fi
}
trap cleanup EXIT INT TERM
new_operation_id() {
# Token-safe on Bash 3.2 (macOS), Linux, and Windows Git Bash. It only needs
# to be unique within one project, not cryptographically random.
printf 'cli-%s-%s-%s-%s\n' "$(date +%s)" "$$" "$RANDOM" "$RANDOM"
}
# Default options
SUBCOMMAND=""
MODE_PLAYMODE=false
MODE_EDITMODE=false
FILTER=""
CATEGORY=""
EXECUTE_METHOD=""
EXECUTE_METHOD_PARAMS=()
EVAL_CODE=""
BG_ACTION=""
BG_MODE=""
# Helper for usage
show_usage() {
local exit_code="${1:-1}"
echo "Usage: $0 <command> [options]"
echo "Commands:"
echo " start <mode> Start a background Unity instance (mode: batchmode | interactive)"
echo " stop Stop the background Unity instance"
echo " status Check status of the background Unity instance"
echo " refresh Trigger AssetDatabase refresh and print compiler diagnostics"
echo " recompile Force a full C# recompilation and print compiler diagnostics"
echo " test [options] Run tests (defaults to running both EditMode and PlayMode)"
echo " --playmode Run PlayMode tests"
echo " --editmode Run EditMode tests"
echo " --filter <filter> Filter tests by name (regex/substring)"
echo " --category <category> Filter tests by category"
echo " executemethod <method> [args...] Execute a custom static method (optionally with parameters)"
echo " (e.g., Namespace.Class.Method 4 3 \"{\\\"Value\\\":4}\")"
echo " eval <code> Evaluate a live C# expression or script dynamically"
echo " (e.g., \"Application.unityVersion\" or \"1 + 1\")"
echo " -h, --help Show this help message"
exit "$exit_code"
}
if [ $# -eq 0 ]; then
show_usage
fi
SUBCOMMAND="$1"
shift
case "$SUBCOMMAND" in
refresh)
if [ $# -gt 0 ]; then
echo "Error: refresh does not accept extra arguments"
show_usage
fi
;;
recompile)
if [ $# -gt 0 ]; then
echo "Error: recompile does not accept extra arguments"
show_usage
fi
;;
test)
while [[ $# -gt 0 ]]; do
case "$1" in
--playmode)
MODE_PLAYMODE=true
shift
;;
--editmode)
MODE_EDITMODE=true
shift
;;
--filter)
if [ -z "${2:-}" ]; then
echo "Error: --filter requires an argument"
show_usage
fi
FILTER="$2"
shift 2
;;
--filter=*)
FILTER="${1#*=}"
shift
;;
--category)
if [ -z "${2:-}" ]; then
echo "Error: --category requires an argument"
show_usage
fi
CATEGORY="$2"
shift 2
;;
--category=*)
CATEGORY="${1#*=}"
shift
;;
-h|--help)
show_usage 0
;;
*)
echo "Unknown option for test subcommand: $1"
show_usage
;;
esac
done
# If neither mode is specified, default to running both
if [ "$MODE_PLAYMODE" = false ] && [ "$MODE_EDITMODE" = false ]; then
MODE_PLAYMODE=true
MODE_EDITMODE=true
fi
;;
executemethod)
if [ $# -eq 0 ]; then
echo "Error: executemethod requires a method name argument (e.g., Namespace.Class.Method)"
show_usage
fi
EXECUTE_METHOD="$1"
shift
EXECUTE_METHOD_PARAMS=("$@")
shift $#
;;
eval)
if [ $# -eq 0 ]; then
echo "Error: eval requires a C# code snippet or expression (e.g., Application.unityVersion)"
show_usage
fi
EVAL_CODE="$*"
shift $#
;;
start)
if [ $# -eq 0 ]; then
echo "Error: start command requires a mode (batchmode|interactive)"
show_usage
fi
BG_MODE="$1"
if [ "$BG_MODE" != "batchmode" ] && [ "$BG_MODE" != "interactive" ]; then
echo "Error: start command mode must be batchmode or interactive"
show_usage
fi
shift
if [ $# -gt 0 ]; then
echo "Error: start command does not accept extra arguments"
show_usage
fi
;;
stop)
if [ $# -gt 0 ]; then
echo "Error: stop command does not accept extra arguments"
show_usage
fi
;;
status)
if [ $# -gt 0 ]; then
echo "Error: status command does not accept extra arguments"
show_usage
fi
;;
-h|--help|help)
show_usage 0
;;
*)
echo "Unknown command: $SUBCOMMAND"
show_usage
;;
esac
# Function to send a command to the socket server
send_socket_cmd() {
local cmd="$1"
local timeout="${2:-10}"
# Read dynamic port
local port=""
if [ -f "Temp/unity_cli_port.txt" ]; then
port=$(cat "Temp/unity_cli_port.txt" | tr -d '[:space:]')
fi
if [ -z "$port" ] || ! [[ "$port" =~ ^[0-9]+$ ]] || [ "$port" -lt 1 ] || [ "$port" -gt 65535 ]; then
return 1
fi
local response=""
local socket_exit_code=0
# Bash implements /dev/tcp on Linux, macOS, and Git Bash. Do not probe the
# port first: that creates a second connection and races with domain reloads.
# The surrounding redirection is important because Bash can otherwise print
# connection-refused diagnostics before the command-level redirection runs.
response=$(
{
exec 3<>"/dev/tcp/127.0.0.1/$port" || exit 1
printf '%s\n' "$cmd" >&3 || exit 1
IFS= read -r -t "$timeout" line <&3 || exit 1
printf '%s\n' "$line"
} 2>/dev/null
) || socket_exit_code=$?
if [ "$socket_exit_code" -ne 0 ] && is_windows_platform; then
# PowerShell is retained only as a Windows fallback for environments where
# the Git Bash /dev/tcp extension cannot connect to a native Win32 socket.
local powershell_command=""
powershell_command=$(find_powershell || true)
if [ -n "$powershell_command" ]; then
socket_exit_code=0
local timeout_ms=$((timeout * 1000))
export UNITY_CLI_CMD="$cmd"
response=$("$powershell_command" -NoProfile -Command "
\$ErrorActionPreference = 'Stop';
try {
\$c = New-Object System.Net.Sockets.TcpClient('127.0.0.1', $port);
\$c.ReceiveTimeout = $timeout_ms;
\$w = New-Object System.IO.StreamWriter(\$c.GetStream());
\$r = New-Object System.IO.StreamReader(\$c.GetStream());
\$w.WriteLine(\$env:UNITY_CLI_CMD);
\$w.Flush();
\$res = \$r.ReadLine();
\$c.Close();
Write-Output \$res;
} catch {
Write-Error \$_.Exception.GetType().Name;
exit 1;
}
" 2>&1) || socket_exit_code=$?
unset UNITY_CLI_CMD
fi
fi
if [ "$socket_exit_code" -ne 0 ]; then
local lower_resp
lower_resp=$(echo "$response" | tr '[:upper:]' '[:lower:]')
if [[ "$lower_resp" == *"operation not permitted"* || "$lower_resp" == *"forbidden by its access permissions"* || "$lower_resp" == *"permissiondenied"* || "$lower_resp" == *"unauthorizedaccessexception"* ]]; then
return 42
fi
return 1
fi
if [ -z "$response" ]; then
return 1
fi
# Strip carriage returns and trim whitespace
response=$(echo "$response" | tr -d '\r')
response="${response#"${response%%[![:space:]]*}"}"
response="${response%"${response##*[![:space:]]}"}"
echo "$response"
return 0
}
print_network_permission_error() {
echo "Error: Local network permission is required to connect to UnityCliRunner at 127.0.0.1. If you are running in a sandbox, allow network access and retry." >&2
}
# Check whether a process is alive. Bash can inspect POSIX processes directly;
# tasklist is the native Windows fallback. PowerShell is used only if that
# fallback is unavailable or cannot answer the query.
is_process_alive() {
local pid="$1"
if [ -z "$pid" ] || ! [[ "$pid" =~ ^[0-9]+$ ]]; then
return 1
fi
if kill -0 "$pid" 2>/dev/null; then
return 0
fi
if is_windows_platform; then
local tasklist_command=""
local tasklist_name
for tasklist_name in tasklist.exe tasklist; do
if command -v "$tasklist_name" >/dev/null 2>&1; then
tasklist_command=$(command -v "$tasklist_name")
break
fi
done
if [ -n "$tasklist_command" ]; then
local tasklist_output=""
local tasklist_status=0
tasklist_output=$("$tasklist_command" //FI "PID eq $pid" //FO CSV //NH 2>/dev/null) || tasklist_status=$?
if [ "$tasklist_status" -eq 0 ]; then
if printf '%s\n' "$tasklist_output" | grep -q -F "\"$pid\""; then
return 0
fi
return 1
fi
fi
local powershell_command=""
powershell_command=$(find_powershell || true)
if [ -n "$powershell_command" ]; then
"$powershell_command" -NoProfile -Command "
\$process = Get-Process -Id $pid -ErrorAction SilentlyContinue;
if (\$null -ne \$process) { exit 0 } else { exit 1 }
" >/dev/null 2>&1
return $?
fi
fi
return 1
}
# Find the Unity lockfile used by this project.
get_unity_lockfile() {
if [ -f "Temp/UnityLockfile" ]; then
echo "Temp/UnityLockfile"
elif [ -f "Temp/UnityLockFile" ]; then
echo "Temp/UnityLockFile"
fi
}
# Return a live PID associated with the project lockfile, if one can be found.
# UnityLockfile is zero bytes on macOS, so the PID must be obtained from the
# file owner rather than from the file contents on that platform.
get_unity_lock_owner_pid() {
local lockfile="$1"
local pid=""
local filesize=""
if [ ! -f "$lockfile" ]; then
return 1
fi
filesize=$(wc -c < "$lockfile" 2>/dev/null | tr -d '[:space:]')
if [ "$filesize" = "4" ] && command -v od >/dev/null 2>&1; then
pid=$(od -An -t d4 -N 4 "$lockfile" 2>/dev/null | tr -d '[:space:]')
fi
if [ -z "$pid" ] || ! [[ "$pid" =~ ^[0-9]+$ ]]; then
pid=$(cat "$lockfile" 2>/dev/null | tr -d '\r')
pid="${pid#"${pid%%[![:space:]]*}"}"
pid="${pid%"${pid##*[![:space:]]}"}"
fi
if [[ "$pid" =~ ^[0-9]+$ ]] && is_process_alive "$pid"; then
echo "$pid"
return 0
fi
# lsof -t emits only PIDs. Unlike fuser's macOS behaviour, its exit status
# is non-zero when the file has no owner.
if command -v lsof >/dev/null 2>&1; then
pid=$(lsof -nP -t "$lockfile" 2>/dev/null | head -n 1)
if [[ "$pid" =~ ^[0-9]+$ ]] && is_process_alive "$pid"; then
echo "$pid"
return 0
fi
fi
# Keep fuser as a Linux fallback, but inspect its output. On macOS it
# returns success for an unowned file and prints only "file:".
if command -v fuser >/dev/null 2>&1; then
local fuser_output=""
local candidate=""
fuser_output=$(fuser "$lockfile" 2>&1 || true)
if [[ "$fuser_output" == *:* ]]; then
fuser_output="${fuser_output#*:}"
fi
for candidate in $fuser_output; do
if [[ "$candidate" =~ ^[0-9]+$ ]] && is_process_alive "$candidate"; then
echo "$candidate"
return 0
fi
done
fi
return 1
}
remove_stale_unity_lockfiles() {
rm -f Temp/UnityLockfile Temp/UnityLockFile 2>/dev/null
}
is_unity_socket_ready() {
local timeout="${1:-1}"
local response=""
response=$(send_socket_cmd "PING" "$timeout" 2>/dev/null) || return 1
[ "$response" = "PONG" ]
}
# Kill exactly the supplied process. Never fall back to killing Unity by image
# name because that can terminate unrelated projects/editors.
kill_process() {
local pid="$1"
if [ -z "$pid" ] || ! [[ "$pid" =~ ^[0-9]+$ ]]; then
return 1
fi
if is_windows_platform; then
if command -v taskkill.exe >/dev/null 2>&1; then
taskkill.exe //PID "$pid" //F >/dev/null 2>&1
return $?
elif command -v taskkill >/dev/null 2>&1; then
taskkill //PID "$pid" //F >/dev/null 2>&1
return $?
fi
fi
kill -9 "$pid" >/dev/null 2>&1
}
# Find the Unity process for this project on Windows. Unity's lockfile is
# opened with sharing restrictions, so querying the command line is the only
# reliable fallback when the socket and our own PID file are unavailable.
find_windows_unity_pid() {
if ! is_windows_platform; then
return 1
fi
local powershell_command=""
powershell_command=$(find_powershell || true)
if [ -z "$powershell_command" ]; then
return 1
fi
"$powershell_command" -NoProfile -Command "
\$project = [string]\$env:UNITY_CLI_PROJECT_NATIVE;
if ([string]::IsNullOrEmpty(\$project)) { exit 1 }
\$project = \$project.Replace('/', '\').TrimEnd('\');
\$process = Get-CimInstance Win32_Process -Filter \"Name = 'Unity.exe'\" |
Where-Object {
\$commandLine = [string]\$_.CommandLine;
if ([string]::IsNullOrEmpty(\$commandLine)) { return \$false }
\$normalizedCommand = \$commandLine.Replace('/', '\');
return \$normalizedCommand.IndexOf(\$project, [StringComparison]::OrdinalIgnoreCase) -ge 0;
} | Select-Object -First 1;
if (\$null -ne \$process) { \$process.ProcessId }
" 2>/dev/null | tr -d '\r'
}
# Function to check if Unity is still running.
is_unity_still_running() {
# Socket readiness is checked separately; use the project identity markers
# below for liveness so a stale port file cannot keep Unity marked active.
# Prefer the exact PID recorded when this CLI launched Unity. This works
# during startup before the socket server has written its port file.
local pid_file="Temp/unity_cli_process.pid"
if [ -f "$pid_file" ]; then
local pid=""
pid=$(cat "$pid_file" 2>/dev/null | tr -d '\r')
pid="${pid#"${pid%%[![:space:]]*}"}"
pid="${pid%"${pid##*[![:space:]]}"}"
if is_process_alive "$pid"; then
return 0
fi
rm -f "$pid_file" 2>/dev/null
fi
local lockfile=""
if [ -f "Temp/UnityLockfile" ]; then
lockfile="Temp/UnityLockfile"
elif [ -f "Temp/UnityLockFile" ]; then
lockfile="Temp/UnityLockFile"
fi
if is_windows_platform; then
local windows_pid=""
windows_pid=$(find_windows_unity_pid || true)
if [[ "$windows_pid" =~ ^[0-9]+$ ]] && is_process_alive "$windows_pid"; then
return 0
fi
if [ -n "$lockfile" ]; then
remove_stale_unity_lockfiles
fi
return 1
fi
if [ -z "$lockfile" ]; then
return 1
fi
# On Unix-like systems (Linux/macOS)
# 1. Try flock command-line utility first (handles 0-byte lockfiles on Linux)
if command -v flock >/dev/null 2>&1; then
if ! flock -n "$lockfile" -c true >/dev/null 2>&1; then
return 0 # Locked -> Unity is running
fi
fi
# 2. Check the actual owner. This is required on macOS where the lockfile
# is a zero-byte file and fuser may succeed without finding a process.
local pid=""
pid=$(get_unity_lock_owner_pid "$lockfile" 2>/dev/null || true)
if [[ "$pid" =~ ^[0-9]+$ ]]; then
return 0
fi
# Stale lockfile
remove_stale_unity_lockfiles
return 1
}
# Detect if Unity is running for this specific project
IS_RUNNING=false
AUTO_STARTED=false
if is_unity_still_running; then
IS_RUNNING=true
fi
# Function to find Unity path
find_unity_path() {
local configured_path="${UNITY_PATH:-${UNITY_EDITOR:-}}"
if [ -n "$configured_path" ]; then
local shell_configured_path=""
shell_configured_path=$(to_shell_path "$configured_path" | tr -d '\r')
if [ -f "$shell_configured_path" ]; then
printf '%s\n' "$shell_configured_path"
return 0
fi
fi
# Prioritize unity-editor wrapper from PATH if explicitly requested via environment variable
if [ "${USE_UNITY_EDITOR_WRAPPER:-false}" = "true" ]; then
local container_unity=""
container_unity=$(command -v unity-editor 2>/dev/null | tr -d '\r')
if [ -n "$container_unity" ]; then
echo "$container_unity"
return 0
fi
fi
local version=""
if [ -f "ProjectSettings/ProjectVersion.txt" ]; then
version=$(grep "m_EditorVersion:" ProjectSettings/ProjectVersion.txt | awk '{print $2}' | tr -d '\r')
fi
local paths=()
if [ -n "$version" ]; then
if is_windows_platform; then
[ -n "${ProgramFiles:-}" ] && paths+=("$ProgramFiles/Unity/Hub/Editor/$version/Editor/Unity.exe")
[ -n "${ProgramW6432:-}" ] && paths+=("$ProgramW6432/Unity/Hub/Editor/$version/Editor/Unity.exe")
[ -n "${LOCALAPPDATA:-}" ] && paths+=("$LOCALAPPDATA/Unity/Hub/Editor/$version/Editor/Unity.exe")
paths+=(
"C:/Program Files/Unity/Hub/Editor/$version/Editor/Unity.exe"
"C:/Program Files (x86)/Unity/Hub/Editor/$version/Editor/Unity.exe"
"C:/Unity/Hub/Editor/$version/Editor/Unity.exe"
)
elif [ "$PLATFORM" = "macos" ]; then
paths=(
"/Applications/Unity/Hub/Editor/$version/Unity.app/Contents/MacOS/Unity"
"$HOME/Unity/Hub/Editor/$version/Unity.app/Contents/MacOS/Unity"
)
else
paths=(
"$HOME/Unity/Hub/Editor/$version/Editor/Unity"
"/opt/unity/Editor/Unity"
"/opt/Unity/Editor/Unity"
)
fi
fi
for p in "${paths[@]}"; do
local shell_path=""
shell_path=$(to_shell_path "$p" | tr -d '\r')
if [ -f "$shell_path" ]; then
printf '%s\n' "$shell_path"
return 0
fi
done
local command_unity=""
local cmd
for cmd in unity-editor Unity Unity.exe unity.exe unity; do
command_unity=$(command -v "$cmd" 2>/dev/null | tr -d '\r')
if [ -n "$command_unity" ]; then
printf '%s\n' "$command_unity"
return 0
fi
done
if is_windows_platform && command -v where.exe >/dev/null 2>&1; then
command_unity=$(where.exe unity 2>/dev/null | head -n 1 | tr -d '\r')
if [ -n "$command_unity" ]; then
shell_path=$(to_shell_path "$command_unity" | tr -d '\r')
if [ -f "$shell_path" ]; then
printf '%s\n' "$shell_path"
return 0
fi
fi
fi
return 1
}
# Function to start background Unity instance or wait for it to be ready
start_background_unity() {
local mode="${1:-batchmode}"
local unity_pid=""
local needs_launch=true
if is_unity_still_running; then
needs_launch=false
# Check if already ready
if [ -f "Temp/unity_cli_port.txt" ] && is_unity_socket_ready 2; then
local resp
resp=$(send_socket_cmd "POLL_REFRESH" 2 2>/dev/null)
if [ "$resp" = "READY" ] || [ "$resp" = "COMPILATION_ERROR" ]; then
echo "Unity is already running."
IS_RUNNING=true
return 0
fi
fi
echo "Unity is already running/starting. Skipping launch..."
echo -n "Waiting for Unity background instance to be ready..."
fi
if [ "$needs_launch" = true ]; then
UNITY_EXE=$(find_unity_path)
if [ -z "$UNITY_EXE" ]; then
local project_version=""
if [ -f "ProjectSettings/ProjectVersion.txt" ]; then
project_version=$(grep "m_EditorVersion:" ProjectSettings/ProjectVersion.txt | awk '{print $2}' | tr -d '\r')
fi
echo "Error: Unity executable not found for Unity version ${project_version:-unknown}."
exit 1
fi
echo -n "Starting Unity background instance..."
mkdir -p Temp
rm -f unity_background_log.txt unity_stdout_stderr.txt
# Run Unity in background (batchmode or interactive)
local abs_proj_path
abs_proj_path="$PROJECT_NATIVE_PATH"
local auth_args=()
local user="${UNITY_EMAIL:-${UNITY_USERNAME:-}}"
if [ -n "$user" ] && [ -n "${UNITY_PASSWORD:-}" ] && [ -n "${UNITY_LICENSE:-}" ]; then
local dev_data
# Use POSIX sed; macOS's default grep does not support GNU -P.
dev_data=$(printf '%s' "$UNITY_LICENSE" | tr -d '\r\n' | sed -n 's/.*<DeveloperData Value="\([^"]*\)".*/\1/p')
if [ -n "$dev_data" ]; then
local serial
serial=$(printf '%s' "$dev_data" | decode_base64 | dd bs=1 skip=4 2>/dev/null)
if [ -n "$serial" ]; then
auth_args+=("-username" "$user" "-password" "$UNITY_PASSWORD" "-serial" "$serial")
fi
fi
fi
local launch_args=()
if [ "$mode" = "batchmode" ]; then
launch_args+=("-batchmode" "-nographics")
fi
launch_args+=("-projectPath" "$abs_proj_path" "-logFile" "unity_background_log.txt")
if [ ${#auth_args[@]} -gt 0 ]; then
launch_args+=("${auth_args[@]}")
fi
if is_windows_platform; then
# Pass each argument through the environment so PowerShell does not
# reinterpret spaces, quotes, dollar signs, or backslashes in values.
local arg_count=${#launch_args[@]}
local arg_index=0
export UNITY_CLI_ARG_COUNT="$arg_count"
for a in "${launch_args[@]}"; do
export "UNITY_CLI_ARG_$arg_index=$a"
arg_index=$((arg_index + 1))
done
local unity_exe_native="$UNITY_EXE"
if [ -f "$UNITY_EXE" ]; then
unity_exe_native=$(to_native_path "$UNITY_EXE" | tr -d '\r')
fi
local powershell_command=""
powershell_command=$(find_powershell || true)
if [ -n "$powershell_command" ]; then
export UNITY_CLI_UNITY_EXE="$unity_exe_native"
unity_pid=$("$powershell_command" -NoProfile -Command "
\$arguments = @();
for (\$i = 0; \$i -lt [int]\$env:UNITY_CLI_ARG_COUNT; \$i++) {
\$arguments += [Environment]::GetEnvironmentVariable(('UNITY_CLI_ARG_' + \$i));
}
\$p = Start-Process -FilePath \$env:UNITY_CLI_UNITY_EXE -ArgumentList \$arguments -PassThru;
\$p.Id
" 2>/dev/null | tr -d '\r')
unset UNITY_CLI_UNITY_EXE
else
# Git Bash can still launch Unity directly if PowerShell is unavailable;
# the PID is retained as the best available fallback.
"$UNITY_EXE" "${launch_args[@]}" >>unity_stdout_stderr.txt 2>&1 &
unity_pid=$!
fi
arg_index=0
while [ "$arg_index" -lt "$arg_count" ]; do
unset "UNITY_CLI_ARG_$arg_index"
arg_index=$((arg_index + 1))
done
unset UNITY_CLI_ARG_COUNT
else
nohup "$UNITY_EXE" "${launch_args[@]}" >>unity_stdout_stderr.txt 2>&1 &
unity_pid=$!
fi
if [[ "$unity_pid" =~ ^[0-9]+$ ]]; then
printf '%s\n' "$unity_pid" > Temp/unity_cli_process.pid
fi
fi
local started=false
# Wait up to 90 seconds (45 iterations * 2s sleep)
for i in {1..45}; do
if is_unity_still_running && [ -f "Temp/unity_cli_port.txt" ]; then
if is_unity_socket_ready 2; then
local response
response=$(send_socket_cmd "POLL_REFRESH" 2 2>/dev/null)
if [ "$response" = "READY" ] || [ "$response" = "COMPILATION_ERROR" ]; then
echo ""
if [ "$needs_launch" = true ]; then
echo "Started successfully!"
else
echo "Unity is ready!"
fi
started=true
break
fi
fi
fi
# Check for compilation errors in the log file
if [ -f "unity_background_log.txt" ]; then
if grep -q -E '^([a-zA-Z]:)?[a-zA-Z0-9_./\\ -]+\([0-9]+,[0-9]+\): error [a-zA-Z0-9]+:' "unity_background_log.txt"; then
echo ""
echo "Compilation errors detected during startup."
# Sleep a moment to let all errors be written
sleep 2
# Extract all errors/warnings and save to Temp/unity_compilation_errors.txt
mkdir -p Temp
grep -E '^([a-zA-Z]:)?[a-zA-Z0-9_./\\ -]+\([0-9]+,[0-9]+\): (error|warning) [a-zA-Z0-9]+:' "unity_background_log.txt" | awk '!seen[$0]++' > Temp/unity_compilation_errors.txt
parse_and_print_compilation_results "Temp/unity_compilation_errors.txt"
if [ -n "$unity_pid" ]; then
echo "Killing Unity process (PID $unity_pid)..."
kill_process "$unity_pid"
fi
exit 1
fi
fi
# Check if the process exited unexpectedly
local process_exited=false
if [ "$needs_launch" = true ] && [ -n "$unity_pid" ]; then
if ! is_process_alive "$unity_pid"; then
process_exited=true
fi
elif [ "$needs_launch" = false ]; then
if ! is_unity_still_running; then
process_exited=true
fi
fi
if [ "$process_exited" = true ]; then
echo ""
echo "Unity process exited unexpectedly."
if [ -f "unity_background_log.txt" ]; then
if grep -q -E '^([a-zA-Z]:)?[a-zA-Z0-9_./\\ -]+\([0-9]+,[0-9]+\): error [a-zA-Z0-9]+:' "unity_background_log.txt"; then
mkdir -p Temp
grep -E '^([a-zA-Z]:)?[a-zA-Z0-9_./\\ -]+\([0-9]+,[0-9]+\): (error|warning) [a-zA-Z0-9]+:' "unity_background_log.txt" | awk '!seen[$0]++' > Temp/unity_compilation_errors.txt
parse_and_print_compilation_results "Temp/unity_compilation_errors.txt"
exit 1
else
echo "Last 20 lines of Unity log:"
tail -n 20 "unity_background_log.txt"
exit 1
fi
else
echo "No Unity log file found."
echo "Listing Temp directory:"
ls -la Temp/ 2>/dev/null || echo "No Temp/ directory"
if [ -f "unity_stdout_stderr.txt" ]; then
echo "Contents of unity_stdout_stderr.txt:"
cat "unity_stdout_stderr.txt"
else
echo "unity_stdout_stderr.txt does not exist"
fi
exit 1
fi
fi
echo -n "."
sleep 2
done
if [ "$started" = false ]; then
echo ""
echo "Failed to start background Unity instance or wait for it to be ready."
exit 1
fi
IS_RUNNING=true
if [ "$needs_launch" = true ]; then
AUTO_STARTED=true
fi
}
# Function to print failed tests in dotnet test format
print_failed_tests() {
local failures_file="Temp/unity_test_failures.txt"
local results_file="Temp/unity_test_results.json"
if [ -f "$failures_file" ]; then
cat "$failures_file"
rm -f "$failures_file"
rm -f "$results_file" 2>/dev/null
fi
}
json_result_matches() {
local file="$1"
local field="$2"
local expected="$3"
[ -f "$file" ] || return 1
command -v perl >/dev/null 2>&1 || return 1
perl -MJSON::PP -e '
local $/;
open(my $f, "<:utf8", $ARGV[0]) or exit 1;
my $data = eval { decode_json(<$f>) } or exit 1;
exit((defined $data->{$ARGV[1]} && $data->{$ARGV[1]} eq $ARGV[2]) ? 0 : 1);
' "$file" "$field" "$expected" 2>/dev/null
}
test_running_matches() {
json_result_matches "Temp/unity_test_running.txt" "runId" "$1"
}
plain_marker_matches() {
local file="$1"
local expected="$2"
[ -f "$file" ] || return 1
[ "$(tr -d '[:space:]' < "$file" 2>/dev/null)" = "$expected" ]
}
# Function to parse test results from Temp/unity_test_results.json if process exited/recycled
parse_and_handle_test_results_file() {
local results_file="Temp/unity_test_results.json"
local expected_operation_id="${1:-}"
if [ ! -f "$results_file" ]; then
return 2
fi
if [ -n "$expected_operation_id" ] && ! json_result_matches "$results_file" "runId" "$expected_operation_id"; then
return 2
fi
if ! command -v perl >/dev/null 2>&1 || ! perl -MJSON::PP -e 'exit 0' 2>/dev/null; then
echo "Error: Perl with JSON::PP module is required to parse test results." >&2
return 1
fi
perl -MJSON::PP -e '
local $/;
open(my $f, "<:utf8", $ARGV[0]) or exit 2;
my $data = decode_json(<$f>);
my $pass_cnt = $data->{passCount} || 0;
my $fail_cnt = $data->{failCount} || 0;
my $skip_cnt = $data->{skipCount} || 0;
my $skip_str = $skip_cnt > 0 ? ", $skip_cnt skipped" : "";
print "\nDone!\n";
if ($data->{success}) {
print "Unity Response: SUCCESS $pass_cnt passed$skip_str\n";
exit 0;
} else {
my $msg = $data->{message};
my $state = $data->{resultState} || "";
if ($state eq "Interrupted") {
print "Unity Response: INTERRUPTION " . (($msg // "") ne "" ? $msg : "Test run was interrupted by Unity domain reload or shutdown.") . "\n";
} elsif (defined $msg && $msg ne "") {
print "Unity Response: FAILURE $msg\n";
} else {
print "Unity Response: FAILURE $fail_cnt failed, $pass_cnt passed$skip_str\n";
}
exit 1;
}
' "$results_file"
local status=$?
if [ $status -ne 0 ]; then
print_failed_tests
fi
return $status
}
# Function to parse execute results from Temp/unity_execute_result.json if process exited/recycled
parse_and_handle_execute_results_file() {
local results_file="Temp/unity_execute_result.json"
local expected_operation_id="${1:-}"
if [ ! -f "$results_file" ]; then
return 2
fi
if [ -n "$expected_operation_id" ] && ! json_result_matches "$results_file" "operationId" "$expected_operation_id"; then
return 2
fi
if ! command -v perl >/dev/null 2>&1 || ! perl -MJSON::PP -e 'exit 0' 2>/dev/null; then
echo "Error: Perl with JSON::PP module is required to parse execute results." >&2