forked from envmodules/modules
-
Notifications
You must be signed in to change notification settings - Fork 0
/
modulecmd.tcl.in
10589 lines (9590 loc) · 363 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-2019 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 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 CSH_LIMIT 4000 ;# Workaround for commandline limits in csh
set reportfd stderr ;# File descriptor to use to report messages
# Configuration option properties (superseding environment variable, default
# value, is configuration lockable to default value, valid value list?,
# internal value representation?, proc to call to initialize option value
array set g_config_defs [list\
contact {MODULECONTACT root@localhost 0}\
auto_handling {MODULES_AUTO_HANDLING @autohandling@ 0 {0 1}}\
avail_indepth {MODULES_AVAIL_INDEPTH @availindepth@ 0 {0 1}}\
avail_report_dir_sym {{} 1 0}\
avail_report_mfile_sym {{} 1 0}\
collection_pin_version {MODULES_COLLECTION_PIN_VERSION 0 0 {0 1}}\
collection_target {MODULES_COLLECTION_TARGET <undef> 0}\
color {MODULES_COLOR @color@ 0 {never auto always} {0 1 2} initConfColor}\
colors {MODULES_COLORS {} 0 {} {} initConfColors}\
extra_siteconfig {MODULES_SITECONFIG <undef> 1 {}}\
home {MODULESHOME @moduleshome@ 0}\
icase {MODULES_ICASE @icase@ 0 {never search always}}\
ignored_dirs {{} {CVS RCS SCCS .svn .git .SYNC .sos} 0}\
locked_configs {{} {@lockedconfigs@} 0}\
pager {MODULES_PAGER {@pagercmd@} 0}\
rcfile {MODULERCFILE <undef> 0}\
run_quarantine {MODULES_RUN_QUARANTINE <undef> 0}\
silent_shell_debug {MODULES_SILENT_SHELL_DEBUG <undef> 0 {0 1}}\
siteconfig {{} @etcdir@/siteconfig.tcl 0}\
tcl_ext_lib {{} @libdir@/libtclenvmodules@SHLIB_SUFFIX@ 0}\
term_background {MODULES_TERM_BACKGROUND @termbg@ 0 {dark light}}\
unload_match_order {MODULES_UNLOAD_MATCH_ORDER @unloadmatchorder@ 0\
{returnlast returnfirst}}\
implicit_default {MODULES_IMPLICIT_DEFAULT @implicitdefault@ 1 {0 1}}\
extended_default {MODULES_EXTENDED_DEFAULT @extendeddefault@ 0 {0 1}}\
advanced_version_spec {MODULES_ADVANCED_VERSION_SPEC @advversspec@ 0 {0\
1}}\
search_match {MODULES_SEARCH_MATCH @searchmatch@ 0 {starts_with contains}}\
set_shell_startup {MODULES_SET_SHELL_STARTUP @setshellstartup@ 0 {0 1}}\
verbosity {MODULES_VERBOSITY @verbosity@ 0 {silent concise normal verbose\
debug}}\
wa_277 {MODULES_WA_277 @wa277@ 0 {0 1}}\
]
proc isConfigLocked {option} {
return [expr {[lsearch -exact [getConf locked_configs] $option] != -1}]
}
# Get configuration option value
proc getConf {option {valifundef {}}} {
if {![info exists ::g_configs($option)]} {
# fetch option properties (including its default value)
lassign $::g_config_defs($option) envvar value islockable validvallist\
intvallist initproc
# ensure option is not locked before superseding its default value
if {!$islockable || ![isConfigLocked $option]} {
# call specific proc to initialize config option if any
if {$initproc ne {}} {
set value [$initproc $envvar $value $validvallist $intvallist]
} else {
# overriden value coming from environment
if {$envvar ne {} && [info exists ::env($envvar)]} {
# ignore non-valid values
if {[llength $validvallist] == 0 || [isInList $validvallist\
$::env($envvar)]} {
set value $::env($envvar)
}
}
# overriden value coming the command-line
if {[info exists ::asked_$option]} {
set value [set ::asked_$option]
}
# convert value to its internal representation
if {[llength $intvallist] > 0} {
set value [lindex $intvallist [lsearch -exact $validvallist\
$value]]
}
}
}
# return passed value if undefined and no value record
if {$value eq {<undef>}} {
set value $valifundef
} else {
setConf $option $value
}
return $value
} else {
return $::g_configs($option)
}
}
# Set configuration option value
proc setConf {option value} {
set ::g_configs($option) $value
reportDebug "$option set to '$value'"
}
# Unset configuration option value if it is set
proc unsetConf {option} {
if {[info exists ::g_configs($option)]} {
unset ::g_configs($option)
reportDebug "$option unset"
}
}
# Append each passed value to the existing config option value list
proc lappendConf {option args} {
# retrieve current value through getConf to initialize it if still undef
set value [getConf $option]
eval appendNoDupToList value $args
setConf $option $value
}
# Source site config which can be used to define global procedures or
# settings. We first look for the global siteconfig, then if an extra
# siteconfig is defined and allowed, source that file if it exists
proc sourceSiteConfig {} {
lappend siteconfiglist [getConf siteconfig]
for {set i 0} {$i < [llength $siteconfiglist]} {incr i} {
set siteconfig [lindex $siteconfiglist $i]
if {[file readable $siteconfig]} {
reportDebug "Source site configuration ($siteconfig)"
if {[catch {uplevel 1 source $siteconfig} errMsg]} {
reportErrorAndExit "Site configuration source failed\n$errMsg"
}
if {$siteconfig eq [getConf siteconfig]} {
set ::g_siteconfig_loaded 1
} else {
set ::g_extra_siteconfig_loaded 1
}
}
# check on extra_siteconfig after initial siteconfig loaded in case
# it inhibits this extra load
if {$siteconfig eq [getConf siteconfig] && [getConf\
extra_siteconfig] ne {}} {
lappend siteconfiglist [getConf extra_siteconfig]
}
}
}
# 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]} {
set ::g_def_separator [expr {[isWin] ? {;} : {:}}]
}
return $::g_def_separator
}
# Sub level separator to serialize a second level of info in env var
set ::g_sub1_separator &
# Sub sub level separator to serialize a third level of info in env var
set ::g_sub2_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
set ::g_tty_columns [expr {![info exists cols] || $cols eq {0} ? 80 :\
$cols}]
}
return $::g_tty_columns
}
# Get force mode
proc getForce {} {
if {![info exists ::g_force]} {
set force 0 ;# By-pass dependency consistency
# overriden value coming the command-line
if {[info exists ::asked_force]} {
set force $::asked_force
}
set ::g_force $force
reportDebug "force set to '$force'"
}
return $::g_force
}
# Initialize Select Graphic Rendition table
proc initConfColors {envvar value validvallist intvallist} {
# overriden value coming from environment
if {[info exists ::env($envvar)]} {
set colors_list $::env($envvar)
if {[catch {
# test overriden value could be set to a dummy array variable
array set test_colors [split $colors_list {:=}]
} errMsg ]} {
# report issue as a debug message rather warning to avoid
# disturbing user with a warning message in the middle of a
# useful output as this table will be initialized at first use
reportDebug "Ignore invalid value set in $envvar ($colors_list)"
unset colors_list
}
}
# if no valid override set use default color theme for terminal
# background color kind (light or dark)
if {![info exists colors_list]} {
if {[getConf term_background] eq {light}} {
set colors_list {@lightbgcolors@}
} else {
set colors_list {@darkbgcolors@}
}
if {[catch {
array set test_colors [split $colors_list {:=}]
} errMsg ]} {
reportDebug "Ignore invalid default [getConf term_background]\
background colors ($colors_list)"
# define an empty list if no valid value set
set colors_list {}
}
}
# check each color defined and unset invalid codes
set value {}
foreach {elt col} [split $colors_list {:=}] {
if {![regexp {^[\d;]+$} $col]} {
reportDebug "Ignore invalid color code for '$elt' ($col)"
} else {
lappend value $elt=$col
}
}
set value [join $value :]
# set SGR table as an array to easily access rendition for each key
array unset ::g_colors
array set ::g_colors [split $value {:=}]
return $value
}
# Initialize color configuration value
proc initConfColor {envvar value validvallist intvallist} {
# overriden value coming from environment via standard variable
if {[info exists ::env(CLICOLOR)]} {
if {$::env(CLICOLOR) eq {0}} {
set value never
} else {
set value auto
}
} elseif {[info exists ::env(CLICOLOR_FORCE)] && $::env(CLICOLOR_FORCE)\
ne {0}} {
set value always
}
# overriden value coming from environment via Modules-specific variable
if {$envvar ne {} && [info exists ::env($envvar)]} {
# ignore non-valid values
if {[llength $validvallist] == 0 || [isInList $validvallist\
$::env($envvar)]} {
set value $::env($envvar)
}
}
# overriden value coming the command-line
if {[info exists ::asked_color]} {
set value [set ::asked_color]
}
# convert value to its internal representation
if {[llength $intvallist] > 0} {
set value [lindex $intvallist [lsearch -exact $validvallist $value]]
}
# disable color mode if no terminal attached except if 'always' asked
if {$value != 0 && (![isStderrTty] || $value == 2)} {
incr value -1
}
# initialize color theme if color mode enabled
getConf colors
return $value
}
# Is currently set verbosity level is equal or higher than level passed as arg
proc isVerbosityLevel {name} {
return [expr {[lsearch -exact [lindex $::g_config_defs(verbosity) 3]\
[getConf verbosity]] >= [lsearch -exact [lindex\
$::g_config_defs(verbosity) 3] $name]}]
}
# Is match performed in a case sensitive or insensitive manner
proc isIcase {} {
# depending on current sub-command, list values that equal to a case
# insensitive match enablement
lappend enabledValList always
if {[isInList [list avail whatis search paths] [currentCommandName]]} {
lappend enabledValList search
}
return [isInList $enabledValList [getConf icase]]
}
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 {showcaller 1}} {
# display caller name as prefix
set prefix [expr {$showcaller && [info level] > 1 ? "[lindex [info level\
-1] 0]: " : {}}]
lappend ::errreport_buffer [list reportDebug $prefix$message 0]
}
# regular procedure to use once error report is initialized
proc __reportDebug {message {showcaller 1}} {
# display active interp details if not the main one
set prefix [currentDebugMsgPrefix]
# display caller name as prefix
if {$showcaller && [info level] > 1} {
append prefix "[lindex [info level -1] 0]: "
}
report [sgr db "DEBUG $prefix$message"] 0 1
}
# alternative procedure used when debug is disabled
proc __reportDebugNop {args} {}
proc reportWarning {message {recordtop 0}} {
reportError $message $recordtop WARNING wa 0
}
proc reportError {message {recordtop 0} {severity ERROR} {sgrkey er}\
{raisecnt 1}} {
lappend ::errreport_buffer [list reportError $message $recordtop $severity\
$sgrkey $raisecnt]
}
proc __reportError {message {recordtop 0} {severity ERROR} {sgrkey er}\
{raisecnt 1}} {
# if report disabled, also disable error raise to get a coherent
# behavior (if no message printed, no error code change)
if {!$::g_inhibit_errreport} {
if {$raisecnt} {
raiseErrorCount
}
set message "[sgr $sgrkey $severity]: $message"
# record message to report it later on if a record id is found
if {[currentMsgRecordId] ne {}} {
recordMessage $message $recordtop
# skip message report if silent
} elseif {[isVerbosityLevel concise]} {
report $message
}
}
}
# 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} {
# change line padding depending on output-kind
set pad [expr {[currentMsgRecordId] ne {} ? {} : { }}]
reportError "$message\n${pad}In '$modfile'\n${pad}Please contact\
<[getConf contact]>" 0 {Module ERROR} me
}
proc reportInfo {message {title INFO}} {
if {[isVerbosityLevel normal]} {
# use reportError for conveniance but there is no error here
reportError $message 0 $title in 0
}
}
# is currently active message record id at top level
proc isMsgRecordIdTop {} {
return [expr {[llength $::g_msgRecordIdStack] eq 1}]
}
# record messages on the eventual additional module evaluations that have
# occurred during the current evaluation
proc reportModuleEval {} {
set evalid [currentEvalId]
array set contexttitle {conun {Unloading conflict} reqlo {Loading\
requirement} depre {Reloading dependent} depun {Unloading dependent}\
urequn {Unloading useless requirement}}
if {[info exists ::g_moduleEval($evalid)]} {
foreach contextevallist $::g_moduleEval($evalid) {
set modlist [lassign $contextevallist context]
# skip context with no description title
if {[info exists contexttitle($context)]} {
reportInfo [join $modlist] $contexttitle($context)
}
}
# purge list in case same evaluation is re-done afterward
unset ::g_moduleEval($evalid)
}
}
# render messages related to current record id under an header block
proc reportMsgRecord {header} {
set recid [currentMsgRecordId]
if {[info exists ::g_msgRecord($recid)]} {
# skip message report if silent
if {[isVerbosityLevel concise]} {
set tty_cols [getTtyColumns]
set padding { }
set dispmsg $header
foreach msg $::g_msgRecord($recid) {
# split lines if too large for terminal
set first 1
set max_idx [expr {$tty_cols - [string length $padding]}]
set linelist [list]
foreach line [split $msg \n] {
set lineadd {}
while {$lineadd ne $line} {
set line_max_idx $max_idx
# sgr tags consume no length
set eidx 0
while {[set sidx [string first "\033\[" $line $eidx]] !=\
-1} {
set eidx [string first m $line $sidx]
incr line_max_idx [expr {1 + $eidx - $sidx}]
}
# no split if no whitespace found to slice
if {[string length $line] > $line_max_idx && [set cut_idx\
[string last { } $line $line_max_idx]] != -1} {
set lineadd [string range $line 0 [expr {$cut_idx-1}]]
set line [string range $line [expr {$cut_idx+1}] end]
} else {
set lineadd $line
}
lappend linelist $lineadd
if {$first} {
set first 0
incr max_idx -[string length $padding]
}
}
}
# display each line
set first 1
foreach line $linelist {
append dispmsg \n
if {$first} {
set first 0
} else {
append dispmsg $padding
}
append dispmsg $padding$line
}
}
reportSeparateNextContent
report $dispmsg
reportSeparateNextContent
}
# purge message list in case same evaluation is re-done afterward
unset ::g_msgRecord($recid)
# report header if no other specific msg to output in verbose mode or in
# normal verbosity mode if currently processing a cmd which triggers
# multiple module evaluations that cannot be guessed by the user
} elseif {[isVerbosityLevel verbose] || ([isVerbosityLevel normal] && (\
[ongoingCommandName restore] || [ongoingCommandName source]))} {
report $header
}
}
# separate next content produced if any
proc reportSeparateNextContent {} {
lappend ::errreport_buffer [list reportSeparateNextContent]
}
# regular procedure to use once error report is initialized
proc __reportSeparateNextContent {} {
# hold or apply
if {[isReportHeld]} {
lappend ::g_holdReport([currentReportHoldId]) [list\
reportSeparateNextContent]
} else {
set ::g_report_sep_next 1
}
}
# save message for block rendering
proc recordMessage {message {recordtop 0}} {
lappend ::g_msgRecord([expr {$recordtop ? [topMsgRecordId] :\
[currentMsgRecordId]}]) $message
}
# Select Graphic Rendition of a string with passed sgr key (if color enabled)
proc sgr {sgrkey str} {
if {[getConf color] && [info exists ::g_colors($sgrkey)]} {
set sgrset $::g_colors($sgrkey)
# if render bold or faint just reset that attribute, not all
if {$sgrset == 1 || $sgrset == 2} {
set sgrreset 22
} else {
set sgrreset 0
}
set str "\033\[${sgrset}m$str\033\[${sgrreset}m"
}
return $str
}
# save message if report is not yet initialized
proc report {message {nonewline 0} {immed 0}} {
lappend ::errreport_buffer [list report $message $nonewline $immed]
}
# regular procedure to use once error report is initialized
proc __report {message {nonewline 0} {immed 0}} {
# hold or print output
if {!$immed && [isReportHeld]} {
lappend ::g_holdReport([currentReportHoldId]) [list report $message\
$nonewline]
} else {
if {![info exists ::g_already_report]} {
set ::g_already_report 1
# start pager at first call and only if enabled
if {$::start_pager} {
startPager
}
# produce blank line prior message if asked to
} elseif {[info exists ::g_report_sep_next]} {
unset ::g_report_sep_next
report {}
}
# protect from issue with fd, just ignore it
catch {
if {$nonewline} {
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} {
set extratab [expr {[string length $cmd] < 8 ? "\t" : {}}]
# only brace empty arguments or those containing whitespace
set cmdargs {}
foreach cmdarg $args {
if {$cmdargs ne {}} {
append cmdargs { }
}
if {$cmdarg eq {} || [string first { } $cmdarg] > -1} {
append cmdargs "{$cmdarg}"
} else {
append cmdargs $cmdarg
}
}
report [sgr cm $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 {![isVerbosityLevel 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 {} {
# ensure init is done only once
if {![info exists ::g_init_error_report]} {
set ::g_init_error_report 1
# determine message paging configuration and enablement
initPager
# ask for color init now as debug mode has already fire lines to render
# and we want them to be reported first (not the color init lines)
if {[isVerbosityLevel debug]} {
getConf color
}
# replace report procedures used to bufferize messages until error
# report being initialized by regular report procedures
rename ::reportDebug {}
if {[isVerbosityLevel debug]} {
rename ::__reportDebug ::reportDebug
} else {
# set a disabled version if debug is disabled
rename ::__reportDebugNop ::reportDebug
}
rename ::reportError {}
rename ::__reportError ::reportError
rename ::reportErrorAndExit {}
rename ::__reportErrorAndExit ::reportErrorAndExit
rename ::reportSeparateNextContent {}
rename ::__reportSeparateNextContent ::reportSeparateNextContent
rename ::report {}
rename ::__report ::report
# now error report is init output every message saved in buffer
foreach errreport $::errreport_buffer {
eval $errreport
}
}
}
# drop or report held messages
proc releaseHeldReport {args} {
foreach {holdid action} $args {
if {[info exists ::g_holdReport($holdid)]} {
if {$action eq {report}} {
foreach repcall $::g_holdReport($holdid) {
eval $repcall
}
}
unset ::g_holdReport($holdid)
}
}
}
# 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 {} {
set pager [getConf pager]
# empty or 'cat' pager command means no-pager
set no_cmds [list {} cat]
# default pager enablement depends on pager command value
set ::use_pager [notInList $no_cmds [file tail [lindex $pager 0]]]
set init_use_pager [notInList $no_cmds [file tail [lindex\
$::g_config_defs(pager) 1]]]
# paging may have been enabled or disabled from the command-line
if {[info exists ::asked_use_pager]} {
# asked enablement could only nullify a previous asked disablement
# as it requires a valid pager command configuration, which by default
# enables pagination
if {!$::asked_use_pager && $::use_pager} {
set ::use_pager 0
}
set asked $::asked_use_pager
} else {
set asked -
}
# some module command may also turn off pager
if {$::command eq {clear}} {
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 "start pager (asked_use_pager=$asked, cmd='$pager')"
set ::start_pager 1
} else {
reportDebug "no pager start (is_tty=$is_tty, mod_cmd='$::command',\
use_pager=$::use_pager, asked_use_pager=$asked, cmd='$pager')"
set ::start_pager 0
}
}
# start pager pipe process with defined configuration
proc startPager {} {
if {[catch {
set ::reportfd [open "|[getConf pager] >@stderr 2>@stderr" w]
fconfigure $::reportfd -buffering line -blocking 1 -buffersize 65536
} errMsg]} {
reportWarning $errMsg
}
}
# helper procedures to format various messages
proc getHintUnFirstMsg {modlist} {
return "HINT: Might try \"module unload [join $modlist]\" first."
}
proc getHintLoFirstMsg {modlist} {
if {[llength $modlist] > 1} {
set oneof {at least one of }
set mod modules
} else {
set oneof {}
set mod module
}
return "HINT: ${oneof}the following $mod must be loaded first: $modlist"
}
proc getErrConflictMsg {mod conlist} {
return "$mod cannot be loaded due to a conflict.\n[getHintUnFirstMsg\
$conlist]"
}
proc getErrPrereqMsg {mod prelist {load 1}} {
lassign [if {$load} {list {} missing [getHintLoFirstMsg $prelist]}\
{list un a [getHintUnFirstMsg $prelist]}] un mis hintmsg
return "$mod cannot be ${un}loaded due to $mis prereq.\n$hintmsg"
}
proc getErrReqLoMsg {prelist} {
return "Load of requirement '[join $prelist {' or '}]' failed"
}
proc getReqNotLoadedMsg {prelist} {
return "Requirement '[join $prelist {' or '}]' is not loaded"
}
proc getDepLoadedMsg {prelist} {
set is [expr {[llength $prelist] > 1 ? {are} : {is}}]
return "Dependent '[join $prelist {' and '}]' $is loaded"
}
proc getErrConUnMsg {conlist} {
return "Unload of conflicting '[join $conlist {' and '}]' failed"
}
proc getConIsLoadedMsg {conlist {loading 0}} {
set is [expr {[llength $conlist] > 1 ? {are} : {is}}]
set loaded [expr {$loading ? {loading} : {loaded}}]
return "Conflicting '[join $conlist {' and '}]' $is $loaded"
}
########################################################################
# 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"
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
}