forked from envmodules/modules
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodulecmd.tcl.in
6469 lines (5817 loc) · 210 KB
/
modulecmd.tcl.in
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
#!@TCLSHDIR@/tclsh
#
# MODULECMD.TCL, a pure TCL implementation of the module command
# Copyright (C) 2002-2004 Mark Lakata
# Copyright (C) 2004-2017 Kent Mein
# Copyright (C) 2016-2018 Xavier Delaruelle
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
##########################################################################
#
# Some Global Variables.....
#
set g_debug 0 ;# Set to 1 to enable debugging
set error_count 0 ;# Start with 0 errors
set g_return_false 0 ;# False value is rendered if == 1
set g_autoInit 0
set g_inhibit_interp 0 ;# Modulefile interpretation disabled if == 1
set g_inhibit_errreport 0 ;# Non-critical error reporting disabled if == 1
set g_force 0 ;# Path element reference counting if == 0
set CSH_LIMIT 4000 ;# Workaround for commandline limits in csh
set flag_default_dir 1 ;# Report default directories
set flag_default_mf 1 ;# Report default modulefiles and version alias
set reportfd "stderr" ;# File descriptor to use to report messages
set g_pager "@pager@" ;# Default command to page into, empty=disable
set g_pager_opts "@pageropts@" ;# Options to pass to the pager command
set g_siteconfig "@etcdir@/siteconfig.tcl" ;# Site configuration
# Used to tell if a machine is running Windows or not
proc isWin {} {
return [expr {$::tcl_platform(platform) eq "windows"}]
}
# Get default path separator
proc getPathSeparator {} {
if {![info exists ::g_def_separator]} {
if {[isWin]} {
set ::g_def_separator ";"
} else {
set ::g_def_separator ":"
}
}
return $::g_def_separator
}
# Detect if terminal is attached to stderr message channel
proc isStderrTty {} {
if {![info exists ::g_is_stderr_tty]} {
set ::g_is_stderr_tty [expr {![catch {fconfigure stderr -mode}]}]
}
return $::g_is_stderr_tty
}
# Provide columns number for output formatting
proc getTtyColumns {} {
if {![info exists ::g_tty_columns]} {
# determine col number from tty capabilites
# tty info query depends on running OS
switch -- $::tcl_platform(os) {
{SunOS} {
catch {regexp {columns = (\d+);} [exec stty] match cols} errMsg
}
{Windows NT} {
catch {regexp {Columns:\s+(\d+)} [exec mode] match cols} errMsg
}
default {
catch {set cols [lindex [exec stty size] 1]} errMsg
}
}
# default size if tty cols cannot be found
if {![info exists cols] || $cols eq "0"} {
set ::g_tty_columns 80
} else {
set ::g_tty_columns $cols
}
}
return $::g_tty_columns
}
# Use MODULECONTACT variable to set your support email address
if {[info exists env(MODULECONTACT)]} {
set contact $env(MODULECONTACT)
} else {
# Or change this to your support email address...
set contact "root@localhost"
}
# Set some directories to ignore when looking for modules.
set ignoreDir(CVS) 1
set ignoreDir(RCS) 1
set ignoreDir(SCCS) 1
set ignoreDir(.svn) 1
set ignoreDir(.git) 1
proc raiseErrorCount {} {
incr ::error_count
}
proc renderFalse {} {
reportDebug "called."
if {[info exists ::g_false_rendered]} {
reportDebug "false already rendered"
} elseif {[info exists ::g_shellType]} {
# setup flag to render only once
set ::g_false_rendered 1
# render a false value most of the time through a variable assignement
# that will be looked at in the shell module function calling
# modulecmd.tcl to return in turns a boolean status. Except for python
# and cmake, the value assigned to variable is also returned as the
# entire rendering status
switch -- $::g_shellType {
{sh} - {csh} - {fish} {
# no need to set a variable on real shells as last statement
# result can easily be checked
puts stdout "test 0 = 1;"
}
{tcl} {
puts stdout "set _mlstatus 0;"
}
{cmd} {
puts stdout "set errorlevel=1"
}
{perl} {
puts stdout "\$_mlstatus = 0;"
}
{python} {
puts stdout "_mlstatus = False"
}
{ruby} {
puts stdout "_mlstatus = false"
}
{lisp} {
puts stdout "nil"
}
{cmake} {
puts stdout "set(_mlstatus FALSE)"
}
{r} {
puts stdout "mlstatus <- FALSE"
}
}
}
}
proc renderTrue {} {
reportDebug "called."
# render a true value most of the time through a variable assignement that
# will be looked at in the shell module function calling modulecmd.tcl to
# return in turns a boolean status. Except for python and cmake, the
# value assigned to variable is also returned as the full rendering status
switch -- $::g_shellType {
{sh} - {csh} - {fish} {
# no need to set a variable on real shells as last statement
# result can easily be checked
puts stdout "test 0;"
}
{tcl} {
puts stdout "set _mlstatus 1;"
}
{cmd} {
puts stdout "set errorlevel=0"
}
{perl} {
puts stdout "\$_mlstatus = 1;"
}
{python} {
puts stdout "_mlstatus = True"
}
{ruby} {
puts stdout "_mlstatus = true"
}
{lisp} {
puts stdout "t"
}
{cmake} {
puts stdout "set(_mlstatus TRUE)"
}
{r} {
puts stdout "mlstatus <- TRUE"
}
}
}
proc renderText {text} {
reportDebug "called ($text)."
# render a text value most of the time through a variable assignement that
# will be looked at in the shell module function calling modulecmd.tcl to
# return in turns a string value.
switch -- $::g_shellType {
{sh} - {csh} - {fish} {
foreach word $text {
# no need to set a variable on real shells, echoing text will make
# it available as result
puts stdout "echo '$word';"
}
}
{tcl} {
puts stdout "set _mlstatus \"$text\";"
}
{cmd} {
foreach word $text {
puts stdout "echo $word"
}
}
{perl} {
puts stdout "\$_mlstatus = '$text';"
}
{python} {
puts stdout "_mlstatus = '$text'"
}
{ruby} {
puts stdout "_mlstatus = '$text'"
}
{lisp} {
puts stdout "(message \"$text\")"
}
{cmake} {
puts stdout "set(_mlstatus \"$text\")"
}
{r} {
puts stdout "mlstatus <- '$text'"
}
}
}
#
# Debug, Info, Warnings and Error message handling.
#
# save message when report is not currently initialized as we do not
# know yet if debug mode is enabled or not
proc reportDebug {message {nonewline ""}} {
lappend ::errreport_buffer [list "reportDebug" $message $nonewline 0]
}
# regular procedure to use once error report is initialized
proc __reportDebug {message {nonewline ""} {showcaller 1}} {
# display caller name as prefix
if {$showcaller && [info level] > 1} {
set prefix "[lindex [info level -1] 0]: "
} else {
set prefix ""
}
report "DEBUG $prefix$message" "$nonewline"
}
# alternative procedure used when debug is disabled
proc __reportDebugNop {args} {}
proc reportWarning {message {nonewline ""}} {
if {!$::g_inhibit_errreport} {
report "WARNING: $message" "$nonewline"
}
}
proc reportError {message {nonewline ""}} {
# if report disabled, also disable error raise to get a coherent
# behavior (if no message printed, no error code change)
if {!$::g_inhibit_errreport} {
raiseErrorCount
report "ERROR: $message" "$nonewline"
}
}
# save message if report is not yet initialized
proc reportErrorAndExit {message} {
lappend ::errreport_buffer [list "reportErrorAndExit" $message]
}
# regular procedure to use once error report is initialized
proc __reportErrorAndExit {message} {
raiseErrorCount
renderFalse
error "$message"
}
proc reportInternalBug {message modfile} {
# if report disabled, also disable error raise to get a coherent
# behavior (if no message printed, no error code change)
if {!$::g_inhibit_errreport} {
raiseErrorCount
report "Module ERROR: $message\n In '$modfile'\n Please contact\
<$::contact>"
}
}
# save message if report is not yet initialized
proc report {message {nonewline ""}} {
lappend ::errreport_buffer [list "report" $message $nonewline]
}
# regular procedure to use once error report is initialized
proc __report {message {nonewline ""}} {
# start pager at first call and only if enabled
if {$::start_pager} {
set ::start_pager 0
startPager
}
# protect from issue with fd, just ignore it
catch {
if {$nonewline ne ""} {
puts -nonewline $::reportfd "$message"
} else {
puts $::reportfd "$message"
}
}
}
# report error the correct way depending of its type
proc reportIssue {issuetype issuemsg {issuefile {}}} {
switch -- $issuetype {
{invalid} {
reportInternalBug $issuemsg $issuefile
}
default {
reportError $issuemsg
}
}
}
# report defined command (used in display evaluation mode)
proc reportCmd {cmd args} {
if {[string length $cmd] < 8} {
set extratab "\t"
} else {
set extratab ""
}
# only brace empty arguments or those containing whitespace
set cmdargs ""
foreach cmdarg $args {
if {$cmdargs != ""} {
append cmdargs " "
}
if {$cmdarg eq "" || [string first " " $cmdarg] > -1} {
append cmdargs "{$cmdarg}"
} else {
append cmdargs $cmdarg
}
}
report "$cmd$extratab\t$cmdargs"
# empty string returns if command result is another command input
return {}
}
# report defined command (called as an execution trace)
proc reportCmdTrace {cmdstring args} {
eval reportCmd $cmdstring
}
proc reportVersion {} {
report "Modules Release @MODULES_RELEASE@@MODULES_BUILD@\
(@MODULES_BUILD_DATE@)"
}
# disable error reporting (non-critical report only) unless debug enabled
proc inhibitErrorReport {} {
if {!$::g_debug} {
set ::g_inhibit_errreport 1
}
}
proc reenableErrorReport {} {
set ::g_inhibit_errreport 0
}
proc isErrorReportInhibited {} {
return $::g_inhibit_errreport
}
# init error report and output buffered messages
proc initErrorReport {} {
# determine message paging configuration and enablement
initPager
# replace report procedures used to bufferize messages until error report
# being initialized by regular report procedures
rename ::reportDebug {}
if {$::g_debug} {
rename ::__reportDebug ::reportDebug
} else {
# set a disabled version if debug is disabled
rename ::__reportDebugNop ::reportDebug
}
rename ::reportErrorAndExit {}
rename ::__reportErrorAndExit ::reportErrorAndExit
rename ::report {}
rename ::__report ::report
# now error report is init output every message saved in buffer
foreach errreport $::errreport_buffer {
eval $errreport
}
}
# exit in a clean manner by closing interaction with external components
proc cleanupAndExit {code} {
# close pager if enabled
if {$::reportfd ne "stderr"} {
catch {flush $::reportfd}
catch {close $::reportfd}
}
exit $code
}
# init configuration for output paging to prepare for startup
proc initPager {} {
# default pager enablement depends of pager command value
if {$::g_pager eq "" || [file tail $::g_pager] eq "cat"} {
set use_pager 0
set init_use_pager 0
} else {
set use_pager 1
set init_use_pager 1
}
if {[info exists ::env(MODULES_PAGER)]} {
if {$::env(MODULES_PAGER) ne ""} {
# MODULES_PAGER env variable set means pager should be enabled
if {!$use_pager} {
set use_pager 1
}
# fetch pager command and option
set ::g_pager [lindex $::env(MODULES_PAGER) 0]
set ::g_pager_opts [lrange $::env(MODULES_PAGER) 1 end]
# variable defined empty means no-pager
} else {
set use_pager 0
set ::g_pager ""
set ::g_pager_opts ""
}
reportDebug "initPager: configure pager from MODULES_PAGER variable\
(use_pager=$use_pager, cmd='$::g_pager', opts='$::g_pager_opts')"
}
# paging may have been enabled or disabled from the command-line
if {[info exists ::asked_pager]} {
# enable from command-line only if it is enabled in script config
if {$::asked_pager && !$use_pager && $init_use_pager} {
set use_pager 1
} elseif {!$::asked_pager && $use_pager} {
set use_pager 0
}
set asked $::asked_pager
} else {
set asked "-"
}
# empty or 'cat' pager command means no-pager
if {$use_pager && ($::g_pager eq "" || [file tail $::g_pager] eq "cat")} {
set use_pager 0
}
# start paging if enabled and if error stream is attached to a terminal
set is_tty [isStderrTty]
if {$is_tty && $use_pager} {
reportDebug "initPager: start pager (asked_pager=$asked,\
cmd='$::g_pager', opts='$::g_pager_opts')"
set ::start_pager 1
} else {
reportDebug "initPager: no pager start (is_tty=$is_tty,\
use_pager=$use_pager, asked_pager=$asked, cmd='$::g_pager',\
opts='$::g_pager_opts')"
set ::start_pager 0
}
}
# start pager pipe process with defined configuration
proc startPager {} {
if {[catch {
set ::reportfd [open "|$::g_pager $::g_pager_opts >@stderr 2>@stderr" w]
fconfigure $::reportfd -buffering line -blocking 1 -buffersize 65536
} errMsg]} {
reportWarning $errMsg
}
}
########################################################################
# Use a slave TCL interpreter to execute modulefiles
#
# dummy proc to disable modulefile commands on some evaluation modes
proc nop {args} {}
# dummy proc for commands available on other Modules flavor but not here
proc nimp {cmd args} {
reportWarning "'$cmd' command not implemented"
}
proc get-env {var {valifunset ""}} {
# return current value if exists and not cleared
if {[info exists ::env($var)] && ![info exists ::g_clearedEnvVars($var)]} {
return $::env($var)
} else {
return $valifunset
}
}
proc set-env {var val} {
set mode [currentMode]
reportDebug "$var=$val (mode=$mode)"
set ::env($var) $val
# variable is not cleared anymore if set again
if {[info exists ::g_clearedEnvVars($var)]} {
unset ::g_clearedEnvVars($var)
}
# propagate variable setup to shell environment on load and unload mode
if {$mode eq "load" || $mode eq "unload"} {
set ::g_stateEnvVars($var) "new"
}
}
proc reset-to-unset-env {var {val {}}} {
set ::env($var) $val
# set var as cleared if val is empty
if {$val eq ""} {
set ::g_clearedEnvVars($var) 1
}
}
proc unset-env {var {internal 0} {val {}}} {
set mode [currentMode]
reportDebug "$var (internal=$internal, val=$val, mode=$mode)"
# clear value instead of unset it not to break variable later reference
# in modulefile. clear whether variable set or not to get a later usage
# consistent behavior whatever env is setup
if {!$internal} {
reset-to-unset-env $var $val
# internal variables (like ref counter var) are purely unset if they exists
} elseif {[info exists ::env($var)]} {
unset ::env($var)
set intwasset 1
}
# propagate deletion in any case if variable is public and for internal
# one only if variable was set
if {($mode eq "load" || $mode eq "unload") && (!$internal ||\
[info exists intwasset])} {
set ::g_stateEnvVars($var) "del"
}
}
# Initialize list of interp alias commands to define for given evaluation mode
proc initModfileModeAliases {mode aliasesVN aliasesPassArgVN tracesVN} {
global g_modfilePerModeAliases
upvar #0 $aliasesVN aliases
upvar #0 $aliasesPassArgVN aliasesPassArg
upvar #0 $tracesVN traces
if {![info exists g_modfilePerModeAliases]} {
set ::g_modfileBaseAliases [list getenv getenv is-loaded is-loaded\
is-saved is-saved is-used is-used is-avail is-avail uname uname\
module-info module-info exit exitModfileCmd reportCmdTrace\
reportCmdTrace reportInternalBug reportInternalBug reportWarning\
reportWarning reportError reportError raiseErrorCount\
raiseErrorCount report report isWin isWin puts putsModfileCmd\
readModuleContent readModuleContent]
# list of alias commands whose target procedure is adapted according to
# the evaluation mode
set ::g_modfileEvalModes {load unload display help test whatis}
array set g_modfilePerModeAliases {
append-path {append-path remove-path append-path append-path append-path edit-path-wh }
chdir {chdir nop reportCmd nop nop nop }
conflict {conflict nop reportCmd nop nop nop }
module {module module reportCmd nop nop nop }
module-alias {module-alias module-alias module-alias module-alias module-alias module-alias }
module-log {nimp nimp reportCmd nop nop nop }
module-trace {nimp nimp reportCmd nop nop nop }
module-user {nimp nimp reportCmd nop nop nop }
module-verbosity {nimp nimp reportCmd nop nop nop }
module-version {module-version module-version module-version module-version module-version module-version}
module-virtual {module-virtual module-virtual module-virtual module-virtual module-virtual module-virtual}
module-whatis {nop nop reportCmd nop nop module-whatis }
prepend-path {prepend-path remove-path prepend-path prepend-path prepend-path edit-path-wh }
prereq {prereq nop reportCmd nop nop nop }
remove-path {remove-path remove-path-un remove-path remove-path remove-path edit-path-wh }
set-alias {set-alias set-alias-un reportCmd nop nop nop }
setenv {setenv setenv-un setenv setenv setenv setenv-wh }
system {system system reportCmd nop nop nop }
unset-alias {unset-alias nop reportCmd nop nop nop }
unsetenv {unsetenv unsetenv-un unsetenv unsetenv unsetenv setenv-wh }
x-resource {x-resource x-resource reportCmd nop nop nop }
}
}
# alias commands where interpreter ref should be passed as argument
array set aliasesPassArg [list puts __itrp__]
# initialize list with all commands not dependent of the evaluation mode
array set aliases $::g_modfileBaseAliases
# add alias commands whose target command vary depending on the eval mode
set modeidx [lsearch -exact $::g_modfileEvalModes $mode]
foreach alias [array names g_modfilePerModeAliases] {
set aliastarget [set aliases($alias) [lindex\
$g_modfilePerModeAliases($alias) $modeidx]]
# some target procedures need command name as first arg
if {$aliastarget eq "reportCmd" || $aliastarget eq "nimp"} {
set aliasesPassArg($alias) $alias
# associate a trace command if per-mode alias command is not reportCmd
# in display mode
} elseif {$mode eq "display"} {
set traces($alias) "reportCmdTrace"
}
}
}
proc execute-modulefile {modfile modname modspec {must_have_cookie 1}} {
pushModuleFile $modfile
pushModuleName $modname
pushSpecifiedName $modspec
set mode [currentMode]
# skip modulefile if interpretation has been inhibited
if {$::g_inhibit_interp} {
reportDebug "skipping $modfile (mode=$mode)"
return 1
}
reportDebug "sourcing $modfile (mode=$mode)"
if {![info exists ::g_modfileUntrackVars]} {
# list variable that should not be tracked for saving
array set ::g_modfileUntrackVars [list ModulesCurrentModulefile 1\
must_have_cookie 1 modcontent 1 env 1]
# commands that should be renamed before aliases setup
array set ::g_modfileRenameCmds [list puts _puts]
}
# dedicate an interpreter per mode and per level of interpretation to have
# a dedicated interpreter in case of cascaded multi-mode interpretations
set itrp "__modfile_${mode}_[getEvalModuleStackDepth]"
# evaluation mode-specific configuration
set dumpCommandsVN "g_modfile${mode}Commands"
set aliasesVN "g_modfile${mode}Aliases"
set aliasesPassArgVN "g_modfile${mode}AliasesPassArg"
set tracesVN "g_modfile${mode}Traces"
if {![info exists ::$aliasesVN]} {
initModfileModeAliases $mode $aliasesVN $aliasesPassArgVN $tracesVN
}
# create modulefile interpreter at first interpretation
if {![interp exists $itrp]} {
reportDebug "creating interp $itrp"
interp create $itrp
# dump initial interpreter state to restore it before each modulefile
# interpretation. use same dump state for all modes/levels
if {![info exists ::g_modfileVars]} {
dumpInterpState $itrp g_modfileVars g_modfileArrayVars\
g_modfileUntrackVars g_modfileProcs
}
# interp has just been created
set fresh 1
} else {
set fresh 0
}
# reset interp state command before each interpretation
resetInterpState $itrp $fresh g_modfileVars g_modfileArrayVars\
g_modfileUntrackVars g_modfileProcs $aliasesVN $aliasesPassArgVN\
$tracesVN g_modfileRenameCmds $dumpCommandsVN
# reset modulefile-specific variable before each interpretation
interp eval $itrp set ::ModulesCurrentModulefile $modfile
interp eval $itrp set must_have_cookie $must_have_cookie
set errorVal [interp eval $itrp {
set modcontent [readModuleContent $::ModulesCurrentModulefile 1\
$must_have_cookie]
if {$modcontent eq ""} {
return 1
}
info script $::ModulesCurrentModulefile
# eval then call for specific proc depending mode under same catch
set sourceFailed [catch {
eval $modcontent
switch -- [module-info mode] {
{help} {
if {[info procs "ModulesHelp"] eq "ModulesHelp"} {
ModulesHelp
} else {
reportWarning "Unable to find ModulesHelp in\
$::ModulesCurrentModulefile."
}
}
{display} {
if {[info procs "ModulesDisplay"] eq "ModulesDisplay"} {
ModulesDisplay
}
}
{test} {
if {[info procs "ModulesTest"] eq "ModulesTest"} {
if {[string is true -strict [ModulesTest]]} {
report "Test result: PASS"
} else {
report "Test result: FAIL"
raiseErrorCount
}
} else {
reportWarning "Unable to find ModulesTest in\
$::ModulesCurrentModulefile."
}
}
}
} errorMsg]
if {$sourceFailed} {
# no error in case of "continue" command
# catch continue even if called outside of a loop
if {$errorMsg eq "invoked \"continue\" outside of a loop"\
|| $sourceFailed == 4} {
unset errorMsg
return 0
# catch break even if called outside of a loop
} elseif {$errorMsg eq "invoked \"break\" outside of a loop"\
|| ($errorMsg eq "" && (![info exists ::errorInfo]\
|| $::errorInfo eq ""))} {
raiseErrorCount
unset errorMsg
return 1
} elseif {$errorMsg eq "SUB_FAILED"} {
# error counter and message already handled, just return error
return 1
} elseif [regexp "^WARNING" $errorMsg] {
raiseErrorCount
report $errorMsg
return 1
} else {
reportInternalBug $errorMsg $::ModulesCurrentModulefile
return 1
}
} else {
unset errorMsg
return 0
}
}]
popSpecifiedName
popModuleName
popModuleFile
reportDebug "exiting $modfile (mode=$mode)"
return $errorVal
}
# Smaller subset than main module load... This function runs modulerc and
# .version files
proc execute-modulerc {modfile modname modspec} {
pushModuleFile $modfile
# push name to be found by module-alias and version
pushModuleName $modname
pushSpecifiedName $modspec
set ::ModulesVersion {}
if {![info exists ::g_modrcUntrackVars]} {
# list variable that should not be tracked for saving
array set ::g_modrcUntrackVars [list ModulesCurrentModulefile 1\
ModulesVersion 1 modcontent 1 env 1]
# commands that should be renamed before aliases setup
array set ::g_modrcRenameCmds [list]
# list interpreter alias commands to define
array set ::g_modrcAliases [list uname uname system system chdir\
nop module-version module-version module-alias module-alias\
module-virtual module-virtual module nop module-info module-info\
module-trace nop module-verbosity nop module-user nop module-log\
nop reportInternalBug reportInternalBug setModulesVersion\
setModulesVersion readModuleContent readModuleContent]
# alias commands where an argument should be passed
array set ::g_modrcAliasesPassArg [list]
# trace commands that should be associated to aliases
array set ::g_modrcAliasesTraces [list]
}
# dedicate an interpreter per level of interpretation to have in case of
# cascaded interpretations a specific interpreter per level
set itrp "__modrc_[getEvalModuleStackDepth]"
reportDebug "sourcing $modfile"
# create modulerc interpreter at first interpretation
if {![interp exists $itrp]} {
reportDebug "creating interp $itrp"
interp create $itrp
# dump initial interpreter state to restore it before each modulerc
# interpreation. use same dump state for all levels
if {![info exists ::g_modrcVars]} {
dumpInterpState $itrp g_modrcVars g_modrcArrayVars\
g_modrcUntrackVars g_modrcProcs
}
# interp has just been created
set fresh 1
} else {
set fresh 0
}
# reset interp state command before each interpretation
resetInterpState $itrp $fresh g_modrcVars g_modrcArrayVars\
g_modrcUntrackVars g_modrcProcs g_modrcAliases g_modrcAliasesPassArg\
g_modrcAliasesTraces g_modrcRenameCmds g_modrcCommands
interp eval $itrp set ::ModulesCurrentModulefile $modfile
interp eval $itrp {set ::ModulesVersion {}}
set errorVal [interp eval $itrp {
set modcontent [readModuleContent $::ModulesCurrentModulefile]
if {$modcontent eq ""} {
# simply skip rc file, no exit on error here
return 1
}
info script $::ModulesCurrentModulefile
if [catch {eval $modcontent} errorMsg] {
reportInternalBug $errorMsg $::ModulesCurrentModulefile
return 1
} else {
# pass ModulesVersion value to master interp
if {[info exists ::ModulesVersion]} {
setModulesVersion $::ModulesVersion
}
return 0
}
}]
# default version set via ModulesVersion variable in .version file
# override previously defined default version for modname
lassign [getModuleNameVersion] mod modname modversion
if {$modversion eq ".version" && $::ModulesVersion ne ""} {
setModuleResolution "$modname/default" $modname/$::ModulesVersion\
"default"
}
popSpecifiedName
popModuleName
popModuleFile
return $::ModulesVersion
}
# Save list of the defined procedure and the global variables with their
# associated values set in slave interpreter passed as argument. Global
# structures are used to save these information and the name of these
# structures are provided as argument.
proc dumpInterpState {itrp dumpVarsVN dumpArrayVarsVN untrackVarsVN\
dumpProcsVN} {
upvar #0 $dumpVarsVN dumpVars
upvar #0 $dumpArrayVarsVN dumpArrayVars
upvar #0 $untrackVarsVN untrackVars
upvar #0 $dumpProcsVN dumpProcs
regexp {^__[a-z]+} $itrp itrpkind
# save name and value for any other global variables
foreach var [$itrp eval {info globals}] {
if {![info exists untrackVars($var)]} {
reportDebug "saving for $itrpkind var $var"
if {[$itrp eval array exists ::$var]} {
set dumpVars($var) [$itrp eval array get ::$var]
set dumpArrayVars($var) 1
} else {
set dumpVars($var) [$itrp eval set ::$var]
}
}
}
# save name of every defined procedures
foreach var [$itrp eval {info procs}] {
set dumpProcs($var) 1
}
reportDebug "saving for $itrpkind proc list [array names dumpProcs]"
}
# Define commands to be known by slave interpreter.
proc initInterpCommands {itrp fresh aliasesVN aliasesPassArgVN tracesVN\
renameCmdsVN} {
upvar #0 $aliasesVN aliases
upvar #0 $aliasesPassArgVN aliasesPassArg
upvar #0 $tracesVN traces
upvar #0 $renameCmdsVN renameCmds
# rename some commands on freshly created interp before aliases defined
# below overwrite them
if {$fresh} {
foreach cmd [array names renameCmds] {
$itrp eval rename $cmd $renameCmds($cmd)
}
}
# set interpreter alias commands each time to guaranty them being
# defined and not overridden by modulefile or modulerc content
foreach alias [array names aliases] {
if {[info exists aliasesPassArg($alias)]} {
set aliasarg $aliasesPassArg($alias)
# pass current itrp reference on special keyword
if {$aliasarg eq "__itrp__"} {
set aliasarg $itrp
}
interp alias $itrp $alias {} $aliases($alias) $aliasarg
} else {
interp alias $itrp $alias {} $aliases($alias)
}
}
foreach alias [array names traces] {
interp eval $itrp [list trace add execution $alias leave\
$traces($alias)]
}
}
# Restore initial setup of slave interpreter passed as argument based on
# global structure previously filled with initial list of defined procedure
# and values of global variable.
proc resetInterpState {itrp fresh dumpVarsVN dumpArrayVarsVN untrackVarsVN\
dumpProcsVN aliasesVN aliasesPassArgVN tracesVN renameCmdsVN\
dumpCommandsVN} {
upvar #0 $dumpVarsVN dumpVars
upvar #0 $dumpArrayVarsVN dumpArrayVars
upvar #0 $untrackVarsVN untrackVars
upvar #0 $dumpProcsVN dumpProcs
upvar #0 $dumpCommandsVN dumpCommands
# look at list of defined procedures and delete those not part of the
# initial state list. do not check if they have been altered as no vital
# procedures lied there. note that if a Tcl command has been overridden
# by a proc, it will be removed here and command will also disappear
foreach var [$itrp eval {info procs}] {
if {![info exists dumpProcs($var)]} {
reportDebug "removing on $itrp proc $var"
$itrp eval [list rename $var {}]
}
}
# rename some commands and set aliases on interpreter
initInterpCommands $itrp $fresh $aliasesVN $aliasesPassArgVN $tracesVN\
$renameCmdsVN
# dump interpreter command list here on first time as aliases should be
# set prior to be found on this list for correct match
if {![info exists dumpCommands]} {
set dumpCommands [$itrp eval {info commands}]
reportDebug "saving for $itrp command list $dumpCommands"
# if current interpreter command list does not match initial list it
# means that at least one command has been altered so we need to recreate
# interpreter to guaranty proper functioning
} elseif {$dumpCommands ne [$itrp eval {info commands}]} {
reportDebug "missing command(s), recreating interp $itrp"
interp delete $itrp
interp create $itrp
initInterpCommands $itrp 1 $aliasesVN $aliasesPassArgVN $tracesVN\
$renameCmdsVN
}
# check every global variables currently set and correct them to restore
# initial interpreter state. work on variables at the very end to ensure
# procedures and commands are correctly defined
foreach var [$itrp eval {info globals}] {
if {![info exists untrackVars($var)]} {
if {![info exists dumpVars($var)]} {
reportDebug "removing on $itrp var $var"
$itrp eval unset ::$var
} elseif {![info exists dumpArrayVars($var)]} {
if {$dumpVars($var) ne [$itrp eval set ::$var]} {
reportDebug "restoring on $itrp var $var"
if {[llength $dumpVars($var)] > 1} {
# restore value as list
$itrp eval set ::$var [list $dumpVars($var)]
} else {