Debian Codegraph @

tcl/mfcmd.tcl

raw
1 ##########################################################################
2
3 # MFCMD.TCL, modulefile command procedures
4 # Copyright (C) 2002-2004 Mark Lakata
5 # Copyright (C) 2004-2017 Kent Mein
6 # Copyright (C) 2016-2026 Xavier Delaruelle
7 #
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 2 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20
21 ##########################################################################
22
23 # Dictionary-style string comparison
24 # Use dictionary sort of lsort proc to compare two strings in the "string
25 # compare" fashion (returning -1, 0 or 1). Tcl dictionary-style comparison
26 # enables to compare software versions (ex: "1.10" is greater than "1.8")
27 proc versioncmp {str1 str2} {
28 if {$str1 eq $str2} {
29 return 0
30 # put both strings in a list, then lsort it and get first element
31 } elseif {[lindex [lsort -dictionary [list $str1 $str2]] 0] eq $str1} {
32 return -1
33 } else {
34 return 1
35 }
36 }
37
38 proc module-info {what {more {}}} {
39 set mode [currentState mode]
40
41 switch -- $what {
42 mode {
43 if {$more ne {}} {
44 set command [currentState commandname]
45 return [expr {$mode eq $more || ($more eq {remove} && $mode eq \
46 {unload}) || ($more eq {switch} && $command eq {switch}) ||\
47 ($more eq {nonpersist} && $mode eq {refresh})}]
48 } else {
49 return $mode
50 }
51 }
52 command {
53 set command [currentState commandname]
54 if {$more eq {}} {
55 return $command
56 } else {
57 return [expr {$command eq $more}]
58 }
59 }
60 name {
61 return [currentState modulename]
62 }
63 specified {
64 return [currentState specifiedname]
65 }
66 shell {
67 if {$more ne {}} {
68 return [expr {[getState shell] eq $more}]
69 } else {
70 return [getState shell]
71 }
72 }
73 flags {
74 # C-version specific option, not relevant for Tcl-version but return
75 # a zero integer value to avoid breaking modulefiles using it
76 return 0
77 }
78 shelltype {
79 if {$more ne {}} {
80 return [expr {[getState shelltype] eq $more}]
81 } else {
82 return [getState shelltype]
83 }
84 }
85 user {
86 # C-version specific option, not relevant for Tcl-version but return
87 # an empty value or false to avoid breaking modulefiles using it
88 if {$more ne {}} {
89 return 0
90 } else {
91 return {}
92 }
93 }
94 alias {
95 set ret [resolveModuleVersionOrAlias $more [isIcase]]
96 if {$ret ne $more} {
97 return $ret
98 } else {
99 return {}
100 }
101 }
102 trace {
103 return {}
104 }
105 tracepat {
106 return {}
107 }
108 type {
109 return Tcl
110 }
111 symbols {
112 lassign [getModuleNameVersion $more 1] mod modname modversion
113 set sym_list [getVersAliasList $mod]
114 # if querying special symbol "default" but nothing found registered
115 # on it, look at symbol registered on bare module name in case there
116 # are symbols registered on it but no default symbol set yet to link
117 # to them
118 if {![llength $sym_list] && $modversion eq {default}} {
119 set sym_list [getVersAliasList $modname]
120 }
121 return [join $sym_list :]
122 }
123 tags {
124 # refresh mod name version and variant to correctly get all matching
125 # tags (in case tags apply to specific module variant)
126 set modname [currentState modulename]
127 set modnamevr [getAndParseLoadedModuleWithVariant $modname]
128 collectModuleTags $modnamevr
129
130 if {$more ne {}} {
131 return [expr {$more in [getTagList $modnamevr [currentState\
132 modulefile]]}]
133 } else {
134 return [getTagList $modnamevr [currentState modulefile]]
135 }
136 }
137 version {
138 lassign [getModuleNameVersion $more 1] mod
139 return [resolveModuleVersionOrAlias $mod [isIcase]]
140 }
141 loaded {
142 lassign [getModuleNameVersion $more 1] mod
143 return [getLoadedMatchingName $mod returnall]
144 }
145 usergroups {
146 if {[getState is_win]} {
147 knerror "module-info usergroups not supported on Windows platform"
148 } else {
149 if {$more ne {}} {
150 return [expr {$more in [getState usergroups]}]
151 } else {
152 return [getState usergroups]
153 }
154 }
155 }
156 username {
157 if {[getState is_win]} {
158 knerror "module-info username not supported on Windows platform"
159 } else {
160 if {$more ne {}} {
161 return [expr {[getState username] eq $more}]
162 } else {
163 return [getState username]
164 }
165 }
166 }
167 default {
168 knerror "module-info $what not supported"
169 return {}
170 }
171 }
172 }
173
174 proc module-whatis {args} {
175 lappend ::g_whatis [join $args]
176
177 return {}
178 }
179
180 # Specifies a default or alias version for a module that points to an
181 # existing module version Note that aliases defaults are stored by the
182 # short module name (not the full path) so aliases and defaults from one
183 # directory will apply to modules of the same name found in other
184 # directories.
185 proc module-version {args} {
186 lassign [getModuleNameVersion [lindex $args 0] 1] mod modname modversion
187
188 # go for registration only if valid modulename
189 if {$mod ne {}} {
190 foreach version [lrange $args 1 end] {
191 set aliasversion $modname/$version
192 # do not alter a previously defined alias version
193 if {![info exists ::g_moduleVersion($aliasversion)]} {
194 setModuleResolution $aliasversion $mod $version
195 } else {
196 reportWarning "Symbolic version '$aliasversion' already defined"
197 }
198 }
199 }
200
201 return {}
202 }
203
204 proc module-alias {args} {
205 lassign [getModuleNameVersion [lindex $args 0]] alias
206 lassign [getModuleNameVersion [lindex $args 1] 1] mod
207
208 reportDebug "$alias = $mod"
209
210 if {[setModuleResolution $alias $mod]} {
211 set ::g_moduleAlias($alias) $mod
212 set ::g_sourceAlias($alias) [currentState modulefile]
213 }
214
215 return {}
216 }
217
218 proc module-virtual {args} {
219 lassign [getModuleNameVersion [lindex $args 0]] mod
220 set modfile [getAbsolutePath [lindex $args 1]]
221
222 reportDebug "$mod = $modfile"
223
224 set ::g_moduleVirtual($mod) $modfile
225 set ::g_sourceVirtual($mod) [currentState modulefile]
226
227 return {}
228 }
229
230 # Parse date time argument value and translate it into epoch time
231 proc __parseDateTimeArg {opt datetime} {
232 if {[regexp {^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2})?$} $datetime match\
233 timespec]} {
234 # time specification is optional
235 if {$timespec eq {}} {
236 append datetime T00:00
237 }
238 # return corresponding epoch time
239 return [clock scan $datetime -format %Y-%m-%dT%H:%M]
240 } else {
241 knerror "Incorrect $opt value '$datetime' (valid date time format is\
242 'YYYY-MM-DD\[THH:MM\]')"
243 }
244 }
245
246 # parse application criteria arguments and determine if command applies
247 proc parseApplicationCriteriaArgs {aftbef nearsec args} {
248 set otherargs {}
249
250 # parse argument list
251 foreach arg $args {
252 if {[info exists nextargisval]} {
253 ##nagelfar vartype nextargisval varName
254 set $nextargisval $arg
255 unset nextargisval
256 } elseif {[info exists nextargisdatetime]} {
257 ##nagelfar ignore Suspicious variable name
258 set ${nextargisdatetime}raw $arg
259 # get epoch time from date time argument value
260 ##nagelfar vartype nextargisdatetime varName
261 ##nagelfar ignore Unknown variable
262 set $nextargisdatetime [parseDateTimeArg $prevarg $arg]
263 unset nextargisdatetime
264 } else {
265 switch -- $arg {
266 --after - --before {
267 # treat --after/--before as regular content if disabled
268 if {!$aftbef} {
269 lappend otherargs $arg
270 } else {
271 set nextargisdatetime [string trimleft $arg -]
272 }
273 }
274 --not-group - --not-user - --group - --user {
275 if {[getState is_win]} {
276 knerror "Option '$arg' not supported on Windows platform"
277 } else {
278 set nextargisval [string map {- {}} $arg]list
279 }
280 }
281 default {
282 lappend otherargs $arg
283 }
284 }
285 set prevarg $arg
286 }
287 }
288
289 if {[info exists nextargisval] || [info exists nextargisdatetime]} {
290 knerror "Missing value for '$prevarg' option"
291 }
292
293 set user [expr {[info exists userlist] && [getState username] in\
294 $userlist}]
295 set group [expr {[info exists grouplist] && [isIntBetweenList\
296 $grouplist [getState usergroups]]}]
297
298 # does it apply to current user?
299 set notuser [expr {[info exists notuserlist] && [getState username] in\
300 $notuserlist}]
301 set notgroup [expr {[info exists notgrouplist] && [isIntBetweenList\
302 $notgrouplist [getState usergroups]]}]
303
304 # does it apply currently?
305 set isbefore [expr {[info exists before] && [getState clock_seconds] <\
306 $before}]
307 set isafter [expr {[info exists after] && [getState clock_seconds] >=\
308 $after}]
309
310
311 set user_or_group_target_defined [expr {[info exists userlist] || [info\
312 exists grouplist]}]
313 set user_or_group_targeted [expr {$user || $group}]
314 set user_or_group_excluded [expr {$notuser || $notgroup}]
315 set time_frame_defined [expr {[info exists before] || [info exists after]}]
316 set in_time_frame [expr {!$time_frame_defined || $isbefore || $isafter}]
317 set in_near_time_frame [expr {[info exists after] && !$isafter &&\
318 [getState clock_seconds] >= ($after - $nearsec)}]
319
320 set apply [expr {$in_time_frame && ($user_or_group_targeted ||\
321 (!$user_or_group_target_defined && !$user_or_group_excluded))}]
322
323 # is end limit near ?
324 set isnearly [expr {!$apply && ($user_or_group_targeted ||\
325 (!$user_or_group_target_defined && !$user_or_group_excluded)) &&\
326 $in_near_time_frame}]
327 if {![info exists afterraw]} {
328 set afterraw {}
329 }
330
331 return [list $apply $isnearly $afterraw $otherargs]
332 }
333
334 proc setModspecTag {modspec tag {props {}}} {
335 reportDebug "Set tag '$tag' with properties '$props' on module\
336 specification '$modspec'"
337
338 if {[isModuleFullPath $modspec]} {
339 # use dedicated structure for full path module specifications
340 if {![info exists ::g_moduleTagFullPath($modspec)] || $tag ni\
341 $::g_moduleTagFullPath($modspec)} {
342 lappend ::g_moduleTagFullPath($modspec) $tag
343 } else {
344 set idx [lsearch -exact $::g_moduleTagFullPath($modspec) $tag]
345 }
346 # record props associated to tag
347 if {[info exists idx]} {
348 lset ::g_moduleTagFullPathSpec($modspec) $idx $props
349 } else {
350 lappend ::g_moduleTagFullPathSpec($modspec) $props
351 }
352 } else {
353 # record tag list for mod root to optimize search
354 set modroot [getModuleRootFromVersSpec $modspec]
355 if {![info exists ::g_moduleTagRoot($modroot)]} {
356 lappend ::g_moduleTagRoot($modroot) $tag
357 set idx 0
358 set new 1
359 } else {
360 set idx [lsearch -exact $::g_moduleTagRoot($modroot) $tag]
361 if {$idx == -1} {
362 set idx [llength $::g_moduleTagRoot($modroot)]
363 lappend ::g_moduleTagRoot($modroot) $tag
364 set new 1
365 }
366 }
367
368 # then record mod spec and props at idx defined for tag. new spec are
369 # appended and firstly matching spec is returned with its props on
370 # search
371 if {[info exists new]} {
372 lappend ::g_moduleTagRootSpec($modroot) [list $modspec $props]
373 } else {
374 set tagrootlist [lindex $::g_moduleTagRootSpec($modroot) $idx]
375 lappend tagrootlist $modspec $props
376 lset ::g_moduleTagRootSpec($modroot) $idx $tagrootlist
377 }
378 }
379 }
380
381 proc module-forbid {args} {
382 # parse application criteria arguments to determine if command apply
383 lassign [parseApplicationCriteriaArgs 1 [expr {[getConf\
384 nearly_forbidden_days] * 86400}] {*}$args] apply isnearly after\
385 otherargs
386
387 # parse remaining argument list, do it even if command does not apply to
388 # raise any command specification error
389 foreach arg $otherargs {
390 if {[info exists nextargisval]} {
391 ##nagelfar vartype nextargisval varName
392 set $nextargisval $arg
393 unset nextargisval
394 } else {
395 switch -glob -- $arg {
396 --nearly-message {
397 set nextargisval nearlymessage
398 }
399 --message {
400 set nextargisval message
401 }
402 -* {
403 knerror "Invalid option '$arg'"
404 }
405 default {
406 lappend modarglist $arg
407 }
408 }
409 set prevarg $arg
410 }
411 }
412
413 if {[info exists nextargisval]} {
414 knerror "Missing value for '$prevarg' option"
415 }
416
417 if {![info exists modarglist]} {
418 knerror {No module specified in argument}
419 }
420
421 # skip record if application criteria are not met
422 if {$apply} {
423 set proplist {}
424 if {[info exists message]} {
425 ##nagelfar ignore Found constant
426 lappend proplist message $message
427 }
428
429 # record each forbid spec after parsing them
430 foreach modarg [parseModuleSpecification 0 0 0 0 {*}$modarglist] {
431 setModspecTag $modarg forbidden $proplist
432 }
433 } elseif {$isnearly} {
434 ##nagelfar ignore Found constant
435 lappend proplist after $after
436 if {[info exists nearlymessage]} {
437 ##nagelfar ignore Found constant
438 lappend proplist message $nearlymessage
439 }
440 # record each nearly forbid spec after parsing them
441 foreach modarg [parseModuleSpecification 0 0 0 0 {*}$modarglist] {
442 setModspecTag $modarg nearly-forbidden $proplist
443 }
444 }
445 }
446
447 proc module-hide {args} {
448 set hidinglvl 1
449 set hiddenloaded 0
450
451 # parse application criteria arguments to determine if command apply
452 lassign [parseApplicationCriteriaArgs 1 0 {*}$args] apply isnearly after\
453 otherargs
454
455 # parse remaining argument list, do it even if command does not apply to
456 # raise any command specification error
457 foreach arg $otherargs {
458 switch -glob -- $arg {
459 --hard {
460 # hardened stealth
461 set hidinglvl 2
462 }
463 --soft {
464 # soften level of camouflage
465 set hidinglvl 0
466 }
467 --hidden-loaded {
468 # module should stay hidden once being loaded
469 set hiddenloaded 1
470 }
471 -* {
472 knerror "Invalid option '$arg'"
473 }
474 default {
475 lappend modarglist $arg
476 }
477 }
478 }
479
480 if {![info exists modarglist]} {
481 knerror {No module specified in argument}
482 }
483
484 # skip hide spec record if application criteria are not met
485 if {$apply} {
486 # record each hide spec after parsing them
487 foreach modarg [parseModuleSpecification 0 0 0 0 {*}$modarglist] {
488 setModspecHidingLevel $modarg $hidinglvl
489 if {$hiddenloaded} {
490 setModspecTag $modarg hidden-loaded
491 }
492 }
493 }
494 }
495
496 proc hide-modulefile {modfile} {
497 module-hide $modfile
498 }
499
500 proc module-tag {args} {
501 # parse application criteria arguments to determine if command apply
502 lassign [parseApplicationCriteriaArgs 0 0 {*}$args] apply isnearly after\
503 otherargs
504
505 # parse remaining argument list, do it even if command does not apply to
506 # raise any command specification error
507 foreach arg $otherargs {
508 switch -glob -- $arg {
509 -* {
510 knerror "Invalid option '$arg'"
511 }
512 default {
513 if {![info exists tag]} {
514 set tag $arg
515 } else {
516 lappend modarglist $arg
517 }
518 }
519 }
520 }
521
522 if {![info exists tag]} {
523 knerror {No tag specified in argument}
524 }
525 if {![info exists modarglist]} {
526 knerror {No module specified in argument}
527 }
528 if {$tag in [list loaded auto-loaded forbidden nearly-forbidden hidden\
529 hidden-loaded warning]} {
530 knerror "'$tag' is a reserved tag name and cannot be set"
531 }
532
533 # skip tag record if application criteria are not met
534 if {$apply} {
535 # record each hide spec after parsing them
536 foreach modarg [parseModuleSpecification 0 0 0 0 {*}$modarglist] {
537 setModspecTag $modarg $tag
538 }
539 }
540 }
541
542 # parse arguments sent to the unsetenv modulefile command
543 proc parseSetenvCommandArgs {mode dflbhv args} {
544 set bhv $dflbhv
545 foreach arg $args {
546 switch -- $arg {
547 --set-if-undef {
548 if {$mode eq {load}} {
549 set setifundef 1
550 }
551 }
552 default {
553 if {![info exists var]} {
554 set var $arg
555 } elseif {![info exists val]} {
556 set val $arg
557 } else {
558 # too much argument
559 set wrongargnum 1
560 }
561 }
562 }
563 }
564
565 if {[info exists wrongargnum] || ![info exists var] || ![info exists\
566 val]} {
567 knerror {wrong # args: should be "setenv ?--set-if-undef? var val"}
568 }
569
570 if {[info exists setifundef] && [isEnvVarDefined $var]} {
571 set bhv noop
572 }
573
574 reportDebug "bhv=$bhv, var=$var, val=$val"
575 return [list $bhv $var $val]
576 }
577
578 proc setenv {args} {
579 lassign [parseSetenvCommandArgs load set {*}$args] bhv var val
580
581 # indicate env var name to configured traces
582 setState current_envvar $var
583
584 if {$bhv eq {set}} {
585 # clean any previously defined reference counter array
586 unset-env [getModshareVarName $var] 1
587
588 # clean any previously defined pushenv stack
589 unset-env [getPushenvVarName $var] 1
590
591 # Set the variable for later use during the modulefile evaluation
592 set-env $var $val
593 }
594
595 return {}
596 }
597
598 # undo setenv in unload mode
599 proc setenv-un {args} {
600 lassign [parseSetenvCommandArgs unload unset {*}$args] bhv var val
601
602 # indicate env var name to configured traces
603 setState current_envvar $var
604
605 # clean any existing reference counter array
606 unset-env [getModshareVarName $var] 1
607
608 # clean any previously defined pushenv stack
609 unset-env [getPushenvVarName $var] 1
610
611 # Add variable to the list of variable to unset in shell output code but
612 # set it in interp context as done on load mode for later use during the
613 # modulefile evaluation
614 unset-env $var 0 $val
615
616 return {}
617 }
618
619 # optimized setenv for whatis mode: init env variable with an empty
620 # value if undefined. do not care about value, just avoid variable to be
621 # undefined for later use during the modulefile evaluation
622 proc setenv-wh {args} {
623 lassign [parseSetenvCommandArgs load set {*}$args] bhv var val
624
625 # indicate env var name to configured traces
626 setState current_envvar $var
627
628 setEnvVarIfUndefined $var {}
629 return {}
630 }
631
632 # parse arguments sent to the getenv modulefile command
633 proc parseGetenvCommandArgs {cmd args} {
634 set returnval 0
635 set valifundef {}
636 switch -- [llength $args] {
637 1 {
638 set var [lindex $args 0]
639 }
640 2 {
641 switch -- [lindex $args 0] {
642 --return-value {
643 set returnval 1
644 set var [lindex $args 1]
645 }
646 default {
647 set var [lindex $args 0]
648 set valifundef [lindex $args 1]
649 }
650 }
651 }
652 3 {
653 if {[lindex $args 0] ne {--return-value}} {
654 set wrongargs 1
655 } else {
656 set returnval 1
657 set var [lindex $args 1]
658 set valifundef [lindex $args 2]
659 }
660 }
661 default {
662 set wrongargs 1
663 }
664 }
665
666 set argname [expr {$cmd eq {getenv} ? {variable} : {name}}]
667 if {[info exists wrongargs]} {
668 knerror "wrong # args: should be \"$cmd ?--return-value? $argname\
669 ?valifundef?\""
670 }
671
672 reportDebug "$argname='$var', valifundef='$valifundef',\
673 returnval='$returnval'"
674 return [list $var $valifundef $returnval]
675 }
676
677 proc getenv {args} {
678 # parse args
679 lassign [parseGetenvCommandArgs getenv {*}$args] var valifundef returnval
680
681 if {[currentState mode] ne {display} || $returnval} {
682 return [get-env $var $valifundef]
683 } else {
684 return "\$$var"
685 }
686 }
687
688 # parse arguments sent to the unsetenv modulefile command
689 proc parseUnsetenvCommandArgs {mode dflbhv args} {
690 foreach arg $args {
691 switch -- $arg {
692 --unset-on-unload {
693 if {$mode eq {unload}} {
694 set bhv unset
695 }
696 }
697 --noop-on-unload {
698 if {$mode eq {unload}} {
699 set bhv noop
700 }
701 }
702 default {
703 if {![info exists var]} {
704 set var $arg
705 } elseif {![info exists val]} {
706 set val $arg
707 if {$mode eq {unload} && ![info exists bhv]} {
708 set bhv set
709 }
710 } else {
711 # too much argument
712 set wrongargnum 1
713 }
714 }
715 }
716 }
717
718 if {[info exists wrongargnum] || ![info exists var]} {
719 knerror {wrong # args: should be "unsetenv ?--noop-on-unload?\
720 ?--unset-on-unload? var ?val?"}
721 }
722
723 if {![info exists bhv]} {
724 set bhv $dflbhv
725 }
726
727 # initialize val to always return same structure, val is only used if bhv
728 # equals 'set'
729 if {![info exists val]} {
730 set val {}
731 }
732
733 reportDebug "bhv=$bhv, var=$var, val=$val"
734 return [list $bhv $var $val]
735 }
736
737 proc unsetenv {args} {
738 lassign [parseUnsetenvCommandArgs load unset {*}$args] bhv var val
739
740 # indicate env var name to configured traces
741 setState current_envvar $var
742
743 # clean any existing reference counter array
744 unset-env [getModshareVarName $var] 1
745
746 # clean any previously defined pushenv stack
747 unset-env [getPushenvVarName $var] 1
748
749 # Set the variable for later use during the modulefile evaluation
750 unset-env $var
751
752 return {}
753 }
754
755 # undo unsetenv in unload mode
756 proc unsetenv-un {args} {
757 lassign [parseUnsetenvCommandArgs unload noop {*}$args] bhv var val
758
759 # indicate env var name to configured traces
760 setState current_envvar $var
761
762 switch -- $bhv {
763 set {
764 # apply value specified for set on unload
765 return [setenv $var $val]
766 }
767 unset {
768 return [unsetenv $var]
769 }
770 noop {
771 # otherwise just clear variable if it does not exist on unload mode
772 # for later use during the modulefile evaluation
773 if {![isEnvVarDefined $var]} {
774 reset-to-unset-env $var
775 }
776 }
777 }
778 return {}
779 }
780
781 # optimized unsetenv for whatis mode: init env variable with an empty
782 # value if undefined. do not care about value, just avoid variable to be
783 # undefined for later use during the modulefile evaluation
784 proc unsetenv-wh {args} {
785 lassign [parseUnsetenvCommandArgs load noop {*}$args] bhv var val
786
787 # indicate env var name to configured traces
788 setState current_envvar $var
789
790 setEnvVarIfUndefined $var {}
791 return {}
792 }
793
794 proc chdir {dir} {
795 if {[file exists $dir] && [file isdirectory $dir]} {
796 set ::g_changeDir $dir
797 } else {
798 # report issue but does not treat it as an error to have the
799 # same behavior as C-version
800 reportWarning "Cannot chdir to '$dir' for '[currentState modulename]'"
801 }
802
803 return {}
804 }
805
806 # supersede exit command to handle it if called within a modulefile
807 # rather than exiting the whole process
808 proc exitModfileCmd {{code 0}} {
809 if {[currentState mode] in {load refresh}} {
810 setState inhibit_interp 1
811 }
812
813 # break to gently end interpretation of current modulefile
814 return -code break
815 }
816
817 # enables sub interp to return ModulesVersion value to the main interp
818 proc setModulesVersion {val} {
819 set ::ModulesVersion $val
820 }
821
822 # supersede puts command to catch content sent to stdout/stderr within
823 # modulefile in order to correctly send stderr content (if a pager has been
824 # enabled) or postpone content channel send after rendering on stdout the
825 # relative environment changes required by the modulefile
826 proc putsModfileCmd {itrp args} {
827 # determine if puts call targets the stdout or stderr channel
828 switch -- [llength $args] {
829 1 {
830 # create struct with newline status and message to output
831 set deferPuts [list 1 [lindex $args 0]]
832 }
833 2 {
834 switch -- [lindex $args 0] {
835 -nonewline {
836 set deferPuts [list 0 [lindex $args 1]]
837 }
838 stdout {
839 set deferPuts [list 1 [lindex $args 1]]
840 }
841 prestdout {
842 set deferPrePuts [list 1 [lindex $args 1]]
843 }
844 stderr {
845 set reportArgs [list [lindex $args 1]]
846 }
847 log {
848 set logPuts [lindex $args 1]
849 }
850 }
851 }
852 3 {
853 if {[lindex $args 0] eq {-nonewline}} {
854 switch -- [lindex $args 1] {
855 stdout {
856 set deferPuts [list 0 [lindex $args 2]]
857 }
858 prestdout {
859 set deferPrePuts [list 0 [lindex $args 2]]
860 }
861 stderr {
862 set reportArgs [list [lindex $args 2] 1]
863 }
864 log {
865 set logPuts [lindex $args 2]
866 }
867 }
868 } else {
869 set wrongNumArgs 1
870 }
871 }
872 default {
873 set wrongNumArgs 1
874 }
875 }
876
877 # raise error if bad argument number detected, do this here rather in _puts
878 # not to confuse people with an error reported by an internal name (_puts)
879 if {[info exists wrongNumArgs]} {
880 knerror {wrong # args: should be "puts ?-nonewline? ?channelId? string"}
881 # send content to log system
882 } elseif {[info exists logPuts]} {
883 log $logPuts
884 # defer puts if it targets stdout (see renderSettings)
885 } elseif {[info exists deferPuts]} {
886 # current module is qualified for refresh evaluation
887 lappendState -nodup refresh_qualified [currentState modulename]
888 lappend ::g_stdoutPuts {*}$deferPuts
889 } elseif {[info exists deferPrePuts]} {
890 lappendState -nodup refresh_qualified [currentState modulename]
891 lappend ::g_prestdoutPuts {*}$deferPrePuts
892 # if it targets stderr call report, which knows what channel to use
893 } elseif {[info exists reportArgs]} {
894 # report message only if not silent
895 if {[isVerbosityLevel concise]} {
896 report {*}$reportArgs
897 }
898 # pass to real puts command if not related to stdout and do that in modfile
899 # interpreter context to get access to eventual specific channel
900 } else {
901 # re-throw error as a known error for accurate stack trace print
902 if {[catch {$itrp eval _puts $args} errMsg]} {
903 knerror $errMsg MODULES_ERR_CUSTOM
904 }
905 }
906 }
907
908 proc prepend-path {args} {
909 # Set the variable for later use during the modulefile evaluation
910 add-path prepend-path load prepend {*}$args
911
912 return {}
913 }
914
915 proc prepend-path-un {args} {
916 # Set the variable for later use during the modulefile evaluation
917 unload-path prepend-path unload remove {*}$args
918
919 return {}
920 }
921
922 proc append-path {args} {
923 # Set the variable for later use during the modulefile evaluation
924 add-path append-path load append {*}$args
925
926 return {}
927 }
928
929 proc append-path-un {args} {
930 # Set the variable for later use during the modulefile evaluation
931 unload-path append-path unload remove {*}$args
932
933 return {}
934 }
935
936 proc remove-path {args} {
937 # Set the variable for later use during the modulefile evaluation
938 unload-path remove-path load remove {*}$args
939
940 return {}
941 }
942
943 # undo remove-path in unload mode
944 proc remove-path-un {args} {
945 lassign [unload-path remove-path unload noop {*}$args] bhv var
946
947 # clean any previously defined pushenv stack
948 unset-env [getPushenvVarName $var] 1
949
950 # clear variable if it does not exist on unload mode for later use
951 # during the modulefile evaluation
952 if {![isEnvVarDefined $var]} {
953 reset-to-unset-env $var
954 }
955 }
956
957 # optimized *-path for whatis mode: init env variable with an empty value if
958 # undefined. do not care about value, just avoid variable to be undefined for
959 # later use during the modulefile evaluation
960 proc edit-path-wh {cmd args} {
961 # get variable name
962 lassign [parsePathCommandArgs $cmd load noop {*}$args] separator allow_dup\
963 idx_val ign_refcount val_set_is_delim glob_match bhv var path_list
964
965 # indicate env var name to configured traces
966 setState current_envvar $var
967
968 setEnvVarIfUndefined $var {}
969
970 return {}
971 }
972
973 proc set-alias {alias what} {
974 set ::g_Aliases($alias) $what
975 set ::g_stateAliases($alias) new
976
977 # current module is qualified for refresh evaluation
978 lappendState -nodup refresh_qualified [currentState modulename]
979
980 return {}
981 }
982
983 # undo set-alias in unload mode
984 proc set-alias-un {alias what} {
985 return [unset-alias $alias]
986 }
987
988 proc unset-alias {alias} {
989 set ::g_Aliases($alias) {}
990 set ::g_stateAliases($alias) del
991
992 return {}
993 }
994
995 proc set-function {function what} {
996 set ::g_Functions($function) $what
997 set ::g_stateFunctions($function) new
998
999 # current module is qualified for refresh evaluation
1000 lappendState -nodup refresh_qualified [currentState modulename]
1001
1002 return {}
1003 }
1004
1005 # undo set-function in unload mode
1006 proc set-function-un {function what} {
1007 return [unset-function $function]
1008 }
1009
1010 proc unset-function {function} {
1011 set ::g_Functions($function) {}
1012 set ::g_stateFunctions($function) del
1013
1014 return {}
1015 }
1016
1017
1018 proc is-loaded {args} {
1019 # parse module version specification
1020 set args [parseModuleSpecification 0 0 0 0 {*}$args]
1021
1022 foreach mod $args {
1023 if {[getLoadedMatchingName $mod returnfirst] ne {}} {
1024 return 1
1025 }
1026 }
1027 # is something loaded whatever it is?
1028 return [expr {![llength $args] && [llength\
1029 [getEnvLoadedModulePropertyParsedList name]]}]
1030 }
1031
1032 proc is-loading {args} {
1033 foreach mod $args {
1034 if {[getLoadedMatchingName $mod returnfirst 1] ne {}} {
1035 return 1
1036 }
1037 }
1038 # is something else loading whatever it is?
1039 return [expr {![llength $args] && [llength [getLoadingModuleList]] > 1}]
1040 }
1041
1042 proc conflict {args} {
1043 set currentModule [currentState modulename]
1044 set curmodnamevr [currentState modulenamevr]
1045 # get module short name if loaded by its full pathname
1046 if {[set isfullpath [isModuleFullPath $currentModule]]} {
1047 set currentSModule [findModuleNameFromModulefile $currentModule]
1048 }
1049
1050 set conflict_unload [expr {[getConf conflict_unload] && [getConf\
1051 auto_handling]}]
1052
1053 # parse module version specification
1054 set args [parseModuleSpecification 0 0 0 0 {*}$args]
1055
1056 registerCurrentModuleConflict {*}$args
1057
1058 foreach mod $args {
1059 set is_conflict_loading 0
1060 set unload_attempt 0
1061 set loaded_conflict_mod_list [getLoadedMatchingName $mod returnall]
1062
1063 if {![llength $loaded_conflict_mod_list]} {
1064 set eq_current_mod [expr {[modEq $mod $currentModule eqstart 1 2 1]\
1065 || ($isfullpath && [modEq $mod $currentSModule eqstart 1 2 1])}]
1066 # currently evaluating module should not be mistaken for loading
1067 # conflicting module
1068 if {!$eq_current_mod} {
1069 set loaded_conflict_mod_list [getLoadedMatchingName $mod\
1070 returnall 1]
1071 if {[llength $loaded_conflict_mod_list]} {
1072 # no conflict unload attempt on loading module
1073 set is_conflict_loading 1
1074 }
1075 }
1076 } elseif {$conflict_unload} {
1077 set still_loaded_conflict_mod_list {}
1078 # unload attempt in reverse load order
1079 foreach loaded_conflict_mod [lreverse $loaded_conflict_mod_list] {
1080 if {[cmdModuleUnload conun match 1 s 0 $loaded_conflict_mod]} {
1081 lappend still_loaded_conflict_mod_list $loaded_conflict_mod
1082 }
1083 }
1084 set loaded_conflict_mod_list $still_loaded_conflict_mod_list
1085 set unload_attempt 1
1086 }
1087
1088 if {[llength $loaded_conflict_mod_list]} {
1089 setConflictErrorAsReported {*}$loaded_conflict_mod_list
1090
1091 # error msg has already been sent if a conflict unload was attempted
1092 set msg [expr {$unload_attempt ? {} : [getPresentConflictErrorMsg\
1093 $curmodnamevr $loaded_conflict_mod_list $is_conflict_loading]}]
1094 knerrorOrWarningIfForced $msg MODULES_ERR_GLOBAL
1095 }
1096 }
1097
1098 return {}
1099 }
1100
1101 proc registerCurrentModuleConflict {args} {
1102 # register conflict list unless record inhibited for current iterp context
1103 if {[currentState inhibit_req_record] != [currentState evalid]} {
1104 setLoadedConflict [currentState modulename] {*}$args
1105 }
1106 }
1107
1108 proc parsePrereqCommandArgs {cmd args} {
1109 set tag_list {}
1110 set modulepath_list {}
1111 set optional 0
1112 set opt_list {}
1113 set prereq_list {}
1114
1115 # parse options defined
1116 set i 0
1117 foreach arg $args {
1118 if {[info exists nextargistaglist]} {
1119 set tag_list [split $arg :]
1120 lappend opt_list $arg
1121 unset nextargistaglist
1122 } elseif {[info exists nextargismodulepathlist]} {
1123 set modulepath_list {}
1124 # record list of absolute paths
1125 foreach modulepath [split $arg :] {
1126 lappend modulepath_list [getAbsolutePath $modulepath]
1127 }
1128 lappend opt_list $arg
1129 unset nextargismodulepathlist
1130 } else {
1131 switch -glob -- $arg {
1132 --optional {
1133 set optional 1
1134 lappend opt_list $arg
1135 }
1136 --tag=* {
1137 set tag_list [split [string range $arg 6 end] :]
1138 lappend opt_list $arg
1139 if {![llength $tag_list]} {
1140 knerror "Missing value for '--tag' option"
1141 }
1142 }
1143 --tag {
1144 set nextargistaglist 1
1145 lappend opt_list $arg
1146 }
1147 --modulepath {
1148 set nextargismodulepathlist 1
1149 lappend opt_list $arg
1150 }
1151 -* {
1152 knerror "Invalid option '$arg'"
1153 }
1154 default {
1155 set prereq_list [lrange $args $i end]
1156 # end option parsing: remaining elts are list of prereqs
1157 break
1158 }
1159 }
1160 }
1161 incr i
1162 }
1163
1164 foreach tag $tag_list {
1165 if {$tag in [list loaded auto-loaded forbidden nearly-forbidden\
1166 hidden warning]} {
1167 knerror "Tag '$tag' cannot be manually set"
1168 }
1169 }
1170 if {![llength $prereq_list]} {
1171 knerror "wrong # args: should be \"$cmd ?--optional? ?--tag? ?taglist?\
1172 ?--modulepath? ?modulepathlist? modulefile ?...?\""
1173 } elseif {[set mispopt [lsearch -inline -glob $prereq_list --*]] ne {}} {
1174 knerror "Misplaced option '$mispopt'"
1175 }
1176
1177 # parse module version specification
1178 set prereq_list [parseModuleSpecification 0 0 0 0 {*}$prereq_list]
1179
1180 return [list $tag_list $modulepath_list $optional $opt_list $prereq_list]
1181 }
1182
1183 proc prereqAnyModfileCmd {tryload auto args} {
1184 lassign [parsePrereqCommandArgs prereq {*}$args] tag_list modulepath_list\
1185 optional opt_list args
1186
1187 set currentModule [currentState modulename]
1188 set curmodnamevr [currentState modulenamevr]
1189
1190 # register prereq list (sets of optional prereq are registered as list)
1191 # unless record inhibited for current iterp context
1192 if {[currentState inhibit_req_record] != [currentState evalid]} {
1193 # if requirement is optional, add current module to the recorded prereq
1194 # list to make the requirement rule satisfied even if none loaded, as
1195 # current module will be loaded
1196 if {$optional} {
1197 lappend record_list $currentModule
1198 }
1199 lappend record_list {*}$args
1200 setLoadedPrereq $currentModule $record_list
1201
1202 if {[llength $modulepath_list]} {
1203 setLoadedPrereqPath $currentModule $record_list $modulepath_list
1204 }
1205 }
1206
1207 if {$auto} {
1208 # convert modulepath list to keep entries not matching any enabled
1209 # modulepaths and transform entries into all matching enabled modulepath
1210 set converted_list {}
1211 foreach modulepath $modulepath_list {
1212 set matching_list [getMatchingModulepathList $modulepath]
1213 if {[llength $matching_list]} {
1214 lappendNoDup converted_list {*}$matching_list
1215 } else {
1216 lappendNoDup converted_list $modulepath
1217 }
1218 }
1219 set modulepath_list $converted_list
1220
1221 # try to load prereq as dependency resolving is enabled
1222 lassign [loadRequirementModuleList $tryload $optional $tag_list\
1223 $modulepath_list {*}$args] retlo prereqloaded
1224 } else {
1225 set loadedmod_list {}
1226 foreach mod $args {
1227 # get all loaded or loading mod in args list
1228 if {[set loadedmod [getLoadedMatchingName $mod returnfirst 0 {}\
1229 $modulepath_list]] ne {} || [set loadedmod [getLoadedMatchingName\
1230 $mod returnfirst 1 {} $modulepath_list]] ne {}} {
1231 lappend loadedmod_list $loadedmod
1232 }
1233 }
1234 set prereqloaded [llength $loadedmod_list]
1235 }
1236
1237 if {!$prereqloaded} {
1238 if {!$optional} {
1239 # error if requirement is not satisfied unless if optional
1240 reportMissingPrereqError $curmodnamevr $modulepath_list {*}$args
1241 }
1242 } elseif {!$auto} {
1243 # apply missing tag to all loaded module found (already done when
1244 # dependency resolving is enabled)
1245 cmdModuleTag 0 0 $tag_list {*}$loadedmod_list
1246 }
1247
1248 return {}
1249 }
1250
1251 proc x-resource {resource {value {}}} {
1252 # sometimes x-resource value may be provided within resource name
1253 # as the "x-resource {Ileaf.popup.saveUnder: True}" example provided
1254 # in manpage. so here is an attempt to extract real resource name and
1255 # value from resource argument
1256 if {![string length $value] && ![file exists $resource]} {
1257 # look first for a space character as delimiter, then for a colon
1258 set sepapos [string first { } $resource]
1259 if { $sepapos == -1 } {
1260 set sepapos [string first : $resource]
1261 }
1262
1263 if { $sepapos > -1 } {
1264 set value [string range $resource $sepapos+1 end]
1265 set resource [string range $resource 0 $sepapos-1]
1266 reportDebug "corrected ($resource, $value)"
1267 } else {
1268 # if not a file and no value provided x-resource cannot be
1269 # recorded as it will produce an error when passed to xrdb
1270 reportWarning "x-resource $resource is not a valid string or file"
1271 return {}
1272 }
1273 }
1274
1275 # check current environment can handle X11 resource edition elsewhere exit
1276 if {[catch {runCommand xrdb -query} errMsg]} {
1277 knerror "X11 resources cannot be edited, issue spotted\n[sgr er\
1278 ERROR]: $errMsg" MODULES_ERR_GLOBAL
1279 }
1280
1281 # if a resource does hold an empty value in g_newXResources or
1282 # g_delXResources arrays, it means this is a resource file to parse
1283 if {[currentState mode] eq {load}} {
1284 set ::g_newXResources($resource) $value
1285 } else {
1286 set ::g_delXResources($resource) $value
1287 }
1288
1289 return {}
1290 }
1291
1292 proc uname {what} {
1293 return [switch -- $what {
1294 sysname {getState os}
1295 machine {getState machine}
1296 nodename - node {getState nodename}
1297 release {getState osversion}
1298 domain {getState domainname}
1299 version {getState kernelversion}
1300 default {knerror "uname $what not supported"}
1301 }]
1302 }
1303
1304 # run shell command
1305 proc system {args} {
1306 # run through the appropriate shell
1307 if {[getState is_win]} {
1308 set shell cmd.exe
1309 set shellarg /c
1310 } else {
1311 set shell /bin/sh
1312 set shellarg -c
1313 }
1314
1315 if {[catch {exec >&@stderr $shell $shellarg [join $args]}]} {
1316 # non-zero exit status, get it:
1317 return [lindex $::errorCode 2]
1318 } else {
1319 # exit status was 0
1320 return 0
1321 }
1322 }
1323
1324 # test at least one of the collections passed as argument exists
1325 proc is-saved {args} {
1326 foreach coll $args {
1327 lassign [findCollections $coll exact] collfile colldesc
1328 if {[string length $collfile]} {
1329 return 1
1330 }
1331 }
1332 # is something saved whatever it is?
1333 return [expr {![llength $args] && [llength [findCollections]]}]
1334 }
1335
1336 # test at least one of the directories passed as argument is set in MODULEPATH
1337 proc is-used {args} {
1338 foreach path $args {
1339 if {[getUsedModulePathEntry $path] ne {}} {
1340 return 1
1341 }
1342 }
1343 # is something used whatever it is?
1344 return [expr {![llength $args] && [llength [getModulePathList]]}]
1345 }
1346
1347 # test at least one of the modulefiles passed as argument exists
1348 proc is-avail {args} {
1349 # parse module version specification
1350 # a module name is mandatory
1351 set args [parseModuleSpecification 0 0 0 0 {*}$args]
1352 set ret 0
1353
1354 # disable error reporting to avoid modulefile errors to pollute result
1355 inhibitErrorReport
1356
1357 foreach mod $args {
1358 lassign [getPathToModule $mod] modfile modname modnamevr
1359 if {$modfile ne {}} {
1360 set ret 1
1361 break
1362 }
1363 }
1364
1365 uninhibitErrorReport
1366 return $ret
1367 }
1368
1369 proc execShAndGetEnv {elt_ignored_list shell script args} {
1370 set sep {%ModulesShToMod%}
1371 set subsep {%ModulesSubShToMod%}
1372 set shdesc [list $script {*}$args]
1373 set sherr 0
1374 set shellopts [list]
1375
1376 upvar ignvarlist ignvarlist
1377 set ignvarlist [list OLDPWD PWD _ _AST_FEATURES PS1 _LMFILES_\
1378 LOADEDMODULES]
1379
1380 # define shell command to run to source script and analyze the environment
1381 # changes it performs
1382 switch -- [file tail $shell] {
1383 dash - sh {
1384 # declare is not supported by dash but functions cannot be retrieved
1385 # anyway, so keep using declare and throw errors out to avoid overall
1386 # execution error. dash does not pass arguments to sourced script but
1387 # it does not raise error if arguments are set
1388 ##nagelfar ignore +3 Found constant
1389 set command "export -p; echo $sep; declare -f 2>/dev/null; echo\
1390 $sep; alias; echo $sep; echo $sep; pwd; echo $sep; . [listTo\
1391 shell $shdesc] 2>&1; echo $sep; export -p; echo $sep; declare -f\
1392 2>/dev/null; echo $sep; alias; echo $sep; echo $sep; pwd"
1393 set varre {export (\S+?)=["']?(.*?)["']?$}
1394 set funcre {(\S+?) \(\)\s?\n?{\s?\n(.+?)\n}$}
1395 set aliasre {([^='\s]+?)='?(.*?)'$}
1396 set varvalmap [list {\"} \" \\\\ \\]
1397 set alvalmap [list {'\''} ' {'"'"'} ']
1398 }
1399 bash {
1400 ##nagelfar ignore +2 Found constant
1401 set command "export -p; echo $sep; declare -f; echo $sep; alias;\
1402 echo $sep; complete; echo $sep; pwd; echo $sep; . [listTo shell\
1403 $shdesc] 2>&1; echo $sep; export -p; echo $sep; declare -f; echo\
1404 $sep; alias; echo $sep; complete; echo $sep; pwd"
1405 set varre {declare -x (\S+?)="(.*?)"$}
1406 set funcre {(\S+?) \(\)\s?\n{\s?\n(.+?)\n}$}
1407 set aliasre {alias (\S+?)='(.*?)'$}
1408 set compre {complete (.+?) (\S+?)$}
1409 set comprevar [list match value name]
1410 set varvalmap [list {\"} \" \\\\ \\]
1411 set alvalmap [list {'\''} ']
1412 lappend shellopts --noprofile --norc
1413 }
1414 bash-eval {
1415 ##nagelfar ignore +3 Found constant
1416 set command "export -p; echo $sep; declare -f; echo $sep; alias;\
1417 echo $sep; complete; echo $sep; pwd; echo $sep; eval \"\$([listTo\
1418 shell $shdesc] 2>/dev/null)\"; echo $sep; export -p; echo $sep;\
1419 declare -f; echo $sep; alias; echo $sep; complete; echo $sep; pwd"
1420 set varre {declare -x (\S+?)="(.*?)"$}
1421 set funcre {(\S+?) \(\)\s?\n{\s?\n(.+?)\n}$}
1422 set aliasre {alias (\S+?)='(.*?)'$}
1423 set compre {complete (.+?) (\S+?)$}
1424 set comprevar [list match value name]
1425 set varvalmap [list {\"} \" \\\\ \\]
1426 set alvalmap [list {'\''} ']
1427 lappend shellopts --noprofile --norc
1428 }
1429 ksh - ksh93 {
1430 ##nagelfar ignore +3 Found constant
1431 set command "typeset -x; echo $sep; typeset +f | while read f; do\
1432 typeset -f \${f%\\(\\)}; echo; done; echo $sep; alias; echo $sep;\
1433 echo $sep; pwd; echo $sep; . [listTo shell $shdesc] 2>&1; echo\
1434 $sep; typeset -x; echo $sep; typeset +f | while read f; do\
1435 typeset -f \${f%\\(\\)}; echo; done; echo $sep; alias; echo $sep;\
1436 echo $sep; pwd"
1437 set varre {(\S+?)=\$?'?(.*?)'?$}
1438 set funcre {(\S+?)\(\) {\n?(.+?)}[;\n]?$}
1439 set aliasre {(\S+?)=\$?'?(.*?)'?$}
1440 set varvalmap [list {\'} ']
1441 set alvalmap [list {\"} \" {\\'} ' {\'} ' {\\\\} {\\}]
1442 }
1443 zsh {
1444 ##nagelfar ignore +2 Found constant
1445 set command "typeset -x; echo $sep; declare -f; echo $sep; alias;\
1446 echo $sep; echo $sep; pwd; echo $sep; . [listTo shell $shdesc]\
1447 2>&1; echo $sep; typeset -x; echo $sep; declare -f; echo $sep;\
1448 alias; echo $sep; echo $sep; pwd"
1449 set varre {(\S+?)=\$?'?(.*?)'?$}
1450 set funcre {(\S+?) \(\) {\n(.+?)\n}$}
1451 set aliasre {(\S+?)=\$?'?(.*?)'?$}
1452 set varvalmap [list {'\''} ']
1453 set alvalmap [list {'\''} ']
1454 }
1455 csh {
1456 ##nagelfar ignore +2 Found constant
1457 set command "setenv; echo $sep; echo $sep; alias; echo $sep; echo\
1458 $sep; pwd; echo $sep; source [listTo shell $shdesc] >&\
1459 /dev/stdout; echo $sep; setenv; echo $sep; echo $sep; alias; echo\
1460 $sep; echo $sep; pwd"
1461 set varre {(\S+?)=(.*?)$}
1462 set aliasre {(\S+?)\t(.*?)$}
1463 set varvalmap [list]
1464 set alvalmap [list]
1465 lappend shellopts -f
1466 }
1467 tcsh {
1468 ##nagelfar ignore +2 Found constant
1469 set command "setenv; echo $sep; echo $sep; alias; echo $sep;\
1470 complete; echo $sep; pwd; echo $sep; source [listTo shell\
1471 $shdesc] >& /dev/stdout; echo $sep; setenv; echo $sep; echo $sep;\
1472 alias; echo $sep; complete; echo $sep; pwd"
1473 set varre {(\S+?)=(.*?)$}
1474 set aliasre {(\S+?)\t\(?(.*?)\)?$}
1475 set compre {(\S+?)\t(.*?)$}
1476 set comprevar [list match name value]
1477 set varvalmap [list]
1478 set alvalmap [list]
1479 lappend shellopts -f
1480 }
1481 fish {
1482 # exclude from search builtins, fish-specific functions and private
1483 # functions defined prior script evaluation: reduce this way the
1484 # the number of functions to parse.
1485 set getfunc "set funcout (string match -r -v \$funcfilter (functions\
1486 -a -n) | while read f; functions \$f; echo '$subsep'; end)"
1487 ##nagelfar ignore +9 Found constant
1488 set command "set -xgL; echo '$sep'; status test-feature\
1489 regex-easyesc 2>/dev/null; and set escrepl '\\\\\\\\\$1'; or set\
1490 escrepl '\\\\\\\\\\\\\\\$1'; set funcfilter \\^\\((string\
1491 join '|' (string replace -r '(\\\[|\\.)' \$escrepl\
1492 (builtin -n; functions -a -n | string split ', ' | string match\
1493 -e -r '^_')))\\|fish\\.\\*\\)\\\$; $getfunc; $getfunc; string\
1494 split \$funcout; echo '$sep'; string split \$funcout; echo\
1495 '$sep'; complete; echo '$sep'; pwd; echo '$sep'; source [listTo\
1496 shell $shdesc] 2>&1; or exit \$status; echo '$sep'; set -xgL;\
1497 echo '$sep'; $getfunc; string split \$funcout; echo '$sep';\
1498 string split \$funcout; echo '$sep'; complete; echo '$sep'; pwd"
1499 set varre {^(\S+?\M) ?['"]?(.*?)['"]?$}
1500 # exclude alias from function list
1501 set funcre "^function (\\S+?)(?: \[^\\n\]*?--description\
1502 (?!'?alias)\[^\\n\]+)?\\n(.+?)?\\s*\\nend\\n$subsep\$"
1503 # fetch aliases from available functions
1504 set aliasre "^function (\\S+?) \[^\\n\]*?--description\
1505 '?alias\[^\\n\]+\\n\\s*(.+?)(?: \\\$argv)?\\s*\\nend\\n$subsep\$"
1506 set compre {complete ((?:-\S+? )*?)(?:(?:-c|--command)\
1507 )?([^-]\S+)(.*?)$}
1508 set comprevar [list match valpart1 name valpart2]
1509 # translate back fish-specific code
1510 set varvalmap [list {' '} : {' '} : {\'} ' {\"} \" \\\\ \\]
1511 set alvalmap [list { $argv;} {}]
1512
1513 # fish builtins change LS_COLORS variable
1514 lappend ignvarlist LS_COLORS
1515 }
1516 default {
1517 knerror "Shell '$shell' not supported"
1518 }
1519 }
1520
1521 if {![file exists $script]} {
1522 knerror "Script '$script' cannot be found"
1523 }
1524
1525 set real_shell [expr {$shell eq {bash-eval} ? {bash} : $shell}]
1526 set shellpath [getCommandPath $real_shell]
1527 if {$shellpath eq {}} {
1528 knerror "Shell '$shell' cannot be found"
1529 }
1530 set shellexec [list $shellpath {*}$shellopts -c $command]
1531
1532 reportDebug "running '$shellexec'"
1533 if {[catch {set output [exec {*}$shellexec]} output]} {
1534 set sherr 1
1535 }
1536
1537 # link result variables to calling context
1538 upvar cwdbefout cwdbefout cwdaftout cwdaftout
1539
1540 # extract each output sections
1541 set idx 0
1542 foreach varout {varbefout funcbefout aliasbefout compbefout cwdbefout\
1543 scriptout varaftout funcaftout aliasaftout compaftout cwdaftout} {
1544 ##nagelfar vartype varout varName
1545 if {[set sepidx [string first $sep $output $idx]] == -1} {
1546 set $varout [string trimright [string range $output $idx end] \n]
1547 if {$varout ne {cwdaftout} && !$sherr} {
1548 knerror "Unexpected output when sourcing '$shdesc' in shell\
1549 '$shell'"
1550 }
1551 } else {
1552 set $varout [string trimright [string range $output $idx $sepidx-1]\
1553 \n]
1554 set idx [expr {$sepidx + [string length $sep] + 1}]
1555 }
1556 # remove expected Tcl error message
1557 if {$sherr && $varout eq {scriptout} && [set erridx [string\
1558 last {child process exited abnormally} [set $varout]]] != -1} {
1559 set $varout [string range [set $varout] 0 $erridx-2]
1560 }
1561 }
1562 if {$sepidx != -1 && !$sherr} {
1563 knerror "Unexpected output when sourcing '$shdesc' in shell '$shell'"
1564 }
1565
1566 reportDebug "script output is '$scriptout'"
1567 if {$sherr} {
1568 # throw error if script had an issue, send script output along if any
1569 set errmsg "Script '$script' exited abnormally"
1570 if {$scriptout ne {}} {
1571 append errmsg "\n with following output\n$scriptout"
1572 }
1573 knerror $errmsg
1574 }
1575
1576 # link result variables to calling context
1577 upvar varbef varbef varaft varaft
1578 upvar funcbef funcbef funcaft funcaft
1579 upvar aliasbef aliasbef aliasaft aliasaft
1580 upvar compbef compbef compaft compaft
1581
1582 # clear current directory change if ignored
1583 if {{chdir} in $elt_ignored_list} {
1584 set cwdaftout $cwdbefout
1585 }
1586
1587 # extract environment variable information
1588 if {{envvar} ni $elt_ignored_list} {
1589 ##nagelfar ignore Found constant
1590 foreach {out arr} [list varbefout varbef varaftout varaft] {
1591 ##nagelfar vartype out varName
1592 foreach {match name value} [regexp -all -inline -lineanchor $varre\
1593 [set $out]] {
1594 # convert shell-specific escaping
1595 ##nagelfar ignore Suspicious variable name
1596 set ${arr}($name) [string map $varvalmap $value]
1597 }
1598 }
1599 }
1600 # extract function information if function supported by shell
1601 if {{function} ni $elt_ignored_list && [info exists funcre]} {
1602 ##nagelfar ignore Found constant
1603 foreach {out arr} [list funcbefout funcbef funcaftout funcaft] {
1604 foreach {match name value} [regexp -all -inline -lineanchor $funcre\
1605 [set $out]] {
1606 # no specific escaping to convert for functions
1607 ##nagelfar ignore Suspicious variable name
1608 set ${arr}($name) $value
1609 }
1610 }
1611 }
1612 # extract alias information
1613 if {{alias} ni $elt_ignored_list} {
1614 ##nagelfar ignore Found constant
1615 foreach {out arr} [list aliasbefout aliasbef aliasaftout aliasaft] {
1616 foreach {match name value} [regexp -all -inline -lineanchor $aliasre\
1617 [set $out]] {
1618 ##nagelfar ignore Suspicious variable name
1619 set ${arr}($name) [string map $alvalmap $value]
1620 }
1621 }
1622 }
1623 # extract complete information if supported by shell
1624 if {{complete} ni $elt_ignored_list && [info exists compre]} {
1625 ##nagelfar ignore Found constant
1626 foreach {out arr} [list compbefout compbef compaftout compaft] {
1627 ##nagelfar ignore Non constant variable list to foreach statement
1628 foreach $comprevar [regexp -all -inline -lineanchor $compre [set\
1629 $out]] {
1630 if {[info exists valpart1]} {
1631 ##nagelfar ignore Unknown variable
1632 set value [concat $valpart1 $valpart2]
1633 }
1634 # no specific escaping to convert for completes
1635 ##nagelfar ignore Suspicious variable name
1636 lappend ${arr}($name) $value
1637 }
1638 }
1639 }
1640 }
1641
1642 # execute script with args through shell and convert environment changes into
1643 # corresponding modulefile commands
1644 proc sh-to-mod {elt_ignored_list args} {
1645 set modcontent [list]
1646 set pathsep [getState path_separator]
1647 set shell [lindex $args 0]
1648
1649 # evaluate script and retrieve environment before and after evaluation
1650 # procedure will set result variables in current context
1651 ##nagelfar implicitvarcmd {execShAndGetEnv *} ignvarlist cwdbefout\
1652 cwdaftout varbef varaft funcbef funcaft aliasbef aliasaft compbef\
1653 compaft
1654 execShAndGetEnv $elt_ignored_list {*}$args
1655
1656 # check environment variable change
1657 lassign [getDiffBetweenArray varbef varaft] notaft diff notbef
1658 foreach name $notaft {
1659 # also ignore Modules variables intended for internal use
1660 if {$name ni $ignvarlist && ![string equal -length 10 $name\
1661 __MODULES_]} {
1662 lappend modcontent [list unsetenv $name]
1663 }
1664 }
1665 foreach name $diff {
1666 if {$name ni $ignvarlist && ![string equal -length 10 $name\
1667 __MODULES_]} {
1668 set idx [string first $varbef($name) $varaft($name)]
1669 set doprepend [expr {$idx > 0}]
1670 if {$doprepend} {
1671 # check from the end to get the largest chunk to prepend
1672 set idx [string last $varbef($name) $varaft($name)]
1673 # get delimiter from char found between new and existing value
1674 set predelim [string index $varaft($name) $idx-1]
1675 set delim $predelim
1676 }
1677 set appdelim_idx [expr {$idx + [string length $varbef($name)]}]
1678 set doappend [expr {$appdelim_idx < [string length $varaft($name)]}]
1679 if {$doappend} {
1680 set appdelim [string index $varaft($name) $appdelim_idx]
1681 set delim $appdelim
1682 }
1683 # new value is totally different (also consider a bare ':' as a
1684 # totally different value to avoid erroneous matches)
1685 # if content must both be prepended and appended but each side uses a
1686 # different delimiter character, consider new value totally different
1687 if {$varbef($name) eq $pathsep || $idx == -1 || ($doprepend &&\
1688 $doappend && $predelim ne $appdelim)} {
1689 lappend modcontent [list setenv $name $varaft($name)]
1690 } else {
1691 set alllist [list]
1692 # de-dup pre-existing list to correctly determine if new dup added
1693 lappendNoDup alllist {*}[split $varbef($name) $delim]
1694 set addmodcmd [list]
1695 # content should be prepended
1696 if {$doprepend} {
1697 set prelist [split [string range $varaft($name) 0 $idx-2]\
1698 $delim]
1699 # an empty element is added
1700 if {![llength $prelist]} {
1701 lappend prelist {}
1702 }
1703 lappend alllist {*}$prelist
1704 lappend addmodcmd prepend-path $prelist
1705 }
1706 # content should be appended
1707 if {$doappend} {
1708 set applist [split [string range $varaft($name) [expr\
1709 {$appdelim_idx + 1}] end] $delim]
1710 # an empty element is added
1711 if {![llength $applist]} {
1712 lappend applist {}
1713 }
1714 lappend alllist {*}$applist
1715 lappend addmodcmd append-path $applist
1716 }
1717
1718 # if a directory is found several times in prepended or appended
1719 # list, or across both list, or already in pre-existing value:
1720 # should not be de-duplicated by prepend-path/append-path's
1721 # default behavior, nor relocated by the path_entry_reorder
1722 # configuration option. a plain membership test (rather than
1723 # merging pre-existing value into alllist) is required here, as
1724 # merging would let lappendNoDup silently skip an entry already
1725 # in alllist, hiding the very overlap this check looks for
1726 set isdup [isDupInList $alllist]
1727
1728 foreach {cmd addlist} $addmodcmd {
1729 set addcmd [list $cmd]
1730 if {$isdup} {
1731 lappend addcmd --duplicates
1732 }
1733 if {$delim ne $pathsep} {
1734 lappend addcmd -d $delim
1735 }
1736 lappend addcmd $name {*}$addlist
1737 lappend modcontent $addcmd
1738 }
1739 }
1740 }
1741 }
1742 foreach name $notbef {
1743 if {$name ni $ignvarlist && ![string equal -length 10 $name\
1744 __MODULES_]} {
1745 if {[string first $pathsep $varaft($name)] == -1} {
1746 lappend modcontent [list setenv $name $varaft($name)]
1747 } else {
1748 # define a path-like variable if path separator found in it
1749 # split value and remove duplicate entries
1750 set vallist [list]
1751 lappendNoDup vallist {*}[split $varaft($name) $pathsep]
1752 lappend modcontent [list prepend-path $name {*}$vallist]
1753 }
1754 }
1755 }
1756 # check function change
1757 lassign [getDiffBetweenArray funcbef funcaft] notaft diff notbef
1758 foreach name $notaft {
1759 lappend modcontent [list unset-function $name]
1760 }
1761 foreach name [list {*}$diff {*}$notbef] {
1762 lappend modcontent [list set-function $name \n$funcaft($name)]
1763 }
1764 # check alias change
1765 lassign [getDiffBetweenArray aliasbef aliasaft] notaft diff notbef
1766 foreach name $notaft {
1767 lappend modcontent [list unset-alias $name]
1768 }
1769 foreach name [list {*}$diff {*}$notbef] {
1770 lappend modcontent [list set-alias $name $aliasaft($name)]
1771 }
1772 # check complete change
1773 set real_shell [expr {$shell eq {bash-eval} ? {bash} : $shell}]
1774 lassign [getDiffBetweenArray compbef compaft] notaft diff notbef
1775 foreach name $notaft {
1776 lappend modcontent [list uncomplete $name]
1777 }
1778 foreach name [list {*}$diff {*}$notbef] {
1779 foreach body $compaft($name) {
1780 lappend modcontent [list complete $real_shell $name $body]
1781 }
1782 }
1783 # check current working directory change
1784 if {$cwdbefout ne $cwdaftout} {
1785 lappend modcontent [list chdir $cwdaftout]
1786 }
1787
1788 # sort result to ensure consistent output whatever the evaluation shell
1789 set modcontent [lsort -dictionary $modcontent]
1790
1791 reportDebug "resulting env changes '$modcontent'"
1792 return $modcontent
1793 }
1794
1795 proc parseSourceShArgs {args} {
1796 set elt_ignored_list {}
1797
1798 set i 0
1799 foreach arg $args {
1800 incr i
1801 if {[info exists nextargisval]} {
1802 ##nagelfar vartype nextargisval varName
1803 set $nextargisval $arg
1804 unset nextargisval
1805 } else {
1806 switch -glob -- $arg {
1807 --ignore {
1808 set nextargisval ignore_opt_raw
1809 }
1810 -* {
1811 knerror "Invalid option '$arg'"
1812 }
1813 default {
1814 set shell $arg
1815 # end option parsing: remaining elts are allowed values
1816 break
1817 }
1818 }
1819 set prevarg $arg
1820 }
1821 }
1822
1823 if {[info exists nextargisval]} {
1824 knerror "Missing value for '$prevarg' option"
1825 }
1826
1827 if {![info exists shell] || $i == [llength $args]} {
1828 knerror "wrong # args: should be \"source-sh ?--ignore? ?eltlist? shell\
1829 script ?arg ...?\""
1830 }
1831
1832 set script_args [lassign [lrange $args $i end] script]
1833
1834 if {[info exists ignore_opt_raw]} {
1835 set elt_ignored_list [split $ignore_opt_raw :]
1836 set allowed_elt_ignored_list {envvar function alias chdir complete}
1837 foreach elt_ignored $elt_ignored_list {
1838 if {$elt_ignored ni $allowed_elt_ignored_list} {
1839 knerror "Invalid ignored element '$elt_ignored'"
1840 }
1841 }
1842 }
1843
1844 return [list $elt_ignored_list $shell $script $script_args]
1845 }
1846
1847 proc source-sh {args} {
1848 lassign [parseSourceShArgs {*}$args] elt_ignored_list shell script\
1849 script_args
1850 # evaluate script and get the environment changes it performs translated
1851 # into modulefile commands
1852 set shtomodargs [list $shell $script {*}$script_args]
1853 set modcontent [sh-to-mod $elt_ignored_list {*}$shtomodargs]
1854
1855 # register resulting modulefile commands
1856 setLoadedSourceSh [currentState modulename] [list $shtomodargs\
1857 {*}$modcontent]
1858
1859 # get name of current module Tcl interp
1860 set itrp [getCurrentModfileInterpName]
1861
1862 # evaluate resulting modulefile commands through current Tcl interp
1863 foreach modcmd $modcontent {
1864 interp eval $itrp $modcmd
1865 }
1866 }
1867
1868 # undo source-sh in unload mode
1869 proc source-sh-un {args} {
1870 lassign [parseSourceShArgs {*}$args] elt_ignored_list shell script\
1871 script_args
1872 set shtomodargs [list $shell $script {*}$script_args]
1873 # find commands resulting from source-sh evaluation recorded in env
1874 set modcontent [getLoadedSourceShScriptContent [currentState modulename]\
1875 $shtomodargs]
1876
1877 # get name of current module unload Tcl interp
1878 set itrp [getCurrentModfileInterpName]
1879
1880 # evaluate each recorded command in unload Tcl interp to get them reversed
1881 foreach modcmd $modcontent {
1882 interp eval $itrp $modcmd
1883 }
1884 }
1885
1886 # report underlying modulefile cmds in display mode
1887 proc source-sh-di {args} {
1888 lassign [parseSourceShArgs {*}$args] elt_ignored_list shell script\
1889 script_args
1890 set shtomodargs [list $shell $script {*}$script_args]
1891
1892 # if module loaded, get as much content from environment as possible
1893 if {[is-loaded [currentState modulename]]} {
1894 # find commands resulting from source-sh evaluation recorded in env
1895 set reccontent [getLoadedSourceShScriptContent [currentState\
1896 modulename] $shtomodargs]
1897
1898 # need to evaluate script to get alias/function/complete definition
1899 execShAndGetEnv $elt_ignored_list {*}$shtomodargs
1900
1901 set modcontent {}
1902 foreach cmd $reccontent {
1903 # build modulefile content to show with recorded elements in env and
1904 # alias/function/complete definition obtained by reevaluating script
1905 switch -- [lindex $cmd 0] {
1906 complete {
1907 set cpname [lindex $cmd 2]
1908 if {[info exists compaft($cpname)]} {
1909 set cpbodylist $compaft($cpname)
1910 } else {
1911 set cpbodylist [list {}]
1912 }
1913 foreach cpbody $cpbodylist {
1914 lappend modcontent [list complete $shell $cpname $cpbody]
1915 }
1916 }
1917 set-alias {
1918 set alname [lindex $cmd 1]
1919 if {[info exists aliasaft($alname)]} {
1920 set albody $aliasaft($alname)
1921 } else {
1922 set albody {}
1923 }
1924 lappend modcontent [list set-alias $alname $albody]
1925 }
1926 set-function {
1927 set fnname [lindex $cmd 1]
1928 if {[info exists funcaft($fnname)]} {
1929 set fnbody \n$funcaft($fnname)
1930 } else {
1931 set fnbody {}
1932 }
1933 lappend modcontent [list set-function $fnname $fnbody]
1934 }
1935 default {
1936 lappend modcontent $cmd
1937 }
1938 }
1939 }
1940 # not loaded, so get full content from script evaluation
1941 } else {
1942 set modcontent [sh-to-mod $elt_ignored_list {*}$shtomodargs]
1943 }
1944
1945 # get name of current module unload Tcl interp
1946 set itrp [getCurrentModfileInterpName]
1947
1948 # evaluate each recorded command in display Tcl interp to get them printed
1949 foreach modcmd $modcontent {
1950 interp eval $itrp $modcmd
1951 }
1952 }
1953
1954 proc isVariantNameValid {name} {
1955 return [expr {![string is digit -strict $name] && [regexp\
1956 {^[A-Za-z0-9_][A-Za-z0-9_-]*$} $name]}]
1957 }
1958
1959 # parse arguments set on a variant modulefile command
1960 proc parseVariantCommandArgs {args} {
1961 set dflvalue {}
1962 set defdflvalue 0
1963 set isboolean 0
1964 set i 0
1965 foreach arg $args {
1966 incr i
1967 if {[info exists nextargisval]} {
1968 ##nagelfar vartype nextargisval varName
1969 set $nextargisval $arg
1970 unset nextargisval
1971 } else {
1972 switch -glob -- $arg {
1973 --default {
1974 ##nagelfar ignore Found constant
1975 set nextargisval dflvalue
1976 set defdflvalue 1
1977 }
1978 --boolean {
1979 set isboolean 1
1980 }
1981 -* {
1982 knerror "Invalid option '$arg'"
1983 }
1984 default {
1985 set name $arg
1986 # end option parsing: remaining elts are allowed values
1987 break
1988 }
1989 }
1990 set prevarg $arg
1991 }
1992 }
1993
1994 if {[info exists nextargisval]} {
1995 knerror "Missing value for '$prevarg' option"
1996 }
1997
1998 # check variant name and allowed values
1999 if {![info exists name]} {
2000 knerror {No variant name specified}
2001 }
2002 if {![isVariantNameValid $name]} {
2003 knerror "Invalid variant name '$name'"
2004 }
2005 set values [lrange $args $i end]
2006 if {$isboolean} {
2007 if {[llength $values]} {
2008 knerror "No value should be defined for boolean variant '$name'"
2009 } else {
2010 set values {1 0 yes no true false on off}
2011 }
2012 } else {
2013 foreach val $values {
2014 if {[string is boolean -strict $val] && ![string is integer\
2015 -strict $val]} {
2016 knerror "Boolean value defined on non-boolean variant '$name'"
2017 }
2018 }
2019 }
2020 if {$defdflvalue && $isboolean} {
2021 # default value should be bool if variant is boolean
2022 if {![string is boolean -strict $dflvalue]} {
2023 knerror "Boolean value is expected as default value for variant\
2024 '$name'"
2025 # translate default value in boolean canonical form (0 or 1)
2026 } else {
2027 set dflvalue [string is true -strict $dflvalue]
2028 }
2029 }
2030
2031 return [list $name $values $defdflvalue $dflvalue $isboolean]
2032 }
2033
2034 proc variant {itrp args} {
2035 # parse args
2036 lassign [parseVariantCommandArgs {*}$args] name values defdflvalue\
2037 dflvalue isboolean
2038
2039 # version variant is forbidden until specific implementation
2040 if {$name eq {version}} {
2041 knerror "'version' is a restricted variant name" MODULES_ERR_GLOBAL
2042 }
2043
2044 # get variant list defined on command line
2045 set vrlist [getVariantListFromVersSpec [currentState modulenamevr]]
2046
2047 # search for variant specification (most right-positionned value wins)
2048 for {set i [expr {[llength $vrlist]-1}]} {$i >= 0} {incr i -1} {
2049 lassign [lindex $vrlist $i] vrname vrnot vrisbool vrvalue
2050 if {$vrname eq $name} {
2051 # translate value in boolean canonical form (0/1) if variant is bool
2052 if {$isboolean && [string is boolean -strict $vrvalue]} {
2053 set value [string is true -strict $vrvalue]
2054 } else {
2055 set value $vrvalue
2056 }
2057 set isdflval [expr {$defdflvalue && $dflvalue eq $value}]
2058 break
2059 }
2060 }
2061
2062 # error if variant has not been specified unless a default is defined
2063 if {![info exists isdflval]} {
2064 if {$defdflvalue} {
2065 set value $dflvalue
2066 # 2 means default value automatically set
2067 set isdflval 2
2068 # no error if variant is undefined on display mode, return here not to
2069 # set any variant-specific variable
2070 } elseif {[currentState mode] eq {display}} {
2071 return
2072 } else {
2073 set allowedmsg [expr {![llength $values] ? {} : "\nAllowed values\
2074 are: $values"}]
2075 knerror "No value specified for variant '$name'$allowedmsg"\
2076 MODULES_ERR_GLOBAL
2077 }
2078 }
2079
2080 # check defined value
2081 if {($isboolean && ![string is boolean -strict $value]) || (!$isboolean &&\
2082 [llength $values] && $value ni $values)} {
2083 # invalid value error is not a modulefile error
2084 knerror "Invalid value '$value' for variant '$name'\nAllowed values\
2085 are: $values" MODULES_ERR_GLOBAL
2086 } else {
2087 # instantiate variant in modulefile context
2088 reportDebug "Set variant on $itrp: ModuleVariant($name) = '$value'"
2089 $itrp eval set "{::ModuleVariant($name)}" "{$value}"
2090 # after modfile interp ModuleVariant is unset by resetInterpState
2091
2092 # record variant for persistency (name value is-boolean is-default)
2093 # unless module is currently unloading
2094 if {[currentState mode] ne {unload}} {
2095 setLoadedVariant [currentState modulename] [list $name $value\
2096 $isboolean $isdflval]
2097 }
2098 }
2099 }
2100
2101 # optimized variant command for whatis mode: init entry in ModuleVariant array
2102 # to avoid variable being undefined when accessed during modulefile evaluation
2103 proc variant-wh {itrp args} {
2104 # parse args
2105 lassign [parseVariantCommandArgs {*}$args] name values defdflvalue\
2106 dflvalue isboolean
2107
2108 # instantiate variant in modulefile context to an empty value
2109 reportDebug "Set variant on $itrp: ModuleVariant($name) = ''"
2110 $itrp eval set "{::ModuleVariant($name)}" "{}"
2111 }
2112
2113 proc getvariant {itrp args} {
2114 # parse args
2115 lassign [parseGetenvCommandArgs getvariant {*}$args] name valifundef\
2116 returnval
2117
2118 if {[currentState mode] ne {display} || $returnval} {
2119 if {[$itrp eval info exists "{::ModuleVariant($name)}"]} {
2120 return [$itrp eval set "{::ModuleVariant($name)}"]
2121 } else {
2122 return $valifundef
2123 }
2124 } else {
2125 return [sgr va "{$name}"]
2126 }
2127 }
2128
2129 proc require-fullname {} {
2130 # test specified name is any alternative name of currently evaluating mod
2131 # expect the default and parent dir name (which are considered unqualified)
2132 if {![modEq [currentState specifiedname] [currentState modulename] eqspec\
2133 1 4]} {
2134 knerror {Module version must be specified to load module}\
2135 MODULES_ERR_GLOBAL
2136 }
2137 }
2138
2139 proc prereqAllModfileCmd {tryload auto args} {
2140 lassign [parsePrereqCommandArgs prereq-all {*}$args] tag_list\
2141 modulepath_list optional opt_list args
2142 # call prereq over each arg independently to emulate a prereq-all
2143 foreach arg $args {
2144 prereqAnyModfileCmd $tryload $auto {*}$opt_list $arg
2145 }
2146 }
2147
2148 proc always-load {args} {
2149 lassign [parsePrereqCommandArgs always-load {*}$args] tag_list\
2150 modulepath_list optional opt_list args
2151 # append keep-loaded tag to the list, second tag list in opt_list will take
2152 # over the initial list defined
2153 lappend tag_list keep-loaded
2154 lappend opt_list --tag [join $tag_list :]
2155
2156 # auto load is inhibited if currently in DepRe context
2157 set auto [expr {[currentModuleEvalContext] eq {depre} ? {0} : {1}}]
2158
2159 # load all module specified
2160 prereqAllModfileCmd 0 $auto {*}$opt_list {*}$args
2161 }
2162
2163 proc family {name} {
2164 # ensure name is valid to be part of the name of an environment variable
2165 if {![string length $name] || ![regexp {^[A-Za-z0-9_]*$} $name]} {
2166 knerror "Invalid family name '$name'"
2167 }
2168
2169 # only one loaded module could provide a given family
2170 conflict $name
2171 # set name as an alias for currently loading module
2172 setLoadedAltname [currentState modulename] [list al $name]
2173
2174 # set variable in environment to know what module name provides family
2175 set upname [string toupper $name]
2176 lassign [getModuleNameVersion] mod modname modversion
2177 if {$modname eq {.}} {
2178 set modname [currentState modulename]
2179 }
2180 setenv MODULES_FAMILY_$upname $modname
2181 # also set Lmod-specific variable for compatibility
2182 setenv LMOD_FAMILY_$upname $modname
2183 }
2184
2185 proc family-un {name} {
2186 # ensure name is valid to be part of the name of an environment variable
2187 if {![string length $name] || ![regexp {^[A-Za-z0-9_]*$} $name]} {
2188 knerror "Invalid family name '$name'"
2189 }
2190
2191 # unset family-related environment variable
2192 set upname [string toupper $name]
2193 unsetenv MODULES_FAMILY_$upname
2194 unsetenv LMOD_FAMILY_$upname
2195 }
2196
2197 proc complete {shell name body} {
2198 if {![string length $name]} {
2199 knerror "Invalid command name '$name'"
2200 }
2201 # append definition retaining for which shell they are made
2202 # also some shells may set multiple definitions for a single name
2203 lappend ::g_Completes($name) $shell $body
2204 set ::g_stateCompletes($name) new
2205
2206 # current module is qualified for refresh evaluation
2207 lappendState -nodup refresh_qualified [currentState modulename]
2208 }
2209
2210 # undo complete in unload mode
2211 proc complete-un {shell name body} {
2212 return [uncomplete $name]
2213 }
2214
2215 proc uncomplete {name} {
2216 if {![string length $name]} {
2217 knerror "Invalid command name '$name'"
2218 }
2219 set ::g_Completes($name) {}
2220 set ::g_stateCompletes($name) del
2221 }
2222
2223 proc pushenv {var val} {
2224 # save initial value in pushenv value stack
2225 set pushvar [getPushenvVarName $var]
2226 if {![isEnvVarDefined $pushvar] && [isEnvVarDefined $var]} {
2227 prepend-path $pushvar &$::env($var)
2228 }
2229
2230 # clean any previously defined reference counter array
2231 unset-env [getModshareVarName $var] 1
2232
2233 # Set the variable for later use during the modulefile evaluation
2234 set-env $var $val
2235
2236 # add this value to the stack associated to current module name in order to
2237 # know what element to remove from stack when unloading
2238 prepend-path $pushvar [currentState modulename]&$val
2239
2240 # indicate env var name to configured traces
2241 setState current_envvar $var
2242
2243 return {}
2244 }
2245
2246 # undo pushenv in unload mode
2247 proc pushenv-un {var val} {
2248 # clean any existing reference counter array
2249 unset-env [getModshareVarName $var] 1
2250
2251 # update value stack
2252 set pushvar [getPushenvVarName $var]
2253 if {[isEnvVarDefined $pushvar]} {
2254 set pushlist [split $::env($pushvar) :]
2255 # find value pushed by currently evaluated module and remove it
2256 set popidx [lsearch -exact $pushlist [currentState modulename]&$val]
2257 if {$popidx != -1} {
2258 set pushlist [lreplace $pushlist $popidx $popidx]
2259 remove-path --index $pushvar $popidx
2260 }
2261
2262 if {[llength $pushlist]} {
2263 # fetch value on top of the stack
2264 set validx [expr {[string first & [lindex $pushlist 0]] + 1}]
2265 set popval [string range [lindex $pushlist 0] $validx end]
2266
2267 # restore top value if different from current one
2268 if {![envVarEquals $var $popval]} {
2269 set-env $var $popval
2270 }
2271
2272 # if last element remaining in stack is the initial value prior first
2273 # pushenv, then clear the stack totally
2274 if {$validx == 1} {
2275 remove-path --index $pushvar 0
2276 }
2277 } else {
2278 unset-env $var 0 $val
2279 }
2280 } else {
2281 # Add variable to the list of variable to unset in shell output code but
2282 # set it in interp context as done on load mode for later use during the
2283 # modulefile evaluation
2284 unset-env $var 0 $val
2285 }
2286
2287 # indicate env var name to configured traces
2288 setState current_envvar $var
2289
2290 return {}
2291 }
2292
2293 # optimized pushenv for whatis mode (same approach than setenv-wh)
2294 proc pushenv-wh {var val} {
2295 # indicate env var name to configured traces
2296 setState current_envvar $var
2297
2298 setEnvVarIfUndefined $var {}
2299 return {}
2300 }
2301
2302 proc modulepath-label {modpath label} {
2303 set modpath [getAbsolutePath $modpath]
2304 set ::g_modulepathLabel($modpath) $label
2305 reportDebug "modpath=$modpath, label='$label'"
2306 }
2307
2308 # translate a gitignore-style pattern into its matching properties: negation
2309 # flag, directory-only flag and a regular expression to apply on file paths
2310 # relative to the pattern anchor directory. empty result if pattern is void
2311 proc compileIgnorePattern {pattern} {
2312 set negated 0
2313 if {[string index $pattern 0] eq {!}} {
2314 set negated 1
2315 set pattern [string range $pattern 1 end]
2316 } elseif {[string equal -length 2 $pattern {\!}]} {
2317 # backslash-escaped leading '!' is matched literally
2318 set pattern [string range $pattern 1 end]
2319 }
2320 set dironly 0
2321 if {[string index $pattern end] eq {/}} {
2322 set dironly 1
2323 set pattern [string range $pattern 0 end-1]
2324 }
2325 # a slash at pattern start or middle anchors it to the directory of the
2326 # rc file defining it, otherwise it matches at any depth below
2327 set anchored [expr {[string first / $pattern] != -1}]
2328 set pattern [string trimleft $pattern /]
2329 set plen [string length $pattern]
2330 if {$plen == 0} {
2331 return {}
2332 }
2333
2334 set re {}
2335 for {set i 0} {$i < $plen} {incr i} {
2336 set c [string index $pattern $i]
2337 switch -- $c {
2338 * {
2339 set seg_start [expr {$i == 0 || [string index $pattern [expr {$i\
2340 - 1}]] eq {/}}]
2341 if {[string index $pattern [expr {$i + 1}]] eq {*}} {
2342 set next2 [string index $pattern [expr {$i + 2}]]
2343 if {$seg_start && $next2 eq {/}} {
2344 # leading '**/' matches zero or more directories
2345 append re {(?:[^/]+/)*}
2346 incr i 2
2347 } elseif {$seg_start && $next2 eq {}} {
2348 # trailing '**' matches everything inside
2349 append re .*
2350 incr i 1
2351 } else {
2352 # consecutive asterisks elsewhere act as a regular one
2353 append re {[^/]*}
2354 incr i 1
2355 }
2356 } else {
2357 append re {[^/]*}
2358 }
2359 }
2360 ? {
2361 append re {[^/]}
2362 }
2363 [ {
2364 # copy character range, translating '!' negation prefix ('[' is
2365 # matched literally if range is not closed, like git does)
2366 set skip [expr {[string index $pattern [expr {$i + 1}]] eq {!} ?\
2367 3 : 2}]
2368 set j [string first {]} $pattern [expr {$i + $skip}]]
2369 if {$j == -1} {
2370 append re {\[}
2371 } else {
2372 set range [string range $pattern [expr {$i + 1}] [expr {$j -\
2373 1}]]
2374 if {[string index $range 0] eq {!}} {
2375 set range ^[string range $range 1 end]
2376 }
2377 append re \[$range\]
2378 set i $j
2379 }
2380 }
2381 default {
2382 if {$c eq "\\"} {
2383 # backslash escapes next character which is matched literally
2384 # (a trailing backslash is matched literally)
2385 incr i
2386 if {$i < $plen} {
2387 set c [string index $pattern $i]
2388 }
2389 }
2390 if {[string first $c {\^$.|?*+()[]{}}] != -1} {
2391 append re \\
2392 }
2393 append re $c
2394 }
2395 }
2396 }
2397
2398 # pattern without slash matches element name at any depth
2399 if {$anchored} {
2400 set re ^$re\$
2401 } else {
2402 set re (?:^|/)$re\$
2403 }
2404 return [list $negated $dironly $re]
2405 }
2406
2407 # register gitignore-style patterns describing modulepath content to ignore
2408 # when searching for modulefiles
2409 proc modulepath-ignore {args} {
2410 if {![llength $args]} {
2411 knerror {No pattern specified in argument}
2412 }
2413 # global and user rc files define global patterns applying to every
2414 # modulepath, rc files within a modulepath anchor patterns to their
2415 # directory
2416 if {[isStateDefined rc_running]} {
2417 set anchor {}
2418 } else {
2419 set rcfile [currentState modulefile]
2420 if {[file tail $rcfile] ni {.modulerc .version}} {
2421 knerror {modulepath-ignore command not allowed in modulefile}
2422 }
2423 set anchor [file dirname $rcfile]
2424 }
2425 foreach pattern $args {
2426 set props [compileIgnorePattern $pattern]
2427 # void pattern does not match anything
2428 if {[llength $props]} {
2429 lappend ::g_pathIgnorePatterns [list $anchor {*}$props]
2430 }
2431 }
2432 reportDebug "anchor='$anchor', patterns='$args'"
2433 }
2434
2435 proc unique-name-conflict {} {
2436 # skip if unique_name_loaded configuration is disabled
2437 if {![getConf unique_name_loaded]} {
2438 return
2439 }
2440
2441 # get root name of all names (actual and alternatives) of currently
2442 # evaluating module
2443 set root_name_list [list]
2444 set mod [currentState modulename]
2445 foreach name [list $mod {*}[getAllModuleResolvedName $mod]] {
2446 lappendNoDup root_name_list [lindex [file split $name] 0]
2447 }
2448
2449 # declare conflict over all these names
2450 conflict {*}$root_name_list
2451 }
2452
2453 proc sourceModfileCmd {itrp args} {
2454 # argument parsing: catch encoding arg but ignore it
2455 switch -- [llength $args] {
2456 1 {}
2457 3 {
2458 set option [lindex $args 0]
2459 if {$option ne {-encoding}} {
2460 knerror "Invalid option '$option'"
2461 }
2462 }
2463 default {
2464 knerror {wrong # args: should be "source ?-encoding? ?encodingName?\
2465 fileName"}
2466 }
2467 }
2468 set filename [lindex $args end]
2469
2470 if {![info exists ::source_cache($filename)]} {
2471 set ::source_cache($filename) [readFile $filename]
2472 }
2473
2474 interp eval $itrp info script $filename
2475 interp eval $itrp $::source_cache($filename)
2476 interp eval $itrp info script [currentState modulefile]
2477 }
2478
2479 proc lsb-release {what} {
2480 return [switch -- $what {
2481 id {getState lsb_id}
2482 release {getState lsb_release}
2483 codename {getState lsb_codename}
2484 default {knerror "lsb-release $what not supported"}
2485 }]
2486 }
2487
2488 proc registerCurrentModuleUse {args} {
2489 if {[string length [currentState modulename]]} {
2490 setLoadedUse [currentState modulename] {*}$args
2491 }
2492 }
2493
2494 proc module-help {args} {
2495 lappend ::g_help_lines [join $args]
2496 }
2497
2498 proc getModuleHelpLines {} {
2499 if {[info exists ::g_help_lines]} {
2500 return $::g_help_lines
2501 }
2502 }
2503
2504 # convert property value as module tag (property name is ignored)
2505 proc add-property {name value} {
2506 set tag_list [split $value :]
2507 set mod [currentState modulename]
2508 foreach tag $tag_list {
2509 module-tag $tag $mod
2510 }
2511 }
2512
2513 proc module-warn {args} {
2514 # parse application criteria arguments to determine if command apply
2515 lassign [parseApplicationCriteriaArgs 1 0 {*}$args] apply isnearly after\
2516 otherargs
2517
2518 # parse remaining argument list, do it even if command does not apply to
2519 # raise any command specification error
2520 foreach arg $otherargs {
2521 if {[info exists nextargisval]} {
2522 ##nagelfar vartype nextargisval varName
2523 set $nextargisval $arg
2524 unset nextargisval
2525 } else {
2526 switch -glob -- $arg {
2527 --message {
2528 set nextargisval message
2529 }
2530 -* {
2531 knerror "Invalid option '$arg'"
2532 }
2533 default {
2534 lappend modarglist $arg
2535 }
2536 }
2537 set prevarg $arg
2538 }
2539 }
2540
2541 if {[info exists nextargisval]} {
2542 knerror "Missing value for '$prevarg' option"
2543 }
2544 if {![info exists message]} {
2545 knerror {No message specified in argument}
2546 }
2547 if {![info exists modarglist]} {
2548 knerror {No module specified in argument}
2549 }
2550
2551 # skip tag record if application criteria are not met
2552 if {$apply} {
2553 ##nagelfar ignore Found constant
2554 set proplist [list message $message]
2555 # record each hide spec after parsing them
2556 foreach modarg [parseModuleSpecification 0 0 0 0 {*}$modarglist] {
2557 setModspecTag $modarg warning $proplist
2558 }
2559 }
2560 }
2561
2562 proc extensions {args} {
2563 if {![llength $args]} {
2564 knerror {No module specified in argument}
2565 }
2566 # skip alias definition for extensions cmd if info_extension is enabled
2567 if {[getConf info_extension]} {
2568 return
2569 }
2570 provide {*}$args
2571 }
2572
2573 proc provide {args} {
2574 if {![llength $args]} {
2575 knerror {No module specified in argument}
2576 }
2577 set current_mod [currentState modulename]
2578 foreach alias $args {
2579 setLoadedAltname $current_mod [list al $alias]
2580 }
2581 }
2582
2583 proc module {command args} {
2584 # resolve and check command name
2585 lassign [parseModuleCommandName $command help] command cmdvalid cmdempty
2586 # clear other args if no command name supplied
2587 if {$cmdempty} {
2588 set args {}
2589 }
2590 # raise error if supplied command is not known
2591 if {!$cmdvalid} {
2592 knerrorModule 0 "Invalid command '$command'"
2593 }
2594
2595 # define states needed by module spec parsing and sub-command processing
2596 # define if modfile should always be fully read even for validity check
2597 lappendState always_read_full_file [expr {$command ni [list path paths\
2598 list avail aliases edit spider]}]
2599 lappendState commandname $command
2600
2601 # parse options, do that globally to ignore options not related to a given
2602 # module sub-command (exclude them from arg list)
2603 lassign [parseModuleCommandArgs 0 $command 0 0 {*}$args] show_oneperline\
2604 show_mtime show_filter search_filter search_match dump_state\
2605 addpath_pos not_req tag_list parsed_args
2606
2607 # some commands can only be called from top level, not within modulefile
2608 switch -- $command {
2609 path - paths - autoinit - help - prepend-path - append-path -\
2610 remove-path - is-loaded - is-saved - is-used - is-avail -\
2611 info-loaded - clear - sh-to-mod - edit - refresh - source - state -\
2612 lint - mod-to-sh - reset - stash - stashpop - stashrm - stashshow -\
2613 stashclear - stashlist - cachebuild - cacheclear - spider {
2614 knerrorModule 0 "Command '$command' not supported"
2615 }
2616 }
2617 # other commands can only be called from modulefile evaluated from
2618 # command acting as top-level context (source and autoinit)
2619 if {([depthState modulename] > 1 || [aboveCommandName] ni [list source\
2620 autoinit]) && $command eq {config}} {
2621 knerrorModule 0 "Command '$command' not supported"
2622 }
2623 # no requirement should be recorded this module load/unload/switch cmd
2624 if {$not_req || ![getConf implicit_requirement]} {
2625 lappendState inhibit_req_record [currentState evalid]
2626 }
2627
2628 checkModuleCommandNbArgs 0 $command [llength $parsed_args]
2629
2630 {*}[formatModuleCommand 0 $command [currentState mode] $tag_list\
2631 $addpath_pos $show_oneperline $show_mtime $show_filter $search_filter\
2632 $search_match $dump_state $parsed_args]
2633
2634 lpopState commandname
2635 lpopState always_read_full_file
2636
2637 if {$not_req || ![getConf implicit_requirement]} {
2638 lpopState inhibit_req_record
2639 }
2640
2641 return {}
2642 }
2643
2644 # supersede append command to sync environment variable in modulefile eval
2645 # sub-interpreter. use "set" Tcl command to use the Tcl-internal sync trigger.
2646 proc appendModfileCmd {itrp var_name args} {
2647 # set a variable if passed var_name is an env variable
2648 if {[string range $var_name 0 3] eq {env(}} {
2649 set env_var_name ::$var_name
2650 } elseif {[string range $var_name 0 5] eq {::env(}} {
2651 set env_var_name $var_name
2652 }
2653 ##nagelfar vartype env_var_name varName
2654 if {[info exists env_var_name] && [info exists $env_var_name]} {
2655 set value [set $env_var_name][join $args {}]
2656 set cmd_op_list [list set $var_name $value]
2657 } else {
2658 set cmd_op_list [list _append $var_name {*}$args]
2659 }
2660 interp eval $itrp $cmd_op_list
2661 }
2662
2663 # ;;; Local Variables:
2664 # ;;; Mode: tcl-mode
2665 # ;;; tcl-indent-level: 3
2666 # ;;; tcl-continued-indent-level: 3
2667 # ;;; indent-tabs-mode: nil
2668 # ;;; End:
2669 # vim:set tabstop=3 shiftwidth=3 expandtab autoindent: