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-2025 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 if {$bhv eq {set}} {
582 # clean any previously defined reference counter array
583 unset-env [getModshareVarName $var] 1
584
585 # clean any previously defined pushenv stack
586 unset-env [getPushenvVarName $var] 1
587
588 # Set the variable for later use during the modulefile evaluation
589 set-env $var $val
590 }
591
592 return {}
593 }
594
595 # undo setenv in unload mode
596 proc setenv-un {args} {
597 lassign [parseSetenvCommandArgs unload unset {*}$args] bhv var val
598
599 # clean any existing reference counter array
600 unset-env [getModshareVarName $var] 1
601
602 # clean any previously defined pushenv stack
603 unset-env [getPushenvVarName $var] 1
604
605 # Add variable to the list of variable to unset in shell output code but
606 # set it in interp context as done on load mode for later use during the
607 # modulefile evaluation
608 unset-env $var 0 $val
609
610 return {}
611 }
612
613 # optimized setenv for whatis mode: init env variable with an empty
614 # value if undefined. do not care about value, just avoid variable to be
615 # undefined for later use during the modulefile evaluation
616 proc setenv-wh {args} {
617 lassign [parseSetenvCommandArgs load set {*}$args] bhv var val
618
619 setEnvVarIfUndefined $var {}
620 return {}
621 }
622
623 # parse arguments sent to the getenv modulefile command
624 proc parseGetenvCommandArgs {cmd args} {
625 set returnval 0
626 set valifundef {}
627 switch -- [llength $args] {
628 1 {
629 set var [lindex $args 0]
630 }
631 2 {
632 switch -- [lindex $args 0] {
633 --return-value {
634 set returnval 1
635 set var [lindex $args 1]
636 }
637 default {
638 set var [lindex $args 0]
639 set valifundef [lindex $args 1]
640 }
641 }
642 }
643 3 {
644 if {[lindex $args 0] ne {--return-value}} {
645 set wrongargs 1
646 } else {
647 set returnval 1
648 set var [lindex $args 1]
649 set valifundef [lindex $args 2]
650 }
651 }
652 default {
653 set wrongargs 1
654 }
655 }
656
657 set argname [expr {$cmd eq {getenv} ? {variable} : {name}}]
658 if {[info exists wrongargs]} {
659 knerror "wrong # args: should be \"$cmd ?--return-value? $argname\
660 ?valifundef?\""
661 }
662
663 reportDebug "$argname='$var', valifundef='$valifundef',\
664 returnval='$returnval'"
665 return [list $var $valifundef $returnval]
666 }
667
668 proc getenv {args} {
669 # parse args
670 lassign [parseGetenvCommandArgs getenv {*}$args] var valifundef returnval
671
672 if {[currentState mode] ne {display} || $returnval} {
673 return [get-env $var $valifundef]
674 } else {
675 return "\$$var"
676 }
677 }
678
679 # parse arguments sent to the unsetenv modulefile command
680 proc parseUnsetenvCommandArgs {mode dflbhv args} {
681 foreach arg $args {
682 switch -- $arg {
683 --unset-on-unload {
684 if {$mode eq {unload}} {
685 set bhv unset
686 }
687 }
688 --noop-on-unload {
689 if {$mode eq {unload}} {
690 set bhv noop
691 }
692 }
693 default {
694 if {![info exists var]} {
695 set var $arg
696 } elseif {![info exists val]} {
697 set val $arg
698 if {$mode eq {unload} && ![info exists bhv]} {
699 set bhv set
700 }
701 } else {
702 # too much argument
703 set wrongargnum 1
704 }
705 }
706 }
707 }
708
709 if {[info exists wrongargnum] || ![info exists var]} {
710 knerror {wrong # args: should be "unsetenv ?--noop-on-unload?\
711 ?--unset-on-unload? var ?val?"}
712 }
713
714 if {![info exists bhv]} {
715 set bhv $dflbhv
716 }
717
718 # initialize val to always return same structure, val is only used if bhv
719 # equals 'set'
720 if {![info exists val]} {
721 set val {}
722 }
723
724 reportDebug "bhv=$bhv, var=$var, val=$val"
725 return [list $bhv $var $val]
726 }
727
728 proc unsetenv {args} {
729 lassign [parseUnsetenvCommandArgs load unset {*}$args] bhv var val
730
731 # clean any existing reference counter array
732 unset-env [getModshareVarName $var] 1
733
734 # clean any previously defined pushenv stack
735 unset-env [getPushenvVarName $var] 1
736
737 # Set the variable for later use during the modulefile evaluation
738 unset-env $var
739
740 return {}
741 }
742
743 # undo unsetenv in unload mode
744 proc unsetenv-un {args} {
745 lassign [parseUnsetenvCommandArgs unload noop {*}$args] bhv var val
746
747 switch -- $bhv {
748 set {
749 # apply value specified for set on unload
750 return [setenv $var $val]
751 }
752 unset {
753 return [unsetenv $var]
754 }
755 noop {
756 # otherwise just clear variable if it does not exist on unload mode
757 # for later use during the modulefile evaluation
758 if {![isEnvVarDefined $var]} {
759 reset-to-unset-env $var
760 }
761 }
762 }
763 return {}
764 }
765
766 # optimized unsetenv for whatis mode: init env variable with an empty
767 # value if undefined. do not care about value, just avoid variable to be
768 # undefined for later use during the modulefile evaluation
769 proc unsetenv-wh {args} {
770 lassign [parseUnsetenvCommandArgs load noop {*}$args] bhv var val
771
772 setEnvVarIfUndefined $var {}
773 return {}
774 }
775
776 proc chdir {dir} {
777 if {[file exists $dir] && [file isdirectory $dir]} {
778 set ::g_changeDir $dir
779 } else {
780 # report issue but does not treat it as an error to have the
781 # same behavior as C-version
782 reportWarning "Cannot chdir to '$dir' for '[currentState modulename]'"
783 }
784
785 return {}
786 }
787
788 # supersede exit command to handle it if called within a modulefile
789 # rather than exiting the whole process
790 proc exitModfileCmd {{code 0}} {
791 if {[currentState mode] in {load refresh}} {
792 setState inhibit_interp 1
793 }
794
795 # break to gently end interpretation of current modulefile
796 return -code break
797 }
798
799 # enables sub interp to return ModulesVersion value to the main interp
800 proc setModulesVersion {val} {
801 set ::ModulesVersion $val
802 }
803
804 # supersede puts command to catch content sent to stdout/stderr within
805 # modulefile in order to correctly send stderr content (if a pager has been
806 # enabled) or postpone content channel send after rendering on stdout the
807 # relative environment changes required by the modulefile
808 proc putsModfileCmd {itrp args} {
809 # determine if puts call targets the stdout or stderr channel
810 switch -- [llength $args] {
811 1 {
812 # create struct with newline status and message to output
813 set deferPuts [list 1 [lindex $args 0]]
814 }
815 2 {
816 switch -- [lindex $args 0] {
817 -nonewline {
818 set deferPuts [list 0 [lindex $args 1]]
819 }
820 stdout {
821 set deferPuts [list 1 [lindex $args 1]]
822 }
823 prestdout {
824 set deferPrePuts [list 1 [lindex $args 1]]
825 }
826 stderr {
827 set reportArgs [list [lindex $args 1]]
828 }
829 log {
830 set logPuts [lindex $args 1]
831 }
832 }
833 }
834 3 {
835 if {[lindex $args 0] eq {-nonewline}} {
836 switch -- [lindex $args 1] {
837 stdout {
838 set deferPuts [list 0 [lindex $args 2]]
839 }
840 prestdout {
841 set deferPrePuts [list 0 [lindex $args 2]]
842 }
843 stderr {
844 set reportArgs [list [lindex $args 2] 1]
845 }
846 log {
847 set logPuts [lindex $args 2]
848 }
849 }
850 } else {
851 set wrongNumArgs 1
852 }
853 }
854 default {
855 set wrongNumArgs 1
856 }
857 }
858
859 # raise error if bad argument number detected, do this here rather in _puts
860 # not to confuse people with an error reported by an internal name (_puts)
861 if {[info exists wrongNumArgs]} {
862 knerror {wrong # args: should be "puts ?-nonewline? ?channelId? string"}
863 # send content to log system
864 } elseif {[info exists logPuts]} {
865 log $logPuts
866 # defer puts if it targets stdout (see renderSettings)
867 } elseif {[info exists deferPuts]} {
868 # current module is qualified for refresh evaluation
869 lappendState -nodup refresh_qualified [currentState modulename]
870 lappend ::g_stdoutPuts {*}$deferPuts
871 } elseif {[info exists deferPrePuts]} {
872 lappendState -nodup refresh_qualified [currentState modulename]
873 lappend ::g_prestdoutPuts {*}$deferPrePuts
874 # if it targets stderr call report, which knows what channel to use
875 } elseif {[info exists reportArgs]} {
876 # report message only if not silent
877 if {[isVerbosityLevel concise]} {
878 report {*}$reportArgs
879 }
880 # pass to real puts command if not related to stdout and do that in modfile
881 # interpreter context to get access to eventual specific channel
882 } else {
883 # re-throw error as a known error for accurate stack trace print
884 if {[catch {$itrp eval _puts $args} errMsg]} {
885 knerror $errMsg MODULES_ERR_CUSTOM
886 }
887 }
888 }
889
890 proc prepend-path {args} {
891 # Set the variable for later use during the modulefile evaluation
892 add-path prepend-path load prepend {*}$args
893
894 return {}
895 }
896
897 proc prepend-path-un {args} {
898 # Set the variable for later use during the modulefile evaluation
899 unload-path prepend-path unload remove {*}$args
900
901 return {}
902 }
903
904 proc append-path {args} {
905 # Set the variable for later use during the modulefile evaluation
906 add-path append-path load append {*}$args
907
908 return {}
909 }
910
911 proc append-path-un {args} {
912 # Set the variable for later use during the modulefile evaluation
913 unload-path append-path unload remove {*}$args
914
915 return {}
916 }
917
918 proc remove-path {args} {
919 # Set the variable for later use during the modulefile evaluation
920 unload-path remove-path load remove {*}$args
921
922 return {}
923 }
924
925 # undo remove-path in unload mode
926 proc remove-path-un {args} {
927 lassign [unload-path remove-path unload noop {*}$args] bhv var
928
929 # clean any previously defined pushenv stack
930 unset-env [getPushenvVarName $var] 1
931
932 # clear variable if it does not exist on unload mode for later use
933 # during the modulefile evaluation
934 if {![isEnvVarDefined $var]} {
935 reset-to-unset-env $var
936 }
937 }
938
939 # optimized *-path for whatis mode: init env variable with an empty value if
940 # undefined. do not care about value, just avoid variable to be undefined for
941 # later use during the modulefile evaluation
942 proc edit-path-wh {cmd args} {
943 # get variable name
944 lassign [parsePathCommandArgs $cmd load noop {*}$args] separator allow_dup\
945 idx_val ign_refcount val_set_is_delim glob_match bhv var path_list
946
947 setEnvVarIfUndefined $var {}
948
949 return {}
950 }
951
952 proc set-alias {alias what} {
953 set ::g_Aliases($alias) $what
954 set ::g_stateAliases($alias) new
955
956 # current module is qualified for refresh evaluation
957 lappendState -nodup refresh_qualified [currentState modulename]
958
959 return {}
960 }
961
962 # undo set-alias in unload mode
963 proc set-alias-un {alias what} {
964 return [unset-alias $alias]
965 }
966
967 proc unset-alias {alias} {
968 set ::g_Aliases($alias) {}
969 set ::g_stateAliases($alias) del
970
971 return {}
972 }
973
974 proc set-function {function what} {
975 set ::g_Functions($function) $what
976 set ::g_stateFunctions($function) new
977
978 # current module is qualified for refresh evaluation
979 lappendState -nodup refresh_qualified [currentState modulename]
980
981 return {}
982 }
983
984 # undo set-function in unload mode
985 proc set-function-un {function what} {
986 return [unset-function $function]
987 }
988
989 proc unset-function {function} {
990 set ::g_Functions($function) {}
991 set ::g_stateFunctions($function) del
992
993 return {}
994 }
995
996
997 proc is-loaded {args} {
998 # parse module version specification
999 set args [parseModuleSpecification 0 0 0 0 {*}$args]
1000
1001 foreach mod $args {
1002 if {[getLoadedMatchingName $mod returnfirst] ne {}} {
1003 return 1
1004 }
1005 }
1006 # is something loaded whatever it is?
1007 return [expr {![llength $args] && [llength\
1008 [getEnvLoadedModulePropertyParsedList name]]}]
1009 }
1010
1011 proc is-loading {args} {
1012 foreach mod $args {
1013 if {[getLoadedMatchingName $mod returnfirst 1] ne {}} {
1014 return 1
1015 }
1016 }
1017 # is something else loading whatever it is?
1018 return [expr {![llength $args] && [llength [getLoadingModuleList]] > 1}]
1019 }
1020
1021 proc conflict {args} {
1022 set currentModule [currentState modulename]
1023 set curmodnamevr [currentState modulenamevr]
1024 # get module short name if loaded by its full pathname
1025 if {[set isfullpath [isModuleFullPath $currentModule]]} {
1026 set currentSModule [findModuleNameFromModulefile $currentModule]
1027 }
1028 defineModEqProc [isIcase] [getConf extended_default]
1029
1030 set conflict_unload [expr {[getConf conflict_unload] && [getConf\
1031 auto_handling]}]
1032
1033 # parse module version specification
1034 set args [parseModuleSpecification 0 0 0 0 {*}$args]
1035
1036 registerCurrentModuleConflict {*}$args
1037
1038 foreach mod $args {
1039 set is_conflict_loading 0
1040 set unload_attempt 0
1041 set loaded_conflict_mod_list [getLoadedMatchingName $mod returnall]
1042
1043 if {![llength $loaded_conflict_mod_list]} {
1044 set eq_current_mod [expr {[modEq $mod $currentModule eqstart 1 2 1]\
1045 || ($isfullpath && [modEq $mod $currentSModule eqstart 1 2 1])}]
1046 # currently evaluating module should not be mistaken for loading
1047 # conflicting module
1048 if {!$eq_current_mod} {
1049 set loaded_conflict_mod_list [getLoadedMatchingName $mod\
1050 returnall 1]
1051 if {[llength $loaded_conflict_mod_list]} {
1052 # no conflict unload attempt on loading module
1053 set is_conflict_loading 1
1054 }
1055 }
1056 } elseif {$conflict_unload} {
1057 set still_loaded_conflict_mod_list {}
1058 # unload attempt in reverse load order
1059 foreach loaded_conflict_mod [lreverse $loaded_conflict_mod_list] {
1060 if {[cmdModuleUnload conun match 1 s 0 $loaded_conflict_mod]} {
1061 lappend still_loaded_conflict_mod_list $loaded_conflict_mod
1062 }
1063 }
1064 set loaded_conflict_mod_list $still_loaded_conflict_mod_list
1065 set unload_attempt 1
1066 }
1067
1068 if {[llength $loaded_conflict_mod_list]} {
1069 setConflictErrorAsReported {*}$loaded_conflict_mod_list
1070
1071 # error msg has already been sent if a conflict unload was attempted
1072 set msg [expr {$unload_attempt ? {} : [getPresentConflictErrorMsg\
1073 $curmodnamevr $loaded_conflict_mod_list $is_conflict_loading]}]
1074 knerrorOrWarningIfForced $msg MODULES_ERR_GLOBAL
1075 }
1076 }
1077
1078 return {}
1079 }
1080
1081 proc registerCurrentModuleConflict {args} {
1082 # register conflict list unless record inhibited for current iterp context
1083 if {[currentState inhibit_req_record] != [currentState evalid]} {
1084 setLoadedConflict [currentState modulename] {*}$args
1085 }
1086 }
1087
1088 proc parsePrereqCommandArgs {cmd args} {
1089 set tag_list {}
1090 set modulepath_list {}
1091 set optional 0
1092 set opt_list {}
1093 set prereq_list {}
1094
1095 # parse options defined
1096 set i 0
1097 foreach arg $args {
1098 if {[info exists nextargistaglist]} {
1099 set tag_list [split $arg :]
1100 lappend opt_list $arg
1101 unset nextargistaglist
1102 } elseif {[info exists nextargismodulepathlist]} {
1103 set modulepath_list {}
1104 # record list of absolute paths
1105 foreach modulepath [split $arg :] {
1106 lappend modulepath_list [getAbsolutePath $modulepath]
1107 }
1108 lappend opt_list $arg
1109 unset nextargismodulepathlist
1110 } else {
1111 switch -glob -- $arg {
1112 --optional {
1113 set optional 1
1114 lappend opt_list $arg
1115 }
1116 --tag=* {
1117 set tag_list [split [string range $arg 6 end] :]
1118 lappend opt_list $arg
1119 if {![llength $tag_list]} {
1120 knerror "Missing value for '--tag' option"
1121 }
1122 }
1123 --tag {
1124 set nextargistaglist 1
1125 lappend opt_list $arg
1126 }
1127 --modulepath {
1128 set nextargismodulepathlist 1
1129 lappend opt_list $arg
1130 }
1131 -* {
1132 knerror "Invalid option '$arg'"
1133 }
1134 default {
1135 set prereq_list [lrange $args $i end]
1136 # end option parsing: remaining elts are list of prereqs
1137 break
1138 }
1139 }
1140 }
1141 incr i
1142 }
1143
1144 foreach tag $tag_list {
1145 if {$tag in [list loaded auto-loaded forbidden nearly-forbidden\
1146 hidden warning]} {
1147 knerror "Tag '$tag' cannot be manually set"
1148 }
1149 }
1150 if {![llength $prereq_list]} {
1151 knerror "wrong # args: should be \"$cmd ?--optional? ?--tag? ?taglist?\
1152 ?--modulepath? ?modulepathlist? modulefile ?...?\""
1153 } elseif {[set mispopt [lsearch -inline -glob $prereq_list --*]] ne {}} {
1154 knerror "Misplaced option '$mispopt'"
1155 }
1156 return [list $tag_list $modulepath_list $optional $opt_list $prereq_list]
1157 }
1158
1159 proc prereqAnyModfileCmd {tryload auto args} {
1160 lassign [parsePrereqCommandArgs prereq {*}$args] tag_list modulepath_list\
1161 optional opt_list args
1162
1163 set currentModule [currentState modulename]
1164 set curmodnamevr [currentState modulenamevr]
1165
1166 # parse module version specification
1167 set args [parseModuleSpecification 0 0 0 0 {*}$args]
1168
1169 # register prereq list (sets of optional prereq are registered as list)
1170 # unless record inhibited for current iterp context
1171 if {[currentState inhibit_req_record] != [currentState evalid]} {
1172 # if requirement is optional, add current module to the recorded prereq
1173 # list to make the requirement rule satisfied even if none loaded, as
1174 # current module will be loaded
1175 if {$optional} {
1176 lappend record_list $currentModule
1177 }
1178 lappend record_list {*}$args
1179 setLoadedPrereq $currentModule $record_list
1180
1181 if {[llength $modulepath_list]} {
1182 setLoadedPrereqPath $currentModule $record_list $modulepath_list
1183 }
1184 }
1185
1186 if {$auto} {
1187 # convert modulepath list to keep entries not matching any enabled
1188 # modulepaths and transform entries into all matching enabled modulepath
1189 set converted_list {}
1190 foreach modulepath $modulepath_list {
1191 set matching_list [getMatchingModulepathList $modulepath]
1192 if {[llength $matching_list]} {
1193 appendNoDupToList converted_list {*}$matching_list
1194 } else {
1195 appendNoDupToList converted_list $modulepath
1196 }
1197 }
1198 set modulepath_list $converted_list
1199
1200 # try to load prereq as dependency resolving is enabled
1201 lassign [loadRequirementModuleList $tryload $optional $tag_list\
1202 $modulepath_list {*}$args] retlo prereqloaded
1203 } else {
1204 set loadedmod_list {}
1205 foreach mod $args {
1206 # get all loaded or loading mod in args list
1207 if {[set loadedmod [getLoadedMatchingName $mod returnfirst 0 {}\
1208 $modulepath_list]] ne {} || [set loadedmod [getLoadedMatchingName\
1209 $mod returnfirst 1 {} $modulepath_list]] ne {}} {
1210 lappend loadedmod_list $loadedmod
1211 }
1212 }
1213 set prereqloaded [llength $loadedmod_list]
1214 }
1215
1216 if {!$prereqloaded} {
1217 if {!$optional} {
1218 # error if requirement is not satisfied unless if optional
1219 reportMissingPrereqError $curmodnamevr $modulepath_list {*}$args
1220 }
1221 } elseif {!$auto} {
1222 # apply missing tag to all loaded module found (already done when
1223 # dependency resolving is enabled)
1224 cmdModuleTag 0 0 $tag_list {*}$loadedmod_list
1225 }
1226
1227 return {}
1228 }
1229
1230 proc x-resource {resource {value {}}} {
1231 # sometimes x-resource value may be provided within resource name
1232 # as the "x-resource {Ileaf.popup.saveUnder: True}" example provided
1233 # in manpage. so here is an attempt to extract real resource name and
1234 # value from resource argument
1235 if {![string length $value] && ![file exists $resource]} {
1236 # look first for a space character as delimiter, then for a colon
1237 set sepapos [string first { } $resource]
1238 if { $sepapos == -1 } {
1239 set sepapos [string first : $resource]
1240 }
1241
1242 if { $sepapos > -1 } {
1243 set value [string range $resource $sepapos+1 end]
1244 set resource [string range $resource 0 $sepapos-1]
1245 reportDebug "corrected ($resource, $value)"
1246 } else {
1247 # if not a file and no value provided x-resource cannot be
1248 # recorded as it will produce an error when passed to xrdb
1249 reportWarning "x-resource $resource is not a valid string or file"
1250 return {}
1251 }
1252 }
1253
1254 # check current environment can handle X11 resource edition elsewhere exit
1255 if {[catch {runCommand xrdb -query} errMsg]} {
1256 knerror "X11 resources cannot be edited, issue spotted\n[sgr er\
1257 ERROR]: $errMsg" MODULES_ERR_GLOBAL
1258 }
1259
1260 # if a resource does hold an empty value in g_newXResources or
1261 # g_delXResources arrays, it means this is a resource file to parse
1262 if {[currentState mode] eq {load}} {
1263 set ::g_newXResources($resource) $value
1264 } else {
1265 set ::g_delXResources($resource) $value
1266 }
1267
1268 return {}
1269 }
1270
1271 proc uname {what} {
1272 return [switch -- $what {
1273 sysname {getState os}
1274 machine {getState machine}
1275 nodename - node {getState nodename}
1276 release {getState osversion}
1277 domain {getState domainname}
1278 version {getState kernelversion}
1279 default {knerror "uname $what not supported"}
1280 }]
1281 }
1282
1283 # run shell command
1284 proc system {args} {
1285 # run through the appropriate shell
1286 if {[getState is_win]} {
1287 set shell cmd.exe
1288 set shellarg /c
1289 } else {
1290 set shell /bin/sh
1291 set shellarg -c
1292 }
1293
1294 if {[catch {exec >&@stderr $shell $shellarg [join $args]}]} {
1295 # non-zero exit status, get it:
1296 return [lindex $::errorCode 2]
1297 } else {
1298 # exit status was 0
1299 return 0
1300 }
1301 }
1302
1303 # test at least one of the collections passed as argument exists
1304 proc is-saved {args} {
1305 foreach coll $args {
1306 lassign [findCollections $coll exact] collfile colldesc
1307 if {[string length $collfile]} {
1308 return 1
1309 }
1310 }
1311 # is something saved whatever it is?
1312 return [expr {![llength $args] && [llength [findCollections]]}]
1313 }
1314
1315 # test at least one of the directories passed as argument is set in MODULEPATH
1316 proc is-used {args} {
1317 set modpathlist [getModulePathList]
1318 foreach path $args {
1319 # transform given path in an absolute path to compare with dirs
1320 # registered in the MODULEPATH env var which are returned absolute.
1321 set abspath [getAbsolutePath $path]
1322 if {$abspath in $modpathlist} {
1323 return 1
1324 }
1325 }
1326 # is something used whatever it is?
1327 return [expr {![llength $args] && [llength $modpathlist]}]
1328 }
1329
1330 # test at least one of the modulefiles passed as argument exists
1331 proc is-avail {args} {
1332 # parse module version specification
1333 # a module name is mandatory
1334 set args [parseModuleSpecification 0 0 0 0 {*}$args]
1335 set ret 0
1336
1337 # disable error reporting to avoid modulefile errors
1338 # to pollute result. Only if not already inhibited
1339 set alreadyinhibit [getState inhibit_errreport]
1340 if {!$alreadyinhibit} {
1341 inhibitErrorReport
1342 }
1343
1344 foreach mod $args {
1345 lassign [getPathToModule $mod] modfile modname modnamevr
1346 if {$modfile ne {}} {
1347 set ret 1
1348 break
1349 }
1350 }
1351
1352 # re-enable only is it was disabled from this procedure
1353 if {!$alreadyinhibit} {
1354 setState inhibit_errreport 0
1355 }
1356 return $ret
1357 }
1358
1359 proc execShAndGetEnv {elt_ignored_list shell script args} {
1360 set sep {%ModulesShToMod%}
1361 set subsep {%ModulesSubShToMod%}
1362 set shdesc [list $script {*}$args]
1363 set sherr 0
1364 set shellopts [list]
1365
1366 upvar ignvarlist ignvarlist
1367 set ignvarlist [list OLDPWD PWD _ _AST_FEATURES PS1 _LMFILES_\
1368 LOADEDMODULES]
1369
1370 # define shell command to run to source script and analyze the environment
1371 # changes it performs
1372 switch -- [file tail $shell] {
1373 dash - sh {
1374 # declare is not supported by dash but functions cannot be retrieved
1375 # anyway, so keep using declare and throw errors out to avoid overall
1376 # execution error. dash does not pass arguments to sourced script but
1377 # it does not raise error if arguments are set
1378 ##nagelfar ignore +3 Found constant
1379 set command "export -p; echo $sep; declare -f 2>/dev/null; echo\
1380 $sep; alias; echo $sep; echo $sep; pwd; echo $sep; . [listTo\
1381 shell $shdesc] 2>&1; echo $sep; export -p; echo $sep; declare -f\
1382 2>/dev/null; echo $sep; alias; echo $sep; echo $sep; pwd"
1383 set varre {export (\S+?)=["']?(.*?)["']?$}
1384 set funcre {(\S+?) \(\)\s?\n?{\s?\n(.+?)\n}$}
1385 set aliasre {(\S+?)='(.*?)'$}
1386 set varvalmap [list {\"} \" \\\\ \\]
1387 set alvalmap [list {'\''} ' {'"'"'} ']
1388 }
1389 bash {
1390 ##nagelfar ignore +2 Found constant
1391 set command "export -p; echo $sep; declare -f; echo $sep; alias;\
1392 echo $sep; complete; echo $sep; pwd; echo $sep; . [listTo shell\
1393 $shdesc] 2>&1; echo $sep; export -p; echo $sep; declare -f; echo\
1394 $sep; alias; echo $sep; complete; echo $sep; pwd"
1395 set varre {declare -x (\S+?)="(.*?)"$}
1396 set funcre {(\S+?) \(\)\s?\n{\s?\n(.+?)\n}$}
1397 set aliasre {alias (\S+?)='(.*?)'$}
1398 set compre {complete (.+?) (\S+?)$}
1399 set comprevar [list match value name]
1400 set varvalmap [list {\"} \" \\\\ \\]
1401 set alvalmap [list {'\''} ']
1402 lappend shellopts --noprofile --norc
1403 }
1404 bash-eval {
1405 ##nagelfar ignore +3 Found constant
1406 set command "export -p; echo $sep; declare -f; echo $sep; alias;\
1407 echo $sep; complete; echo $sep; pwd; echo $sep; eval \"\$([listTo\
1408 shell $shdesc] 2>/dev/null)\"; echo $sep; export -p; echo $sep;\
1409 declare -f; echo $sep; alias; echo $sep; complete; echo $sep; pwd"
1410 set varre {declare -x (\S+?)="(.*?)"$}
1411 set funcre {(\S+?) \(\)\s?\n{\s?\n(.+?)\n}$}
1412 set aliasre {alias (\S+?)='(.*?)'$}
1413 set compre {complete (.+?) (\S+?)$}
1414 set comprevar [list match value name]
1415 set varvalmap [list {\"} \" \\\\ \\]
1416 set alvalmap [list {'\''} ']
1417 lappend shellopts --noprofile --norc
1418 }
1419 ksh - ksh93 {
1420 ##nagelfar ignore +3 Found constant
1421 set command "typeset -x; echo $sep; typeset +f | while read f; do\
1422 typeset -f \${f%\\(\\)}; echo; done; echo $sep; alias; echo $sep;\
1423 echo $sep; pwd; echo $sep; . [listTo shell $shdesc] 2>&1; echo\
1424 $sep; typeset -x; echo $sep; typeset +f | while read f; do\
1425 typeset -f \${f%\\(\\)}; echo; done; echo $sep; alias; echo $sep;\
1426 echo $sep; pwd"
1427 set varre {(\S+?)=\$?'?(.*?)'?$}
1428 set funcre {(\S+?)\(\) {\n?(.+?)}[;\n]?$}
1429 set aliasre {(\S+?)=\$?'?(.*?)'?$}
1430 set varvalmap [list {\'} ']
1431 set alvalmap [list {\"} \" {\\'} ' {\'} ' {\\\\} {\\}]
1432 }
1433 zsh {
1434 ##nagelfar ignore +2 Found constant
1435 set command "typeset -x; echo $sep; declare -f; echo $sep; alias;\
1436 echo $sep; echo $sep; pwd; echo $sep; . [listTo shell $shdesc]\
1437 2>&1; echo $sep; typeset -x; echo $sep; declare -f; echo $sep;\
1438 alias; echo $sep; echo $sep; pwd"
1439 set varre {(\S+?)=\$?'?(.*?)'?$}
1440 set funcre {(\S+?) \(\) {\n(.+?)\n}$}
1441 set aliasre {(\S+?)=\$?'?(.*?)'?$}
1442 set varvalmap [list {'\''} ']
1443 set alvalmap [list {'\''} ']
1444 }
1445 csh {
1446 ##nagelfar ignore +2 Found constant
1447 set command "setenv; echo $sep; echo $sep; alias; echo $sep; echo\
1448 $sep; pwd; echo $sep; source [listTo shell $shdesc] >&\
1449 /dev/stdout; echo $sep; setenv; echo $sep; echo $sep; alias; echo\
1450 $sep; echo $sep; pwd"
1451 set varre {(\S+?)=(.*?)$}
1452 set aliasre {(\S+?)\t(.*?)$}
1453 set varvalmap [list]
1454 set alvalmap [list]
1455 lappend shellopts -f
1456 }
1457 tcsh {
1458 ##nagelfar ignore +2 Found constant
1459 set command "setenv; echo $sep; echo $sep; alias; echo $sep;\
1460 complete; echo $sep; pwd; echo $sep; source [listTo shell\
1461 $shdesc] >& /dev/stdout; echo $sep; setenv; echo $sep; echo $sep;\
1462 alias; echo $sep; complete; echo $sep; pwd"
1463 set varre {(\S+?)=(.*?)$}
1464 set aliasre {(\S+?)\t\(?(.*?)\)?$}
1465 set compre {(\S+?)\t(.*?)$}
1466 set comprevar [list match name value]
1467 set varvalmap [list]
1468 set alvalmap [list]
1469 lappend shellopts -f
1470 }
1471 fish {
1472 # exclude from search builtins, fish-specific functions and private
1473 # functions defined prior script evaluation: reduce this way the
1474 # the number of functions to parse.
1475 set getfunc "set funcout (string match -r -v \$funcfilter (functions\
1476 -a -n) | while read f; functions \$f; echo '$subsep'; end)"
1477 ##nagelfar ignore +9 Found constant
1478 set command "set -xgL; echo '$sep'; status test-feature\
1479 regex-easyesc 2>/dev/null; and set escrepl '\\\\\\\\\$1'; or set\
1480 escrepl '\\\\\\\\\\\\\\\$1'; set funcfilter \\^\\((string\
1481 join '|' (string replace -r '(\\\[|\\.)' \$escrepl\
1482 (builtin -n; functions -a -n | string split ', ' | string match\
1483 -e -r '^_')))\\|fish\\.\\*\\)\\\$; $getfunc; $getfunc; string\
1484 split \$funcout; echo '$sep'; string split \$funcout; echo\
1485 '$sep'; complete; echo '$sep'; pwd; echo '$sep'; source [listTo\
1486 shell $shdesc] 2>&1; or exit \$status; echo '$sep'; set -xgL;\
1487 echo '$sep'; $getfunc; string split \$funcout; echo '$sep';\
1488 string split \$funcout; echo '$sep'; complete; echo '$sep'; pwd"
1489 set varre {^(\S+?\M) ?['"]?(.*?)['"]?$}
1490 # exclude alias from function list
1491 set funcre "^function (\\S+?)(?: \[^\\n\]*?--description\
1492 (?!'?alias)\[^\\n\]+)?\\n(.+?)?\\s*\\nend\\n$subsep\$"
1493 # fetch aliases from available functions
1494 set aliasre "^function (\\S+?) \[^\\n\]*?--description\
1495 '?alias\[^\\n\]+\\n\\s*(.+?)(?: \\\$argv)?\\s*\\nend\\n$subsep\$"
1496 set compre {complete ((?:-\S+? )*?)(?:(?:-c|--command)\
1497 )?([^-]\S+)(.*?)$}
1498 set comprevar [list match valpart1 name valpart2]
1499 # translate back fish-specific code
1500 set varvalmap [list {' '} : {\'} ' {\"} \" \\\\ \\]
1501 set alvalmap [list { $argv;} {}]
1502
1503 # fish builtins change LS_COLORS variable
1504 lappend ignvarlist LS_COLORS
1505 }
1506 default {
1507 knerror "Shell '$shell' not supported"
1508 }
1509 }
1510
1511 if {![file exists $script]} {
1512 knerror "Script '$script' cannot be found"
1513 }
1514
1515 set real_shell [expr {$shell eq {bash-eval} ? {bash} : $shell}]
1516 set shellpath [getCommandPath $real_shell]
1517 if {$shellpath eq {}} {
1518 knerror "Shell '$shell' cannot be found"
1519 }
1520 set shellexec [list $shellpath {*}$shellopts -c $command]
1521
1522 reportDebug "running '$shellexec'"
1523 if {[catch {set output [exec {*}$shellexec]} output]} {
1524 set sherr 1
1525 }
1526
1527 # link result variables to calling context
1528 upvar cwdbefout cwdbefout cwdaftout cwdaftout
1529
1530 # extract each output sections
1531 set idx 0
1532 foreach varout {varbefout funcbefout aliasbefout compbefout cwdbefout\
1533 scriptout varaftout funcaftout aliasaftout compaftout cwdaftout} {
1534 ##nagelfar vartype varout varName
1535 if {[set sepidx [string first $sep $output $idx]] == -1} {
1536 set $varout [string trimright [string range $output $idx end] \n]
1537 if {$varout ne {cwdaftout} && !$sherr} {
1538 knerror "Unexpected output when sourcing '$shdesc' in shell\
1539 '$shell'"
1540 }
1541 } else {
1542 set $varout [string trimright [string range $output $idx $sepidx-1]\
1543 \n]
1544 set idx [expr {$sepidx + [string length $sep] + 1}]
1545 }
1546 # remove expected Tcl error message
1547 if {$sherr && $varout eq {scriptout} && [set erridx [string\
1548 last {child process exited abnormally} [set $varout]]] != -1} {
1549 set $varout [string range [set $varout] 0 $erridx-2]
1550 }
1551 }
1552 if {$sepidx != -1 && !$sherr} {
1553 knerror "Unexpected output when sourcing '$shdesc' in shell '$shell'"
1554 }
1555
1556 reportDebug "script output is '$scriptout'"
1557 if {$sherr} {
1558 # throw error if script had an issue, send script output along if any
1559 set errmsg "Script '$script' exited abnormally"
1560 if {$scriptout ne {}} {
1561 append errmsg "\n with following output\n$scriptout"
1562 }
1563 knerror $errmsg
1564 }
1565
1566 # link result variables to calling context
1567 upvar varbef varbef varaft varaft
1568 upvar funcbef funcbef funcaft funcaft
1569 upvar aliasbef aliasbef aliasaft aliasaft
1570 upvar compbef compbef compaft compaft
1571
1572 # clear current directory change if ignored
1573 if {{chdir} in $elt_ignored_list} {
1574 set cwdaftout $cwdbefout
1575 }
1576
1577 # extract environment variable information
1578 if {{envvar} ni $elt_ignored_list} {
1579 ##nagelfar ignore Found constant
1580 foreach {out arr} [list varbefout varbef varaftout varaft] {
1581 ##nagelfar vartype out varName
1582 foreach {match name value} [regexp -all -inline -lineanchor $varre\
1583 [set $out]] {
1584 # convert shell-specific escaping
1585 ##nagelfar ignore Suspicious variable name
1586 set ${arr}($name) [string map $varvalmap $value]
1587 }
1588 }
1589 }
1590 # extract function information if function supported by shell
1591 if {{function} ni $elt_ignored_list && [info exists funcre]} {
1592 ##nagelfar ignore Found constant
1593 foreach {out arr} [list funcbefout funcbef funcaftout funcaft] {
1594 foreach {match name value} [regexp -all -inline -lineanchor $funcre\
1595 [set $out]] {
1596 # no specific escaping to convert for functions
1597 ##nagelfar ignore Suspicious variable name
1598 set ${arr}($name) $value
1599 }
1600 }
1601 }
1602 # extract alias information
1603 if {{alias} ni $elt_ignored_list} {
1604 ##nagelfar ignore Found constant
1605 foreach {out arr} [list aliasbefout aliasbef aliasaftout aliasaft] {
1606 foreach {match name value} [regexp -all -inline -lineanchor $aliasre\
1607 [set $out]] {
1608 ##nagelfar ignore Suspicious variable name
1609 set ${arr}($name) [string map $alvalmap $value]
1610 }
1611 }
1612 }
1613 # extract complete information if supported by shell
1614 if {{complete} ni $elt_ignored_list && [info exists compre]} {
1615 ##nagelfar ignore Found constant
1616 foreach {out arr} [list compbefout compbef compaftout compaft] {
1617 ##nagelfar ignore Non constant variable list to foreach statement
1618 foreach $comprevar [regexp -all -inline -lineanchor $compre [set\
1619 $out]] {
1620 if {[info exists valpart1]} {
1621 ##nagelfar ignore Unknown variable
1622 set value [concat $valpart1 $valpart2]
1623 }
1624 # no specific escaping to convert for completes
1625 ##nagelfar ignore Suspicious variable name
1626 lappend ${arr}($name) $value
1627 }
1628 }
1629 }
1630 }
1631
1632 # execute script with args through shell and convert environment changes into
1633 # corresponding modulefile commands
1634 proc sh-to-mod {elt_ignored_list args} {
1635 set modcontent [list]
1636 set pathsep [getState path_separator]
1637 set shell [lindex $args 0]
1638
1639 # evaluate script and retrieve environment before and after evaluation
1640 # procedure will set result variables in current context
1641 ##nagelfar implicitvarcmd {execShAndGetEnv *} ignvarlist cwdbefout\
1642 cwdaftout varbef varaft funcbef funcaft aliasbef aliasaft compbef\
1643 compaft
1644 execShAndGetEnv $elt_ignored_list {*}$args
1645
1646 # check environment variable change
1647 lassign [getDiffBetweenArray varbef varaft] notaft diff notbef
1648 foreach name $notaft {
1649 # also ignore Modules variables intended for internal use
1650 if {$name ni $ignvarlist && ![string equal -length 10 $name\
1651 __MODULES_]} {
1652 lappend modcontent [list unsetenv $name]
1653 }
1654 }
1655 foreach name $diff {
1656 if {$name ni $ignvarlist && ![string equal -length 10 $name\
1657 __MODULES_]} {
1658 # new value is totally different (also consider a bare ':' as a
1659 # totally different value to avoid erroneous matches)
1660 if {$varbef($name) eq $pathsep || [set idx [string first\
1661 $varbef($name) $varaft($name)]] == -1} {
1662 lappend modcontent [list setenv $name $varaft($name)]
1663 } else {
1664 # content should be prepended
1665 if {$idx > 0} {
1666 set modcmd [list prepend-path]
1667 # check from the end to get the largest chunk to prepend
1668 set idx [string last $varbef($name) $varaft($name)]
1669 # get delimiter from char found between new and existing value
1670 set delim [string index $varaft($name) $idx-1]
1671 if {$delim ne $pathsep} {
1672 lappend modcmd -d $delim
1673 }
1674 lappend modcmd $name
1675 # split value and remove duplicate entries
1676 set vallist [list]
1677 appendNoDupToList vallist {*}[split [string range\
1678 $varaft($name) 0 $idx-2] $delim]
1679 # an empty element is added
1680 if {![llength $vallist]} {
1681 lappend vallist {}
1682 }
1683 lappend modcontent [list {*}$modcmd {*}$vallist]
1684 }
1685 # content should be appended
1686 if {($idx + [string length $varbef($name)]) < [string length\
1687 $varaft($name)]} {
1688 set modcmd [list append-path]
1689 set delim [string index $varaft($name) $idx+[string length\
1690 $varbef($name)]]
1691 if {$delim ne $pathsep} {
1692 lappend modcmd -d $delim
1693 }
1694 lappend modcmd $name
1695 set vallist [list]
1696 appendNoDupToList vallist {*}[split [string range\
1697 $varaft($name) [expr {$idx + [string length $varbef($name)]\
1698 + 1}] end] $delim]
1699 if {![llength $vallist]} {
1700 lappend vallist {}
1701 }
1702 lappend modcontent [list {*}$modcmd {*}$vallist]
1703 }
1704 }
1705 }
1706 }
1707 foreach name $notbef {
1708 if {$name ni $ignvarlist && ![string equal -length 10 $name\
1709 __MODULES_]} {
1710 if {[string first $pathsep $varaft($name)] == -1} {
1711 lappend modcontent [list setenv $name $varaft($name)]
1712 } else {
1713 # define a path-like variable if path separator found in it
1714 # split value and remove duplicate entries
1715 set vallist [list]
1716 appendNoDupToList vallist {*}[split $varaft($name) $pathsep]
1717 lappend modcontent [list prepend-path $name {*}$vallist]
1718 }
1719 }
1720 }
1721 # check function change
1722 lassign [getDiffBetweenArray funcbef funcaft] notaft diff notbef
1723 foreach name $notaft {
1724 lappend modcontent [list unset-function $name]
1725 }
1726 foreach name [list {*}$diff {*}$notbef] {
1727 lappend modcontent [list set-function $name \n$funcaft($name)]
1728 }
1729 # check alias change
1730 lassign [getDiffBetweenArray aliasbef aliasaft] notaft diff notbef
1731 foreach name $notaft {
1732 lappend modcontent [list unset-alias $name]
1733 }
1734 foreach name [list {*}$diff {*}$notbef] {
1735 lappend modcontent [list set-alias $name $aliasaft($name)]
1736 }
1737 # check complete change
1738 set real_shell [expr {$shell eq {bash-eval} ? {bash} : $shell}]
1739 lassign [getDiffBetweenArray compbef compaft] notaft diff notbef
1740 foreach name $notaft {
1741 lappend modcontent [list uncomplete $name]
1742 }
1743 foreach name [list {*}$diff {*}$notbef] {
1744 foreach body $compaft($name) {
1745 lappend modcontent [list complete $real_shell $name $body]
1746 }
1747 }
1748 # check current working directory change
1749 if {$cwdbefout ne $cwdaftout} {
1750 lappend modcontent [list chdir $cwdaftout]
1751 }
1752
1753 # sort result to ensure consistent output whatever the evaluation shell
1754 set modcontent [lsort -dictionary $modcontent]
1755
1756 reportDebug "resulting env changes '$modcontent'"
1757 return $modcontent
1758 }
1759
1760 proc parseSourceShArgs {args} {
1761 set elt_ignored_list {}
1762
1763 set i 0
1764 foreach arg $args {
1765 incr i
1766 if {[info exists nextargisval]} {
1767 ##nagelfar vartype nextargisval varName
1768 set $nextargisval $arg
1769 unset nextargisval
1770 } else {
1771 switch -glob -- $arg {
1772 --ignore {
1773 set nextargisval ignore_opt_raw
1774 }
1775 -* {
1776 knerror "Invalid option '$arg'"
1777 }
1778 default {
1779 set shell $arg
1780 # end option parsing: remaining elts are allowed values
1781 break
1782 }
1783 }
1784 set prevarg $arg
1785 }
1786 }
1787
1788 if {[info exists nextargisval]} {
1789 knerror "Missing value for '$prevarg' option"
1790 }
1791
1792 if {![info exists shell] || $i == [llength $args]} {
1793 knerror "wrong # args: should be \"source-sh ?--ignore? ?eltlist? shell\
1794 script ?arg ...?\""
1795 }
1796
1797 set script_args [lassign [lrange $args $i end] script]
1798
1799 if {[info exists ignore_opt_raw]} {
1800 set elt_ignored_list [split $ignore_opt_raw :]
1801 set allowed_elt_ignored_list {envvar function alias chdir complete}
1802 foreach elt_ignored $elt_ignored_list {
1803 if {$elt_ignored ni $allowed_elt_ignored_list} {
1804 knerror "Invalid ignored element '$elt_ignored'"
1805 }
1806 }
1807 }
1808
1809 return [list $elt_ignored_list $shell $script $script_args]
1810 }
1811
1812 proc source-sh {args} {
1813 lassign [parseSourceShArgs {*}$args] elt_ignored_list shell script\
1814 script_args
1815 # evaluate script and get the environment changes it performs translated
1816 # into modulefile commands
1817 set shtomodargs [list $shell $script {*}$script_args]
1818 set modcontent [sh-to-mod $elt_ignored_list {*}$shtomodargs]
1819
1820 # register resulting modulefile commands
1821 setLoadedSourceSh [currentState modulename] [list $shtomodargs\
1822 {*}$modcontent]
1823
1824 # get name of current module Tcl interp
1825 set itrp [getCurrentModfileInterpName]
1826
1827 # evaluate resulting modulefile commands through current Tcl interp
1828 foreach modcmd $modcontent {
1829 interp eval $itrp $modcmd
1830 }
1831 }
1832
1833 # undo source-sh in unload mode
1834 proc source-sh-un {args} {
1835 lassign [parseSourceShArgs {*}$args] elt_ignored_list shell script\
1836 script_args
1837 set shtomodargs [list $shell $script {*}$script_args]
1838 # find commands resulting from source-sh evaluation recorded in env
1839 set modcontent [getLoadedSourceShScriptContent [currentState modulename]\
1840 $shtomodargs]
1841
1842 # get name of current module unload Tcl interp
1843 set itrp [getCurrentModfileInterpName]
1844
1845 # evaluate each recorded command in unload Tcl interp to get them reversed
1846 foreach modcmd $modcontent {
1847 interp eval $itrp $modcmd
1848 }
1849 }
1850
1851 # report underlying modulefile cmds in display mode
1852 proc source-sh-di {args} {
1853 lassign [parseSourceShArgs {*}$args] elt_ignored_list shell script\
1854 script_args
1855 set shtomodargs [list $shell $script {*}$script_args]
1856
1857 # if module loaded, get as much content from environment as possible
1858 if {[is-loaded [currentState modulename]]} {
1859 # find commands resulting from source-sh evaluation recorded in env
1860 set reccontent [getLoadedSourceShScriptContent [currentState\
1861 modulename] $shtomodargs]
1862
1863 # need to evaluate script to get alias/function/complete definition
1864 execShAndGetEnv $elt_ignored_list {*}$shtomodargs
1865
1866 set modcontent {}
1867 foreach cmd $reccontent {
1868 # build modulefile content to show with recorded elements in env and
1869 # alias/function/complete definition obtained by reevaluating script
1870 switch -- [lindex $cmd 0] {
1871 complete {
1872 set cpname [lindex $cmd 2]
1873 if {[info exists compaft($cpname)]} {
1874 set cpbodylist $compaft($cpname)
1875 } else {
1876 set cpbodylist [list {}]
1877 }
1878 foreach cpbody $cpbodylist {
1879 lappend modcontent [list complete $shell $cpname $cpbody]
1880 }
1881 }
1882 set-alias {
1883 set alname [lindex $cmd 1]
1884 if {[info exists aliasaft($alname)]} {
1885 set albody $aliasaft($alname)
1886 } else {
1887 set albody {}
1888 }
1889 lappend modcontent [list set-alias $alname $albody]
1890 }
1891 set-function {
1892 set fnname [lindex $cmd 1]
1893 if {[info exists funcaft($fnname)]} {
1894 set fnbody \n$funcaft($fnname)
1895 } else {
1896 set fnbody {}
1897 }
1898 lappend modcontent [list set-function $fnname $fnbody]
1899 }
1900 default {
1901 lappend modcontent $cmd
1902 }
1903 }
1904 }
1905 # not loaded, so get full content from script evaluation
1906 } else {
1907 set modcontent [sh-to-mod $elt_ignored_list {*}$shtomodargs]
1908 }
1909
1910 # get name of current module unload Tcl interp
1911 set itrp [getCurrentModfileInterpName]
1912
1913 # evaluate each recorded command in display Tcl interp to get them printed
1914 foreach modcmd $modcontent {
1915 interp eval $itrp $modcmd
1916 }
1917 }
1918
1919 proc isVariantNameValid {name} {
1920 return [expr {![string is digit -strict $name] && [regexp\
1921 {^[A-Za-z0-9_][A-Za-z0-9_-]*$} $name]}]
1922 }
1923
1924 # parse arguments set on a variant modulefile command
1925 proc parseVariantCommandArgs {args} {
1926 set dflvalue {}
1927 set defdflvalue 0
1928 set isboolean 0
1929 set i 0
1930 foreach arg $args {
1931 incr i
1932 if {[info exists nextargisval]} {
1933 ##nagelfar vartype nextargisval varName
1934 set $nextargisval $arg
1935 unset nextargisval
1936 } else {
1937 switch -glob -- $arg {
1938 --default {
1939 ##nagelfar ignore Found constant
1940 set nextargisval dflvalue
1941 set defdflvalue 1
1942 }
1943 --boolean {
1944 set isboolean 1
1945 }
1946 -* {
1947 knerror "Invalid option '$arg'"
1948 }
1949 default {
1950 set name $arg
1951 # end option parsing: remaining elts are allowed values
1952 break
1953 }
1954 }
1955 set prevarg $arg
1956 }
1957 }
1958
1959 if {[info exists nextargisval]} {
1960 knerror "Missing value for '$prevarg' option"
1961 }
1962
1963 # check variant name and allowed values
1964 if {![info exists name]} {
1965 knerror {No variant name specified}
1966 }
1967 if {![isVariantNameValid $name]} {
1968 knerror "Invalid variant name '$name'"
1969 }
1970 set values [lrange $args $i end]
1971 if {$isboolean} {
1972 if {[llength $values]} {
1973 knerror "No value should be defined for boolean variant '$name'"
1974 } else {
1975 set values {1 0 yes no true false on off}
1976 }
1977 } else {
1978 foreach val $values {
1979 if {[string is boolean -strict $val] && ![string is integer\
1980 -strict $val]} {
1981 knerror "Boolean value defined on non-boolean variant '$name'"
1982 }
1983 }
1984 }
1985 if {$defdflvalue && $isboolean} {
1986 # default value should be bool if variant is boolean
1987 if {![string is boolean -strict $dflvalue]} {
1988 knerror "Boolean value is expected as default value for variant\
1989 '$name'"
1990 # translate default value in boolean canonical form (0 or 1)
1991 } else {
1992 set dflvalue [string is true -strict $dflvalue]
1993 }
1994 }
1995
1996 return [list $name $values $defdflvalue $dflvalue $isboolean]
1997 }
1998
1999 proc variant {itrp args} {
2000 # parse args
2001 lassign [parseVariantCommandArgs {*}$args] name values defdflvalue\
2002 dflvalue isboolean
2003
2004 # version variant is forbidden until specific implementation
2005 if {$name eq {version}} {
2006 knerror "'version' is a restricted variant name" MODULES_ERR_GLOBAL
2007 }
2008
2009 # get variant list defined on command line
2010 set vrlist [getVariantListFromVersSpec [currentState modulenamevr]]
2011
2012 # search for variant specification (most right-positionned value wins)
2013 for {set i [expr {[llength $vrlist]-1}]} {$i >= 0} {incr i -1} {
2014 lassign [lindex $vrlist $i] vrname vrnot vrisbool vrvalue
2015 if {$vrname eq $name} {
2016 # translate value in boolean canonical form (0/1) if variant is bool
2017 if {$isboolean && [string is boolean -strict $vrvalue]} {
2018 set value [string is true -strict $vrvalue]
2019 } else {
2020 set value $vrvalue
2021 }
2022 set isdflval [expr {$defdflvalue && $dflvalue eq $value}]
2023 break
2024 }
2025 }
2026
2027 # error if variant has not been specified unless a default is defined
2028 if {![info exists isdflval]} {
2029 if {$defdflvalue} {
2030 set value $dflvalue
2031 # 2 means default value automatically set
2032 set isdflval 2
2033 # no error if variant is undefined on display mode, return here not to
2034 # set any variant-specific variable
2035 } elseif {[currentState mode] eq {display}} {
2036 return
2037 } else {
2038 set allowedmsg [expr {![llength $values] ? {} : "\nAllowed values\
2039 are: $values"}]
2040 knerror "No value specified for variant '$name'$allowedmsg"\
2041 MODULES_ERR_GLOBAL
2042 }
2043 }
2044
2045 # check defined value
2046 if {($isboolean && ![string is boolean -strict $value]) || (!$isboolean &&\
2047 [llength $values] && $value ni $values)} {
2048 # invalid value error is not a modulefile error
2049 knerror "Invalid value '$value' for variant '$name'\nAllowed values\
2050 are: $values" MODULES_ERR_GLOBAL
2051 } else {
2052 # instantiate variant in modulefile context
2053 reportDebug "Set variant on $itrp: ModuleVariant($name) = '$value'"
2054 $itrp eval set "{::ModuleVariant($name)}" "{$value}"
2055 # after modfile interp ModuleVariant is unset by resetInterpState
2056
2057 # record variant for persistency (name value is-boolean is-default)
2058 # unless module is currently unloading
2059 if {[currentState mode] ne {unload}} {
2060 setLoadedVariant [currentState modulename] [list $name $value\
2061 $isboolean $isdflval]
2062 }
2063 }
2064 }
2065
2066 # optimized variant command for whatis mode: init entry in ModuleVariant array
2067 # to avoid variable being undefined when accessed during modulefile evaluation
2068 proc variant-wh {itrp args} {
2069 # parse args
2070 lassign [parseVariantCommandArgs {*}$args] name values defdflvalue\
2071 dflvalue isboolean
2072
2073 # instantiate variant in modulefile context to an empty value
2074 reportDebug "Set variant on $itrp: ModuleVariant($name) = ''"
2075 $itrp eval set "{::ModuleVariant($name)}" "{}"
2076 }
2077
2078 proc getvariant {itrp args} {
2079 # parse args
2080 lassign [parseGetenvCommandArgs getvariant {*}$args] name valifundef\
2081 returnval
2082
2083 if {[currentState mode] ne {display} || $returnval} {
2084 if {[$itrp eval info exists "{::ModuleVariant($name)}"]} {
2085 return [$itrp eval set "{::ModuleVariant($name)}"]
2086 } else {
2087 return $valifundef
2088 }
2089 } else {
2090 return [sgr va "{$name}"]
2091 }
2092 }
2093
2094 proc require-fullname {} {
2095 # test specified name is any alternative name of currently evaluating mod
2096 # expect the default and parent dir name (which are considered unqualified)
2097 if {![modEq [currentState specifiedname] [currentState modulename] eqspec\
2098 1 4]} {
2099 knerror {Module version must be specified to load module}\
2100 MODULES_ERR_GLOBAL
2101 }
2102 }
2103
2104 proc prereqAllModfileCmd {tryload auto args} {
2105 lassign [parsePrereqCommandArgs prereq-all {*}$args] tag_list\
2106 modulepath_list optional opt_list args
2107 # call prereq over each arg independently to emulate a prereq-all
2108 foreach arg $args {
2109 prereqAnyModfileCmd $tryload $auto {*}$opt_list $arg
2110 }
2111 }
2112
2113 proc always-load {args} {
2114 lassign [parsePrereqCommandArgs always-load {*}$args] tag_list\
2115 modulepath_list optional opt_list args
2116 # append keep-loaded tag to the list, second tag list in opt_list will take
2117 # over the initial list defined
2118 lappend tag_list keep-loaded
2119 lappend opt_list --tag [join $tag_list :]
2120
2121 # auto load is inhibited if currently in DepRe context
2122 set auto [expr {[currentModuleEvalContext] eq {depre} ? {0} : {1}}]
2123
2124 # load all module specified
2125 prereqAllModfileCmd 0 $auto {*}$opt_list {*}$args
2126 }
2127
2128 proc family {name} {
2129 # ensure name is valid to be part of the name of an environment variable
2130 if {![string length $name] || ![regexp {^[A-Za-z0-9_]*$} $name]} {
2131 knerror "Invalid family name '$name'"
2132 }
2133
2134 # only one loaded module could provide a given family
2135 conflict $name
2136 # set name as an alias for currently loading module
2137 setLoadedAltname [currentState modulename] [list al $name]
2138
2139 # set variable in environment to know what module name provides family
2140 set upname [string toupper $name]
2141 lassign [getModuleNameVersion] mod modname modversion
2142 if {$modname eq {.}} {
2143 set modname [currentState modulename]
2144 }
2145 setenv MODULES_FAMILY_$upname $modname
2146 # also set Lmod-specific variable for compatibility
2147 setenv LMOD_FAMILY_$upname $modname
2148 }
2149
2150 proc family-un {name} {
2151 # ensure name is valid to be part of the name of an environment variable
2152 if {![string length $name] || ![regexp {^[A-Za-z0-9_]*$} $name]} {
2153 knerror "Invalid family name '$name'"
2154 }
2155
2156 # unset family-related environment variable
2157 set upname [string toupper $name]
2158 unsetenv MODULES_FAMILY_$upname
2159 unsetenv LMOD_FAMILY_$upname
2160 }
2161
2162 proc complete {shell name body} {
2163 if {![string length $name]} {
2164 knerror "Invalid command name '$name'"
2165 }
2166 # append definition retaining for which shell they are made
2167 # also some shells may set multiple definitions for a single name
2168 lappend ::g_Completes($name) $shell $body
2169 set ::g_stateCompletes($name) new
2170
2171 # current module is qualified for refresh evaluation
2172 lappendState -nodup refresh_qualified [currentState modulename]
2173 }
2174
2175 # undo complete in unload mode
2176 proc complete-un {shell name body} {
2177 return [uncomplete $name]
2178 }
2179
2180 proc uncomplete {name} {
2181 if {![string length $name]} {
2182 knerror "Invalid command name '$name'"
2183 }
2184 set ::g_Completes($name) {}
2185 set ::g_stateCompletes($name) del
2186 }
2187
2188 proc pushenv {var val} {
2189 # save initial value in pushenv value stack
2190 set pushvar [getPushenvVarName $var]
2191 if {![isEnvVarDefined $pushvar] && [isEnvVarDefined $var]} {
2192 prepend-path $pushvar &$::env($var)
2193 }
2194
2195 # clean any previously defined reference counter array
2196 unset-env [getModshareVarName $var] 1
2197
2198 # Set the variable for later use during the modulefile evaluation
2199 set-env $var $val
2200
2201 # add this value to the stack associated to current module name in order to
2202 # know what element to remove from stack when unloading
2203 prepend-path $pushvar [currentState modulename]&$val
2204
2205 return {}
2206 }
2207
2208 # undo pushenv in unload mode
2209 proc pushenv-un {var val} {
2210 # clean any existing reference counter array
2211 unset-env [getModshareVarName $var] 1
2212
2213 # update value stack
2214 set pushvar [getPushenvVarName $var]
2215 if {[isEnvVarDefined $pushvar]} {
2216 set pushlist [split $::env($pushvar) :]
2217 # find value pushed by currently evaluated module and remove it
2218 set popidx [lsearch -exact $pushlist [currentState modulename]&$val]
2219 if {$popidx != -1} {
2220 set pushlist [lreplace $pushlist $popidx $popidx]
2221 remove-path --index $pushvar $popidx
2222 }
2223
2224 if {[llength $pushlist]} {
2225 # fetch value on top of the stack
2226 set validx [expr {[string first & [lindex $pushlist 0]] + 1}]
2227 set popval [string range [lindex $pushlist 0] $validx end]
2228
2229 # restore top value if different from current one
2230 if {![envVarEquals $var $popval]} {
2231 set-env $var $popval
2232 }
2233
2234 # if last element remaining in stack is the initial value prior first
2235 # pushenv, then clear the stack totally
2236 if {$validx == 1} {
2237 remove-path --index $pushvar 0
2238 }
2239 } else {
2240 unset-env $var 0 $val
2241 }
2242 } else {
2243 # Add variable to the list of variable to unset in shell output code but
2244 # set it in interp context as done on load mode for later use during the
2245 # modulefile evaluation
2246 unset-env $var 0 $val
2247 }
2248
2249 return {}
2250 }
2251
2252 # optimized pushenv for whatis mode (same approach than setenv-wh)
2253 proc pushenv-wh {var val} {
2254 setEnvVarIfUndefined $var {}
2255 return {}
2256 }
2257
2258 proc modulepath-label {modpath label} {
2259 set modpath [getAbsolutePath $modpath]
2260 set ::g_modulepathLabel($modpath) $label
2261 reportDebug "modpath=$modpath, label='$label'"
2262 }
2263
2264 proc unique-name-conflict {} {
2265 # skip if unique_name_loaded configuration is disabled
2266 if {![getConf unique_name_loaded]} {
2267 return
2268 }
2269
2270 # get root name of all names (actual and alternatives) of currently
2271 # evaluating module
2272 set root_name_list [list]
2273 set mod [currentState modulename]
2274 foreach name [list $mod {*}[getAllModuleResolvedName $mod]] {
2275 appendNoDupToList root_name_list [lindex [file split $name] 0]
2276 }
2277
2278 # declare conflict over all these names
2279 conflict {*}$root_name_list
2280 }
2281
2282 proc sourceModfileCmd {itrp filename} {
2283 if {![info exists ::source_cache($filename)]} {
2284 set ::source_cache($filename) [readFile $filename]
2285 }
2286
2287 interp eval $itrp info script $filename
2288 interp eval $itrp $::source_cache($filename)
2289 interp eval $itrp info script [currentState modulefile]
2290 }
2291
2292 proc lsb-release {what} {
2293 return [switch -- $what {
2294 id {getState lsb_id}
2295 release {getState lsb_release}
2296 codename {getState lsb_codename}
2297 default {knerror "lsb-release $what not supported"}
2298 }]
2299 }
2300
2301 proc registerCurrentModuleUse {args} {
2302 if {[string length [currentState modulename]]} {
2303 setLoadedUse [currentState modulename] {*}$args
2304 }
2305 }
2306
2307 proc module-help {args} {
2308 lappend ::g_help_lines [join $args]
2309 }
2310
2311 proc getModuleHelpLines {} {
2312 if {[info exists ::g_help_lines]} {
2313 return $::g_help_lines
2314 }
2315 }
2316
2317 # convert property value as module tag (property name is ignored)
2318 proc add-property {name value} {
2319 set tag_list [split $value :]
2320 set mod [currentState modulename]
2321 foreach tag $tag_list {
2322 module-tag $tag $mod
2323 }
2324 }
2325
2326 proc module-warn {args} {
2327 # parse application criteria arguments to determine if command apply
2328 lassign [parseApplicationCriteriaArgs 1 0 {*}$args] apply isnearly after\
2329 otherargs
2330
2331 # parse remaining argument list, do it even if command does not apply to
2332 # raise any command specification error
2333 foreach arg $otherargs {
2334 if {[info exists nextargisval]} {
2335 ##nagelfar vartype nextargisval varName
2336 set $nextargisval $arg
2337 unset nextargisval
2338 } else {
2339 switch -glob -- $arg {
2340 --message {
2341 set nextargisval message
2342 }
2343 -* {
2344 knerror "Invalid option '$arg'"
2345 }
2346 default {
2347 lappend modarglist $arg
2348 }
2349 }
2350 set prevarg $arg
2351 }
2352 }
2353
2354 if {[info exists nextargisval]} {
2355 knerror "Missing value for '$prevarg' option"
2356 }
2357 if {![info exists message]} {
2358 knerror {No message specified in argument}
2359 }
2360 if {![info exists modarglist]} {
2361 knerror {No module specified in argument}
2362 }
2363
2364 # skip tag record if application criteria are not met
2365 if {$apply} {
2366 ##nagelfar ignore Found constant
2367 set proplist [list message $message]
2368 # record each hide spec after parsing them
2369 foreach modarg [parseModuleSpecification 0 0 0 0 {*}$modarglist] {
2370 setModspecTag $modarg warning $proplist
2371 }
2372 }
2373 }
2374
2375 proc provide {args} {
2376 if {![llength $args]} {
2377 knerror {No module specified in argument}
2378 }
2379 set current_mod [currentState modulename]
2380 foreach alias $args {
2381 setLoadedAltname $current_mod [list al $alias]
2382 }
2383 }
2384
2385 # ;;; Local Variables: ***
2386 # ;;; mode:tcl ***
2387 # ;;; End: ***
2388 # vim:set tabstop=3 shiftwidth=3 expandtab autoindent: