-
Notifications
You must be signed in to change notification settings - Fork 3
/
mettalog
executable file
·773 lines (634 loc) · 24.3 KB
/
mettalog
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
#!/bin/bash
function quote_arg {
# Check if the argument contains single quotes
if [[ $1 == *\'* ]]; then
# Argument contains single quotes, use double quotes and escape necessary characters
local escaped=${1//\\/\\\\} # Escape backslashes
escaped=${escaped//\"/\\\"} # Escape double quotes
echo "\"$escaped\"" # Wrap in double quotes
else
# Use single quotes for arguments without single quotes, no escaping needed
echo "'$1'"
fi
}
function quote_args_if_needed {
local -a quoted_array=() # Initialize an empty array to store the results
for arg in "$@"; do
# Check if the argument contains spaces, exclamation marks, backslashes, or quote characters
if [[ $arg =~ [[:space:]] || $arg == *'!'* || $arg == *'\\'* || $arg == *\"* || $arg == *\'* ]]; then
# The argument needs to be quoted
local quoted_arg=$(quote_arg "$arg")
quoted_array+=("$quoted_arg")
else
# The argument does not need quoting
quoted_array+=("$arg")
fi
done
# Output the array elements without newlines, joined by spaces
echo "${quoted_array[*]}"
}
function remove_quotes {
local arg="$1"
# Determine the type of quote at the start (if any)
local first_char="${arg:0:1}"
if [[ $first_char == '"' ]]; then
# Double-quoted: Remove leading and trailing quotes and unescape backslashes and double quotes
arg="${arg#\"}"
arg="${arg%\"}"
arg="${arg//\\\\/\\}"
arg="${arg//\\\"/\"}"
elif [[ $first_char == "'" ]]; then
# Single-quoted: Remove leading and trailing quotes
# Note: Inside single quotes, backslashes and double quotes are treated literally
arg="${arg#\'}"
arg="${arg%\'}"
fi
echo "$arg"
}
function unquote_arg {
# Remove leading and trailing quotes
local arg="$1"
arg="${arg#\'}"
arg="${arg%\'}"
arg="${arg#\"}"
arg="${arg%\"}"
# Unescape escaped characters
arg="${arg//\\\\/\\}" # Unescape backslashes
arg="${arg//\\\"/\"}" # Unescape double quotes
arg="${arg//\\\'/\'}" # Unescape single quotes (if needed, depending on usage context)
echo "$arg"
}
debug_this_script=true
do_DEBUG() {
# Calculate the screen width and 74% of it
local screen_width=$(tput cols)
local threshold=$((screen_width * 74 / 100))
# Construct the debug message
local msg="; DEBUG $*"
# Calculate the length of the debug message
local msg_length=${#msg}
if [ "$msg_length" -gt "$threshold" ]; then
# If the message is longer than 74% of the screen width,
# print a newline before and after the message
echo >&2
echo "$msg" >&2
echo >&2
else
# If the message is not longer than 74% of the screen width, print it as usual
echo "$msg" >&2
fi
}
DEBUG() {
if [ "$debug_this_script" == "true" ]; then
do_DEBUG "$@"
fi
}
export RPWD=$PWD
IS_SOURCED=$( [[ "${BASH_SOURCE[0]}" != "${0}" ]] && echo 1 || echo 0)
# Function to exit the script properly
if [ "$IS_SOURCED" -eq "0" ]; then SCRIPT=$(readlink -f "$0"); else SCRIPT=$(readlink -f "${BASH_SOURCE[0]}"); fi
export MeTTa=$(realpath "$SCRIPT")
export METTALOG_DIR=$(dirname "$SCRIPT")
# echo "METTALOG_DIR=$METTALOG_DIR"
cd "$METTALOG_DIR" || { echo "Failed to navigate to $METTALOG_DIR"; [[ "$IS_SOURCED" == "1" ]] && return 1 || exit 1; }
should_compile=0
never_compile=0
compatio=false
#compatio=false
CMD_TIMEOUT=0
repl_flag=auto
use_rc_file=~/.mettalogrc
debug_this_script=false
# Function to resolve path upward but stop one level higher than /usr/
function resolve_upward {
local current_dir="$1"
while [ "$current_dir" != "/" ]; do
if [ "$current_dir" == "/tmp" ]; then
echo "/tmp"
return
fi
if [ "$current_dir" == "/usr" ]; then
echo "/usr"
return
fi
if [ -d "$current_dir/$2" ]; then
echo "$current_dir/$2"
return
fi
current_dir=$(dirname "$current_dir")
done
}
# Check if the script is running inside a Docker container
if [ ! -f /.dockerenv ]; then
# Define the name of the Docker image
IMAGE_NAME="mettalog"
# Check if Docker is installed
if command -v docker &> /dev/null; then
# Check if the Docker image exists
if docker image inspect "$IMAGE_NAME" &> /dev/null; then
DEBUG "Updating the Docker image: $IMAGE_NAME"
# Create a temporary file to capture the build output
temp_file=$(mktemp)
# Build the Docker image and redirect stderr to the temporary file
if ! docker build . -t "$IMAGE_NAME" > "$temp_file" 2>&1; then
echo "Docker build failed. Output:"
# Tail the last 30 lines of the build output for debugging
tail -30 "$temp_file"
# Clean up the temporary file
rm "$temp_file"
exit 1
else
# If build succeeds, remove the temporary file
rm "$temp_file"
DEBUG "Image $IMAGE_NAME successfully updated."
fi
# Setup additional environment variables or paths
SCRIPT_DIR=$(dirname "$(readlink -f "$0")")
# Example: UPWARD=$(resolve_upward "$(pwd)")
# Run the Docker container with the necessary volumes mounted
exec docker run -it \
-v "${SCRIPT_DIR}:/home/user/vspace-metta" \
-v "$(pwd):$(pwd)" \
-w "$(pwd)" \
"$IMAGE_NAME" \
/home/user/vspace-metta/mettalog "$@"
else
DEBUG "Image $IMAGE_NAME is not installed. Continuing with script..."
fi
else
DEBUG "Docker is not installed. Continuing with script..."
fi
fi
quoted_args=() # Initialize an empty array to store the results
for arg in "$@"; do
# Check if the argument contains spaces, exclamation marks, backslashes, or quote characters
if [[ $arg =~ [[:space:]] || $arg == *'!'* || $arg == *'\\'* || $arg == *\"* || $arg == *\'* ]]; then
# The argument needs to be quoted
quoted_arg=$(quote_arg "$arg")
quoted_args+=("$quoted_arg")
else
# The argument does not need quoting
quoted_args+=("$arg")
fi
done
if [ "$#" -gt 0 ]; then
: #echo "ARGS: ${quoted_args[*]}"
fi
# Initialize the variable to indicate whether to use the test script
use_test_script=0
# Iterate over all command-line arguments
for arg in "$@"; do
if [[ "$arg" == "--compatio" ]]; then
debug_this_script=false
compatio=true
fi
if [[ "$arg" == "--debug" ]]; then
debug_this_script=true
compatio=false
fi
# Check if the argument is a directory
if [ -d "$arg" ]; then
use_test_script=1
else
# Check for specific flags
case "$arg" in
--fres*|--fail*|--contin*|--clean)
use_test_script=1
;;
esac
fi
done
# Execute the test script if the condition is met
if [[ "$use_test_script" -eq 1 ]]; then
exec ./scripts/test_in_metta.sh -y --report=n $(quote_args_if_needed $@)
fi
for arg in "$@"; do
if [[ "$arg" == "--debugable" ]]; then
scripts/send_keys_debug.sh $(quote_args_if_needed $@)
fi
done
#export TEE_FILE=${TEE_FILE:-"$METTALOG_DIR/TEE.ansi"}
set -e
function load_rc_file {
local file="$1" # Use the argument as the file
local METTALOG_OPTIONS_LOCAL=()
local multiline_accumulator=""
local verbose="${VERBOSE:-0}" # Use the VERBOSE environment variable or default to '0' (not verbose)
if [[ -f "$file" ]]; then
while IFS= read -r line || [[ -n "$line" ]]; do
# Trim leading and trailing whitespace
line="${line#"${line%%[![:space:]]*}"}"
line="${line%"${line##*[![:space:]]}"}"
[[ -z "$line" ]] && continue # Skip empty lines
# Check for line continuation (trailing '\')
if [[ "$line" =~ \\$ ]]; then
multiline_accumulator+="${line%\\} "
continue
else
line="$multiline_accumulator$line"
multiline_accumulator=""
fi
[[ $line =~ ^# ]] && continue # Skip lines that start with a comment
METTALOG_OPTIONS_LOCAL+=("$line")
# Verbose logging
[[ "$verbose" == "1" ]] && DEBUG "Loaded option: $line"
done < "$file"
fi
local do_args="${METTALOG_OPTIONS_LOCAL[@]}"
[[ -z "$do_args" ]] && return
DEBUG "handle_args ${do_args}"
handle_args "${do_args}"
}
add_to_list() {
local item="$1"
local -n list_ref="$2"
if [[ ! " ${list_ref[*]} " =~ " $item " ]]; then
list_ref+=("$item")
fi
}
function print_help {
echo " Usage: ${MeTTa} [options] <metta-files|directories> ... [-- arg ...passed to your program...]"
echo " ${MeTTa} --help Display this message"
echo " ${MeTTa} --version Display version information"
cat << EOF
-x state Start from state (must be first)
-g goal Run goal (may be repeated)
-t toplevel Toplevel goal
-f file User initialisation file
-F file Site initialisation file
-l file Script source file
-s file Script source file
-p alias=path Define file search path 'alias'
Compilation:
${MeTTa} [options] [-o executable] -c metta-file1 -c metta-file2 ... to compile into executable ...
-O Optimised compilation
--debug[=bool] Do (not) generate debug info
--traditional Disable extensions of version (SWI-Prolog version 7)
--abi-version Display ABI version key (and exit)
--arch Display architecture (and exit)
--dump-runtime-variables[=format]
Dump link info in sh(1) format (and exit)
Running:
--rc File read command line arguments from a file
--repl Start the REPL (Read-Eval-Print Loop) after processing metta files.
If no metta files are provided, this is the default behavior.
--home[=DIR] Print home or use DIR as SWI-Prolog home
--stack-limit=size[BKMG] Specify maximum size of stacks
--table-space=size[BKMG] Specify maximum size of SLG tables
--shared-table-space=size[BKMG] Maximum size of *shared* SLG tables
--pce[=bool] Make the xpce gui available
--packs[=bool] Do (not) attach add-ons
--pldoc[=port] Start PlDoc server [at port]
--python[=bool] Enable or disable Python support (default: $python_flag)
--tty[=bool] (Dis)allow tty control
--quiet[=bool] (-q) Do (not) suppress informational messages
Testing:
--test Use the test options:
--continue Continue running tests (Generating any missing html files)
--failures Rerun unsuccessfull tests only
--regressions Rerun only tests in which we previously scored 100%
--timeout=seconds Kill the script after so many seconds.
--html[=bool] Save an HTML file containing terminal output in the same
directory as the input file or directory.
Defaults to true if exactly one metta file or directory argument was provided
--fresh Clean up by deleting any .answers files under directory
--clean Clean up by deleting all .html files under directory
Debugging:
--exec=skip Skip over !exec dirrectives
--eval=debug Recursively trace Evaluation
--case=debug Show extra debug info about case statements
--signals[=bool] Do (not) modify signal handling
--threads[=bool] Do (not) allow for threads
--debug-on-interrupt[=bool] Trap the debugger on interrupt
--prolog Drop to the host system debugger
--on-error=style One of print, halt or status
--on-warning=style One of print, halt or status
Boolean options may be written as --name=bool, --name, --no-name or --noname.
Both '-' or '_' are accepted as word-separator for long options.
Configuration File:
This script reads options from the ~/.mettalogrc file, one option per line.
Options specified in ~/.mettalogrc are processed before command-line arguments.
WAS: ${MeTTa} ${SWI_OPTIONS[*]} -l $METTALOG_DIR/metta_vspace/$PYSWIP_VERSION/metta_interp.pl -- --python=$python_flag ${PRE_METTALOG_OPTIONS[*]} ${METTALOG_OPTIONS[*]} \\
$METTA_CMD
EOF
}
# Initialize variables
SWI_OPTIONS=()
METTALOG_OPTIONS=()
if [[ "$compatio" == "true" && ! ( $* == *--compatio* ) ]]; then
METTALOG_OPTIONS=("--compatio")
fi
PRE_METTALOG_OPTIONS=()
SWI_FLAG_WITH_ARG=false
python_flag=enable
LIST_OF_FILE_ARGS=()
PYSWIP_VERSION="pyswip"
wants_print_help=0
DefaultSav="Sav.$(hostname).MeTTaLog"
function handle_args {
SWI_FLAG_WITH_ARG=false
METTA_FLAG_WITH_ARG=false
SKIP_TO_METTALOG_OPTIONS=false
NEXT_ARG_IS_RC_FILE=false
PrevDir="${RPWD:-$(pwd)}" # Default to current directory if PrevDir is not set
for arg in "$@"; do
arg=$(remove_quotes "$arg") # Remove the quotes
# Check if the previous argument was --rc
if [[ "$NEXT_ARG_IS_RC_FILE" == true ]]; then
rc_file_path="$PrevDir/$arg" # Resolve file path relative to PrevDir
rc_file_path="$(realpath "$rc_file_path")" # Resolve to absolute path
load_rc_file "$rc_file_path"
NEXT_ARG_IS_RC_FILE=false
continue
fi
if [[ $SKIP_TO_METTALOG_OPTIONS == true ]]; then
METTALOG_OPTIONS+=("$arg")
continue
fi
if [[ "$arg" == "--" ]]; then
METTALOG_OPTIONS+=("$arg")
SKIP_TO_METTALOG_OPTIONS=true
continue
fi
# Add support for --rc followed by a file
if [[ "$arg" == "--rc" ]]; then
NEXT_ARG_IS_RC_FILE=true
continue
fi
# track file paths but keep going
if [[ -f "$arg" || -d "$arg" ]]; then
arg_realpath="$(realpath "$arg")"
if [[ -f "$arg_realpath" || -d "$arg_realpath" ]]; then
add_to_list "$arg_realpath" LIST_OF_FILE_ARGS
fi
fi
if [[ "$arg" =~ ^--timeout=([0-9]+)$ ]]; then
export TIMEOUT="${BASH_REMATCH[1]}"
#DEBUG "$0 TIMEOUT=$TIMEOUT"
CMD_TIMEOUT=$TIMEOUT
METTALOG_OPTIONS=("--timeout=$TIMEOUT" "${METTALOG_OPTIONS[@]}")
continue
elif [[ "$arg" =~ ^--python=(enable|false)$ ]]; then
python_flag="${BASH_REMATCH[1]}"
elif [[ "$arg" == "--python" ]]; then
python_flag=enable
elif [[ "$arg" == "--no-python" ]]; then
python_flag=false
elif [[ "$arg" == "--repl" ]]; then
add_to_list "$arg" METTALOG_OPTIONS
repl_flag=true
elif [[ "$arg" == "--repl=true" ]]; then
repl_flag=true
elif [[ "$arg" == "--repl=false" ]]; then
repl_flag=false
elif [[ "$arg" == "--no-repl" ]]; then
repl_flag=false
elif [[ "$arg" == "--html" ]]; then
add_to_list "$arg" METTALOG_OPTIONS
html_flag=enable
elif [[ "$arg" == "--no-html" ]]; then
html_flag=false
elif [[ "$arg" == "--prolog" ]]; then
add_to_list "$arg" METTALOG_OPTIONS
repl_flag=false
fi
[[ "$arg" == "--help" || "$arg" == "-h" ]] && { wants_print_help=1; EXIT_SCRIPT=0; }
[[ "$arg" =~ ^--dump-runtime-variables.*$ || "$arg" == "--abi-version" || "$arg" == "--version" || "$arg" == "--arch" ]] && { swipl $@; EXIT_SCRIPT=0; }
[[ "$SWI_FLAG_WITH_ARG" == true ]] && { SWI_OPTIONS+=("$arg"); SWI_FLAG_WITH_ARG=false; continue; }
[[ "$METTA_FLAG_WITH_ARG" == true ]] && { METTALOG_OPTIONS+=("\"$arg\""); METTA_FLAG_WITH_ARG=false; continue; }
# These options require an argument (like a filename)
case $arg in
--v*)
PYSWIP_VERSION="pyswip${arg#*v}"
rm -f "${DefaultSav}"
never_compile=1
continue
;;
-x|-g|-t|-f|-F|-l|-s|-p|--on-error|--on-warning|--home|--stack-limit|--table-space|--shared-table-space|--pldoc)
SWI_OPTIONS+=("$arg")
SWI_FLAG_WITH_ARG=true
continue
;;
-G|-L|-F)
METTALOG_OPTIONS+=("$arg")
METTA_FLAG_WITH_ARG=true
continue
;;
# These options don't require an argument
-O|--traditional|--tty*|--packs*|--signals*|--threads*|--debug*|--debug-on-interrupt*|--quiet*|--pce*)
SWI_OPTIONS+=("$arg")
continue
;;
---*)
DASH2="-${arg#*---}"
METTALOG_OPTIONS=("$DASH2" "${METTALOG_OPTIONS[@]}")
continue
;;
*)
add_to_list "$arg" METTALOG_OPTIONS
if [[ -f "$arg" || -d "$arg" ]]; then
arg_realpath="$(realpath "$arg")"
if [[ -f "$arg_realpath" || -d "$arg_realpath" ]]; then
add_to_list "$arg_realpath" LIST_OF_FILE_ARGS
fi
fi
;;
esac
done
}
# First process arguments from ~/.mettalogrc
# Then process actual command-line arguments
#handle_args "$@"
for arg in "$@"; do
arg=$(remove_quotes "$arg") # Remove the quotes
if [[ -f "$arg" || -d "$arg" ]]; then
arg_realpath="$(realpath "$arg")"
if [[ -f "$arg_realpath" || -d "$arg_realpath" ]]; then
add_to_list "$arg_realpath" LIST_OF_FILE_ARGS
fi
elif [[ "$arg" =~ ^--rc=(.*) ]]; then
use_rc_file=""
continue
fi
done
# Then process actual command-line arguments
#DEBUG "LIST_OF_FILE_ARGS[0]=${LIST_OF_FILE_ARGS[0]}"
DIRNAME="${LIST_OF_FILE_ARGS[0]}"
if [[ -f "$DIRNAME" ]]; then
HTML_OUT="$DIRNAME".html
DIRNAME=$(dirname "${DIRNAME}")
elif [[ -d "$DIRNAME" ]]; then
HTML_OUT="${DIRNAME}/Result.html"
else
DIRNAME="${PWD}"
HTML_OUT="${DIRNAME}/Result.html"
fi
DIR_RC="$DIRNAME/.mettalogrc"
#DEBUG "DIR_RC=$DIR_RC"
if [[ -z "${use_rc_file}" ]]; then
:
elif [[ -f "$DIR_RC" ]]; then
use_rc_file="${DIR_RC}"
else
: # DEBUG "No RC file (.mettalogrc) for directory: $DIRNAME"
fi
handle_args "$@"
load_rc_file $use_rc_file
# Decide on enabling the REPL
if [[ "$repl_flag" != "false" ]]; then
[[ ${#LIST_OF_FILE_ARGS[@]} -eq 0 ]] && repl_flag=true && add_to_list "--repl" METTALOG_OPTIONS || true
fi
if [[ "$repl_flag" == "true" ]]; then
CMD_TIMEOUT=0
fi
DEBUG "SWI_OPTIONS: ${SWI_OPTIONS[@]}"
DEBUG "PRE_METTALOG_OPTIONS: ${PRE_METTALOG_OPTIONS[@]}"
DEBUG "LIST_OF_FILE_ARGS: ${LIST_OF_FILE_ARGS[@]}"
DEBUG "METTALOG_OPTIONS: ${METTALOG_OPTIONS[@]}"
# Store the initial PYTHONPATH for later comparison
initial_pythonpath="$PYTHONPATH"
# Add DIRNAME to PYTHONPATH if it's a valid path and not already present
if [[ -d "$DIRNAME" && ":$PYTHONPATH:" != *":$DIRNAME:"* ]]; then
export PYTHONPATH="${PYTHONPATH:+${PYTHONPATH}:}$DIRNAME"
fi
# Add metta_vspace to PYTHONPATH if not already present
[[ ":$PYTHONPATH:" != *":$METTALOG_DIR/metta_vspace:"* ]] && export PYTHONPATH="${PYTHONPATH:+${PYTHONPATH}:}$METTALOG_DIR/metta_vspace"
# If PYTHONPATH has changed, echo the new value
if [[ "$PYTHONPATH" != "$initial_pythonpath" ]]; then
: #DEBUG ";; Updated PYTHONPATH: $PYTHONPATH"
fi
export RUST_BACKTRACE=full
# Directory containing the .pl files
pl_directory="metta_vspace/$PYSWIP_VERSION"
# Initialize a flag to check if any file is newer or if reference file is missing
if [[ $never_compile -eq 0 ]]; then
# Reference file
reference_file=$(find . -maxdepth 1 -type f -name "${DefaultSav}*" -not -name "*.*" -printf "%T@ %p\n" | sort -k1,1nr | head -n 1 | cut -f2- -d" ")
if [[ -z "$reference_file" ]]; then
reference_file="$METTALOG_DIR/${DefaultSav}"
fi
# Check if ${DefaultSav} exists
if [[ ! -e "$reference_file" ]]; then
DEBUG "Reference file $reference_file does not exist. Compiler will be called."
should_compile=1
else
# Iterate over each .pl file to check if it's newer
for pl_file in "$pl_directory"/*_*.pl; do
if [[ ! -e "$pl_file" ]]; then
DEBUG "No matching .pl files found in $pl_directory."
#exit 1
fi
# Check if this .pl file is newer than the reference file
if [[ "$pl_file" -nt "$reference_file" ]]; then
DEBUG "$pl_file is newer than $reference_file."
should_compile=1
break # No need to check further, exit loop
fi
done
fi
fi
# If any newer file found or reference file missing, call the compiler
if [[ $should_compile -eq 1 ]]; then
#if [[ -f "$reference_file" ]]; then
# DEBUG "Calling compiler from $reference_file..."
# swipl -x $reference_file -g qsave_program -g halt
#else
rm -f $reference_file
if [[ "$never_compile" -eq 0 ]]; then
:
#DEBUG "Compiling $reference_file"
#swipl -l metta_vspace/$PYSWIP_VERSION/metta_interp.pl -g qcompile_mettalog -- --exeout=$reference_file
fi
fi
reference_file=$(find . -maxdepth 1 -type f -name "${DefaultSav}*" -not -name "*.*" -printf "%T@ %p\n" | sort -k1,1nr | head -n 1 | cut -f2- -d" ")
if [[ -z "$reference_file" ]]; then
reference_file="$METTALOG_DIR/${DefaultSav}"
fi
if [[ -f "$reference_file" ]]; then
: # rm -f $reference_file
fi
if [[ -f "$reference_file" ]]; then
MLOG="$reference_file --"
if [[ "${#SWI_OPTIONS[@]}" -gt 0 ]]; then
MLOG="swipl -x $reference_file ${SWI_OPTIONS[*]} --"
fi
if [[ "$never_compile" -eq 1 ]]; then
MLOG="swipl ${SWI_OPTIONS[*]} -l $METTALOG_DIR/metta_vspace/$PYSWIP_VERSION/metta_interp.pl --"
fi
else
MLOG="swipl ${SWI_OPTIONS[*]} -l $METTALOG_DIR/metta_vspace/$PYSWIP_VERSION/metta_interp.pl --"
fi
METTA_CMD="$MLOG --python=$python_flag ${PRE_METTALOG_OPTIONS[*]} ${METTALOG_OPTIONS[*]}"
OS=$(uname)
TIMEOUT_CMD="timeout"
if [[ "$OS" == "Darwin" ]]; then
# macOS
if command -v gtimeout >/dev/null 2>&1; then
TIMEOUT_CMD="gtimeout"
else
DEBUG "Please install coreutils using Homebrew to get the gtimeout command."
[[ "$IS_SOURCED" == "1" ]] && return 1 || exit 1
fi
fi
# Initialize the variable to store the exit status of METTA_CMD
METTA_CMD_EXIT_STATUS=666
TEMP_EXIT_CODE_FILE="$(mktemp)"
# Set a trap to ensure stty sane is run on script exit or interruption
cleanup() {
stty sane
if [[ -f "$TEMP_EXIT_CODE_FILE" ]]; then
METTA_CMD_EXIT_STATUS=$(<"$TEMP_EXIT_CODE_FILE")
rm -f "$TEMP_EXIT_CODE_FILE"
else
METTA_CMD_EXIT_STATUS=${METTA_CMD_EXIT_STATUS:-$?}
fi
DEBUG "Exit code of METTA_CMD: $METTA_CMD_EXIT_STATUS"
[[ $IS_SOURCED -eq 1 ]] && return $METTA_CMD_EXIT_STATUS || exit $METTA_CMD_EXIT_STATUS
}
#DEBUG "CMD_TIMEOUT=$CMD_TIMEOUT"
if [[ -n "$CMD_TIMEOUT" && "$CMD_TIMEOUT" -gt 0 ]]; then
METTA_CMD="$TIMEOUT_CMD --foreground --preserve-status --signal=SIGTERM --kill-after=5s $CMD_TIMEOUT ${METTA_CMD}"
fi
function escape_quotes {
local value="$1"
echo "${value//\"/\\\"}"
}
cd "${RPWD}"
export CMD_TIMEOUT
set +e
# Conditional to check if html_flag is enabled
if [[ "$html_flag" == "enable" ]]; then
# Generate a random filename for TEE_FILE with date,time,PID
random_suffix=$(date +"%Y%m%d_%H%M")_$$
TEE_FILE="$METTALOG_DIR/TEE_$random_suffix.ansi"
export TEE_FILE
export TYPESCRIPT=1
if [[ "$OS" == "Darwin" ]]; then # macOS
METTA_CMD="/usr/bin/script -q -f -a \"$TEE_FILE\" \"${METTA_CMD//\"/\\\"}\""
else # Assume Linux
METTA_CMD="/usr/bin/script -q -f --force -e -a \"$TEE_FILE\" -c \"${METTA_CMD//\"/\\\"}\""
fi
[[ "$wants_print_help" == "1" ]] && { print_help; }
DEBUG ""
DEBUG "Afterwhich ansi2html -u < $TEE_FILE > \"$HTML_OUT\""
DEBUG ""
[[ -n "${EXIT_SCRIPT+x}" ]] && { [[ "$IS_SOURCED" == "1" ]] && return "$EXIT_SCRIPT" || exit "$EXIT_SCRIPT"; }
( touch "$TEE_FILE"
chmod 777 "$TEE_FILE"
cat /dev/null > "$TEE_FILE"
DEBUG "METTA_CMD: $METTA_CMD"
eval "$METTA_CMD"
echo $? > "$TEMP_EXIT_CODE_FILE"
ansi2html -u < "$TEE_FILE" >"$HTML_OUT" ) || true
rm -f "$TEE_FILE"
cleanup
else
[[ "$wants_print_help" == "1" ]] && { print_help; [[ "$IS_SOURCED" == "1" ]] && return "$EXIT_SCRIPT" || exit "$EXIT_SCRIPT"; }
[[ -n "${EXIT_SCRIPT+x}" ]] && { [[ "$IS_SOURCED" == "1" ]] && return "$EXIT_SCRIPT" || exit "$EXIT_SCRIPT"; }
DEBUG "METTA_CMD: $METTA_CMD"
(
eval "$METTA_CMD"
echo $? > "$TEMP_EXIT_CODE_FILE" )
#rm -f "$TEE_FILE"
cleanup
fi