Debian Codegraph @

tcl/envmngt.tcl.in

raw
1 ##########################################################################
2
3 # ENVMNGT.TCL, environment management 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 proc incrErrorCount {} {
24 updateErrorCount [expr {[getState error_count] + 1}]
25 }
26
27 proc decrErrorCount {} {
28 updateErrorCount [expr {[getState error_count] - 1}]
29 }
30
31 proc updateErrorCount {count} {
32 # hold update of error count
33 if {[depthState reportholdid] > 0} {
34 lappend ::g_holdReport([currentState reportholdid]) [list\
35 updateErrorCount $count]
36 } else {
37 setState error_count $count
38 }
39 }
40
41 proc renderFalse {} {
42 if {[isStateDefined false_rendered] || ![isStateDefined shell]} {
43 return
44 }
45
46 # setup flag to render only once
47 setState false_rendered 1
48
49 # render a false value most of the time through a variable assignment
50 # that will be looked at in the shell module function calling
51 # modulecmd.tcl to return in turns a boolean status. Except for python
52 # and cmake, the value assigned to variable is also returned as the
53 # entire rendering status
54 switch -- [getState shelltype] {
55 sh - csh - fish {
56 # no need to set a variable on real shells as last statement
57 # result can easily be checked
58 lappend ::g_shcode_out {test 0 = 1;}
59 }
60 tcl {
61 lappend ::g_shcode_out {set _mlstatus 0;}
62 }
63 cmd {
64 lappend ::g_shcode_out {set errorlevel=1}
65 }
66 perl {
67 lappend ::g_shcode_out {{ no strict 'vars'; $_mlstatus = 0; }}
68 }
69 python {
70 lappend ::g_shcode_out {_mlstatus = False}
71 }
72 ruby {
73 lappend ::g_shcode_out {_mlstatus = false}
74 }
75 lisp {
76 lappend ::g_shcode_out {nil}
77 }
78 cmake {
79 lappend ::g_shcode_out {set(_mlstatus FALSE)}
80 }
81 r {
82 lappend ::g_shcode_out {mlstatus <- FALSE}
83 }
84 pwsh {
85 lappend ::g_shcode_out {Set-Variable -Name "_mlstatus" -Value $false\
86 -Scope Global}
87 }
88 }
89 }
90
91 proc renderTrue {} {
92 # render a true value most of the time through a variable assignment that
93 # will be looked at in the shell module function calling modulecmd.tcl to
94 # return in turns a boolean status. Except for python, cmake, and pwsh,
95 # the value assigned to variable is also returned as the full rendering
96 # status
97 switch -- [getState shelltype] {
98 sh - csh - fish {
99 # no need to set a variable on real shells as last statement
100 # result can easily be checked
101 lappend ::g_shcode_out {test 0;}
102 }
103 tcl {
104 lappend ::g_shcode_out {set _mlstatus 1;}
105 }
106 cmd {
107 lappend ::g_shcode_out {set errorlevel=0}
108 }
109 perl {
110 lappend ::g_shcode_out {{ no strict 'vars'; $_mlstatus = 1; }}
111 }
112 python {
113 lappend ::g_shcode_out {_mlstatus = True}
114 }
115 ruby {
116 lappend ::g_shcode_out {_mlstatus = true}
117 }
118 lisp {
119 lappend ::g_shcode_out {t}
120 }
121 cmake {
122 lappend ::g_shcode_out {set(_mlstatus TRUE)}
123 }
124 r {
125 lappend ::g_shcode_out {mlstatus <- TRUE}
126 }
127 pwsh {
128 lappend ::g_shcode_out {Set-Variable -Name "_mlstatus" -Value\
129 $true -Scope Global}
130 }
131 }
132 }
133
134 proc renderText {text} {
135 # render a text value most of the time through a variable assignment that
136 # will be looked at in the shell module function calling modulecmd.tcl to
137 # return in turns a string value.
138 switch -- [getState shelltype] {
139 sh - csh - fish {
140 foreach word $text {
141 # no need to set a variable on real shells, echoing text will make
142 # it available as result
143 lappend ::g_shcode_out "echo '$word';"
144 }
145 }
146 tcl {
147 lappend ::g_shcode_out "set _mlstatus \"$text\";"
148 }
149 cmd {
150 foreach word $text {
151 lappend ::g_shcode_out "echo $word"
152 }
153 }
154 perl {
155 lappend ::g_shcode_out "{ no strict 'vars'; \$_mlstatus = '$text'; }"
156 }
157 python {
158 lappend ::g_shcode_out "_mlstatus = '$text'"
159 }
160 ruby {
161 lappend ::g_shcode_out "_mlstatus = '$text'"
162 }
163 lisp {
164 lappend ::g_shcode_out "(message \"$text\")"
165 }
166 cmake {
167 lappend ::g_shcode_out "set(_mlstatus \"$text\")"
168 }
169 r {
170 lappend ::g_shcode_out "mlstatus <- '$text'"
171 }
172 pwsh {
173 lappend ::g_shcode_out "Set-Variable -Name \"_mlstatus\" -Value\
174 '$text' -Scope Global"
175 }
176 }
177 }
178
179 proc renderSettings {} {
180 global g_stateEnvVars g_stateAliases g_stateFunctions g_stateCompletes\
181 g_newXResources g_delXResources g_shcode_out
182
183 # preliminaries if there is stuff to render
184 if {[getState autoinit] || [array size g_stateEnvVars] || [array size\
185 g_stateAliases] || [array size g_newXResources] || [array size\
186 g_stateFunctions] || [array size g_stateCompletes] || [array size\
187 g_delXResources] || [info exists ::g_changeDir] || [info exists\
188 ::g_stdoutPuts] || [info exists ::g_prestdoutPuts] || [info exists\
189 ::g_return_text]} {
190 switch -- [getState shelltype] {
191 python {
192 lappend g_shcode_out {import os}
193 }
194 }
195 set has_rendered 1
196 } else {
197 set has_rendered 0
198 }
199
200 # send pre content deferred during modulefile interpretation
201 if {[info exists ::g_prestdoutPuts]} {
202 foreach {newline msg} $::g_prestdoutPuts {
203 append outmsg $msg
204 if {$newline} {
205 lappend g_shcode_out $outmsg
206 unset outmsg
207 }
208 }
209 # add last remaining message
210 if {[info exists outmsg]} {
211 lappend g_shcode_out $outmsg
212 }
213 }
214
215 if {[getState autoinit]} {
216 renderAutoinit
217 }
218
219 # filter Modules-specific environment variables for mod-to-sh subcmd
220 if {[getState modtosh_real_shell] ne {}} {
221 foreach globvar [getModulesEnvVarGlobList 1] {
222 foreach var [array names g_stateEnvVars -glob $globvar] {
223 unset g_stateEnvVars($var)
224 }
225 }
226 }
227
228 # new environment variables
229 foreach var [array names g_stateEnvVars] {
230 switch -- $g_stateEnvVars($var) {
231 new {
232 switch -- [getState shelltype] {
233 csh {
234 # cannot handle newline character in env var value with csh
235 # shells: chop newline character in value (as done on
236 # Modules v3 for all shells)
237 set val [string map {\n {}} $::env($var)]
238 set val [charEscaped $val]
239 # csh barfs on long env vars
240 if {[getState shell] eq {csh} && [string length $val] >\
241 [getConf csh_limit]} {
242 if {$var eq {PATH}} {
243 reportWarning "PATH exceeds [getConf csh_limit]\
244 characters, truncating and appending\
245 /usr/bin:/bin ..."
246 set val [string range $val 0 [getConf\
247 csh_limit]-1]:/usr/bin:/bin
248 } else {
249 reportWarning "$var exceeds [getConf csh_limit]\
250 characters, truncating..."
251 set val [string range $val 0 [getConf csh_limit]-1]
252 }
253 }
254 lappend g_shcode_out "setenv $var $val;"
255 }
256 sh {
257 set val [string map {' '\\''} $::env($var)]
258 lappend g_shcode_out "$var='$val'; export $var;"
259 }
260 fish {
261 set val [charEscaped $::env($var) ']
262 # fish shell has special treatment for PATH variable
263 # so its value should be provided as a list separated
264 # by spaces not by semi-colons
265 if {$var eq {PATH}} {
266 set val [join [split $val :] {' '}]
267 }
268 lappend g_shcode_out "set -xg $var '$val';"
269 }
270 tcl {
271 set val $::env($var)
272 lappend g_shcode_out "set ::env($var) {$val};"
273 }
274 cmd {
275 set val $::env($var)
276 lappend g_shcode_out "set $var=$val"
277 }
278 perl {
279 set val [charEscaped $::env($var) ']
280 lappend g_shcode_out "\$ENV{'$var'} = '$val';"
281 }
282 python {
283 set val [charEscaped $::env($var) ']
284 lappend g_shcode_out "os.environ\['$var'\] = '$val'"
285 }
286 ruby {
287 set val [charEscaped $::env($var) ']
288 lappend g_shcode_out "ENV\['$var'\] = '$val'"
289 }
290 lisp {
291 set val [charEscaped $::env($var) \"]
292 lappend g_shcode_out "(setenv \"$var\" \"$val\")"
293 }
294 cmake {
295 set val [charEscaped $::env($var) \"]
296 lappend g_shcode_out "set(ENV{$var} \"$val\")"
297 }
298 r {
299 set val [charEscaped $::env($var) {\\'}]
300 lappend g_shcode_out "Sys.setenv('$var'='$val')"
301 }
302 pwsh {
303 set val [charEscaped $::env($var) ']
304 lappend g_shcode_out "\$env:$var = '$val'"
305 }
306 }
307 }
308 del {
309 switch -- [getState shelltype] {
310 csh {
311 lappend g_shcode_out "unsetenv $var;"
312 }
313 sh {
314 lappend g_shcode_out "unset $var;"
315 }
316 fish {
317 lappend g_shcode_out "set -e $var;"
318 }
319 tcl {
320 lappend g_shcode_out "catch {unset ::env($var)};"
321 }
322 cmd {
323 lappend g_shcode_out "set $var="
324 }
325 perl {
326 lappend g_shcode_out "delete \$ENV{'$var'};"
327 }
328 python {
329 lappend g_shcode_out "os.environ\['$var'\] = ''"
330 lappend g_shcode_out "del os.environ\['$var'\]"
331 }
332 ruby {
333 lappend g_shcode_out "ENV\['$var'\] = nil"
334 }
335 lisp {
336 lappend g_shcode_out "(setenv \"$var\" nil)"
337 }
338 cmake {
339 lappend g_shcode_out "unset(ENV{$var})"
340 }
341 r {
342 lappend g_shcode_out "Sys.unsetenv('$var')"
343 }
344 pwsh {
345 lappend g_shcode_out "Remove-Item -Path env:$var\
346 -ErrorAction SilentlyContinue"
347 }
348 }
349 }
350 }
351 }
352
353 foreach var [array names g_stateAliases] {
354 switch -- $g_stateAliases($var) {
355 new {
356 set val $::g_Aliases($var)
357 # convert $n in !!:n and $* in !* on csh (like on compat version)
358 if {[getState shelltype] eq {csh}} {
359 regsub -all {([^\\]|^)\$([0-9]+)} $val {\1!!:\2} val
360 regsub -all {([^\\]|^)\$\*} $val {\1!*} val
361 }
362 # unescape \$ after now csh-specific conversion is over
363 regsub -all {\\\$} $val {$} val
364 switch -- [getState shelltype] {
365 csh {
366 set val [charEscaped $val]
367 lappend g_shcode_out "alias $var $val;"
368 }
369 sh {
370 set val [charEscaped $val]
371 lappend g_shcode_out "alias $var=$val;"
372 }
373 fish {
374 set val [charEscaped $val]
375 lappend g_shcode_out "alias $var $val;"
376 }
377 cmd {
378 lappend g_shcode_out "doskey $var=$val"
379 }
380 pwsh {
381 lappend g_shcode_out "function global:$var { $val }"
382 }
383 }
384 }
385 del {
386 switch -- [getState shelltype] {
387 csh {
388 lappend g_shcode_out "unalias $var;"
389 }
390 sh {
391 lappend g_shcode_out "unalias $var 2>/dev/null || true;"
392 }
393 fish {
394 lappend g_shcode_out "functions -e $var;"
395 }
396 cmd {
397 lappend g_shcode_out "doskey $var="
398 }
399 pwsh {
400 lappend g_shcode_out "Remove-Item -Path function:$var\
401 -ErrorAction SilentlyContinue"
402 }
403 }
404 }
405 }
406 }
407 foreach funcname [array names g_stateFunctions] {
408 switch -- $g_stateFunctions($funcname) {
409 new {
410 # trim function body to smoothly add a finishing ;
411 set val [string trim $::g_Functions($funcname) "; \t\n\r"]
412 switch -- [getState shell] {
413 sh - ksh - zsh {
414 lappend g_shcode_out "$funcname () { $val; };"
415 }
416 bash {
417 lappend g_shcode_out "$funcname () { $val; }; export -f\
418 $funcname;"
419 }
420 fish {
421 lappend g_shcode_out "function $funcname; $val; end;"
422 }
423 pwsh {
424 lappend g_shcode_out "function global:$funcname { $val }"
425 }
426 }
427 }
428 del {
429 switch -- [getState shelltype] {
430 sh {
431 lappend g_shcode_out "unset -f $funcname 2>/dev/null ||\
432 true;"
433 }
434 fish {
435 lappend g_shcode_out "functions -e $funcname;"
436 }
437 pwsh {
438 lappend g_shcode_out "Remove-Item -Path function:$funcname\
439 -ErrorAction SilentlyContinue"
440 }
441 }
442 }
443 }
444 }
445 foreach compname [array names g_stateCompletes] {
446 switch -- $g_stateCompletes($compname) {
447 new {
448 foreach {compshell body} $::g_Completes($compname) {
449 # skip definition not made for current shell
450 if {$compshell eq [getState shell]} {
451 switch -- [getState shell] {
452 bash {
453 lappend g_shcode_out "complete $body $compname;"
454 }
455 tcsh {
456 lappend g_shcode_out "complete $compname $body;"
457 }
458 fish {
459 # ensure pre-existing fish completion is cleared
460 if {![info exists fishcompclear($compname)]} {
461 lappend g_shcode_out "complete -e -c $compname;"
462 set fishcompclear($compname) 1
463 }
464 lappend g_shcode_out "complete -c $compname $body;"
465 }
466 pwsh {
467 lappend g_shcode_out "Register-ArgumentCompleter\
468 -CommandName $compname -ScriptBlock { $body }"
469 }
470 }
471 }
472 }
473 }
474 del {
475 switch -- [getState shell] {
476 bash {
477 lappend g_shcode_out "complete -r $compname;"
478 }
479 tcsh {
480 lappend g_shcode_out "uncomplete $compname;"
481 }
482 fish {
483 lappend g_shcode_out "complete -e -c $compname;"
484 }
485 pwsh {
486 lappend g_shcode_out "Unregister-ArgumentCompleter\
487 -CommandName $compname"
488 }
489 }
490 }
491 }
492 }
493
494 # preliminaries for x-resources stuff
495 if {[array size g_newXResources] || [array size g_delXResources]} {
496 switch -- [getState shelltype] {
497 python {
498 lappend g_shcode_out {import subprocess}
499 }
500 ruby {
501 lappend g_shcode_out {require 'open3'}
502 }
503 }
504 }
505
506 # new x resources
507 if {[array size g_newXResources]} {
508 # xrdb executable has already be verified in x-resource
509 set xrdb [getCommandPath xrdb]
510 foreach var [array names g_newXResources] {
511 set val $g_newXResources($var)
512 # empty val means that var is a file to parse
513 if {$val eq {}} {
514 switch -- [getState shelltype] {
515 sh - csh - fish {
516 lappend g_shcode_out "$xrdb -merge $var;"
517 }
518 tcl {
519 lappend g_shcode_out "exec $xrdb -merge $var;"
520 }
521 perl {
522 lappend g_shcode_out "system(\"$xrdb -merge $var\");"
523 }
524 python {
525 set var [charEscaped $var ']
526 lappend g_shcode_out "subprocess.Popen(\['$xrdb',\
527 '-merge', '$var'\])"
528 }
529 ruby {
530 set var [charEscaped $var ']
531 lappend g_shcode_out "Open3.popen2('$xrdb -merge $var')"
532 }
533 lisp {
534 lappend g_shcode_out "(shell-command-to-string \"$xrdb\
535 -merge $var\")"
536 }
537 cmake {
538 lappend g_shcode_out "execute_process(COMMAND $xrdb -merge\
539 $var)"
540 }
541 r {
542 set var [charEscaped $var {\\'}]
543 lappend g_shcode_out "system('$xrdb -merge $var')"
544 }
545 }
546 } else {
547 switch -- [getState shelltype] {
548 sh - csh - fish {
549 set var [charEscaped $var \"]
550 set val [charEscaped $val \"]
551 lappend g_shcode_out "echo \"$var: $val\" | $xrdb -merge;"
552 }
553 tcl {
554 lappend g_shcode_out "set XRDBPIPE \[open \"|$xrdb -merge\"\
555 r+\];"
556 set var [charEscaped $var \"]
557 set val [charEscaped $val \"]
558 lappend g_shcode_out "puts \$XRDBPIPE \"$var: $val\";"
559 lappend g_shcode_out {close $XRDBPIPE;}
560 lappend g_shcode_out {unset XRDBPIPE;}
561 }
562 perl {
563 lappend g_shcode_out "open(XRDBPIPE, \"|$xrdb -merge\");"
564 set var [charEscaped $var \"]
565 set val [charEscaped $val \"]
566 lappend g_shcode_out "print XRDBPIPE \"$var: $val\\n\";"
567 lappend g_shcode_out {close XRDBPIPE;}
568 }
569 python {
570 set var [charEscaped $var ']
571 set val [charEscaped $val ']
572 lappend g_shcode_out "subprocess.Popen(\['$xrdb',\
573 '-merge'\],\
574 stdin=subprocess.PIPE).communicate(input='$var:\
575 $val\\n')"
576 }
577 ruby {
578 set var [charEscaped $var ']
579 set val [charEscaped $val ']
580 lappend g_shcode_out "Open3.popen2('$xrdb -merge') {|i,o,t|\
581 i.puts '$var: $val'}"
582 }
583 lisp {
584 lappend g_shcode_out "(shell-command-to-string \"echo $var:\
585 $val | $xrdb -merge\")"
586 }
587 cmake {
588 set var [charEscaped $var \"]
589 set val [charEscaped $val \"]
590 lappend g_shcode_out "execute_process(COMMAND echo \"$var:\
591 $val\" COMMAND $xrdb -merge)"
592 }
593 r {
594 set var [charEscaped $var {\\'}]
595 set val [charEscaped $val {\\'}]
596 lappend g_shcode_out "system('$xrdb -merge', input='$var:\
597 $val')"
598 }
599 }
600 }
601 }
602 }
603
604 if {[array size g_delXResources]} {
605 ##nagelfar ignore Found constant
606 set xrdb [getCommandPath xrdb]
607 set xres_to_del {}
608 foreach var [array names g_delXResources] {
609 # empty val means that var is a file to parse
610 if {$g_delXResources($var) eq {}} {
611 # xresource file has to be parsed to find what resources
612 # are declared there and need to be unset
613 foreach fline [split [exec $xrdb -n load $var] \n] {
614 lappend xres_to_del [lindex [split $fline :] 0]
615 }
616 } else {
617 lappend xres_to_del $var
618 }
619 }
620
621 # xresource strings are unset by emptying their value since there
622 # is no command of xrdb that can properly remove one property
623 switch -- [getState shelltype] {
624 sh - csh - fish {
625 foreach var $xres_to_del {
626 lappend g_shcode_out "echo \"$var:\" | $xrdb -merge;"
627 }
628 }
629 tcl {
630 foreach var $xres_to_del {
631 lappend g_shcode_out "set XRDBPIPE \[open \"|$xrdb -merge\"\
632 r+\];"
633 set var [charEscaped $var \"]
634 lappend g_shcode_out "puts \$XRDBPIPE \"$var:\";"
635 lappend g_shcode_out {close $XRDBPIPE;}
636 lappend g_shcode_out {unset XRDBPIPE;}
637 }
638 }
639 perl {
640 foreach var $xres_to_del {
641 lappend g_shcode_out "open(XRDBPIPE, \"|$xrdb -merge\");"
642 set var [charEscaped $var \"]
643 lappend g_shcode_out "print XRDBPIPE \"$var:\\n\";"
644 lappend g_shcode_out {close XRDBPIPE;}
645 }
646 }
647 python {
648 foreach var $xres_to_del {
649 set var [charEscaped $var ']
650 lappend g_shcode_out "subprocess.Popen(\['$xrdb', '-merge'\],\
651 stdin=subprocess.PIPE).communicate(input='$var:\\n')"
652 }
653 }
654 ruby {
655 foreach var $xres_to_del {
656 set var [charEscaped $var ']
657 lappend g_shcode_out "Open3.popen2('$xrdb -merge') {|i,o,t|\
658 i.puts '$var:'}"
659 }
660 }
661 lisp {
662 foreach var $xres_to_del {
663 lappend g_shcode_out "(shell-command-to-string \"echo $var: |\
664 $xrdb -merge\")"
665 }
666 }
667 cmake {
668 foreach var $xres_to_del {
669 set var [charEscaped $var \"]
670 lappend g_shcode_out "execute_process(COMMAND echo \"$var:\"\
671 COMMAND $xrdb -merge)"
672 }
673 }
674 r {
675 foreach var $xres_to_del {
676 set var [charEscaped $var {\\'}]
677 lappend g_shcode_out "system('$xrdb -merge', input='$var:')"
678 }
679 }
680 }
681 }
682
683 if {[info exists ::g_changeDir]} {
684 switch -- [getState shelltype] {
685 sh - csh - fish {
686 lappend g_shcode_out "cd '$::g_changeDir';"
687 }
688 tcl {
689 lappend g_shcode_out "cd \"$::g_changeDir\";"
690 }
691 cmd {
692 lappend g_shcode_out "cd $::g_changeDir"
693 }
694 perl {
695 lappend g_shcode_out "chdir '$::g_changeDir';"
696 }
697 python {
698 lappend g_shcode_out "os.chdir('$::g_changeDir')"
699 }
700 ruby {
701 lappend g_shcode_out "Dir.chdir('$::g_changeDir')"
702 }
703 lisp {
704 lappend g_shcode_out "(shell-command-to-string \"cd\
705 '$::g_changeDir'\")"
706 }
707 r {
708 lappend g_shcode_out "setwd('$::g_changeDir')"
709 }
710 pwsh {
711 lappend g_shcode_out "Set-Location '$::g_changeDir'"
712 }
713 }
714 # cannot change current directory of cmake "shell"
715 }
716
717 # send content deferred during modulefile interpretation
718 if {[info exists ::g_stdoutPuts]} {
719 foreach {newline msg} $::g_stdoutPuts {
720 append outmsg $msg
721 if {$newline} {
722 lappend g_shcode_out $outmsg
723 unset outmsg
724 }
725 }
726 # add last remaining message
727 if {[info exists outmsg]} {
728 lappend g_shcode_out $outmsg
729 }
730 }
731
732 # if currently processing mod-to-sh subcmd, send shell code to the message
733 # channel then reset code and shell state to get evaluation result shell
734 # code on stdout channel
735 if {[getState modtosh_real_shell] ne {}} {
736 if {[info exists g_shcode_out]} {
737 report [join $::g_shcode_out \n]
738 unset g_shcode_out
739 }
740
741 setState shell [getState modtosh_real_shell]
742 unsetState shelltype
743 }
744
745 # return text value if defined even if error happened
746 if {[info exists ::g_return_text]} {
747 reportDebug {text value should be returned.}
748 renderText $::g_return_text
749 } elseif {[getState error_count] > 0} {
750 reportDebug "[getState error_count] error(s) detected."
751 renderFalse
752 } elseif {[getState return_false]} {
753 reportDebug {false value should be returned.}
754 renderFalse
755 } elseif {$has_rendered} {
756 # finish with true statement if something has been put
757 renderTrue
758 }
759 }
760
761 # Output all gathered shell code to stdout. This is a separate proc rather the
762 # final code of renderSettings as such output is also done when exiting after
763 # an error. Stdout is flushed from flushAndExit proc
764 proc renderFlush {} {
765 if {[info exists ::g_shcode_out]} {
766 # required to work on cygwin, shouldn't hurt real linux
767 fconfigure stdout -translation lf
768
769 puts stdout [join $::g_shcode_out \n]
770 }
771 }
772
773 proc renderAutoinit {} {
774 # automatically detect which tclsh should be used for
775 # future module commands
776 set tclshbin [info nameofexecutable]
777
778 # ensure script path is absolute
779 set ::argv0 [getAbsolutePath $::argv0]
780
781 set is_mogui_avail [string length [getCommandPath mogui-cmd]]
782
783 ##nagelfar ignore #482 Close brace not aligned with line
784 switch -- [getState shelltype] {
785 csh {
786 set pre_hi {set _histchars = $histchars; unset histchars;}
787 set post_hi {set histchars = $_histchars; unset _histchars;}
788 set pre_pr {set _prompt=$prompt:q; set prompt="";}
789 set post_pr {set prompt=$_prompt:q; unset _prompt;}
790 # apply workaround for Tcsh history if set
791 set eval_cmd [expr {[getConf wa_277] ? "eval `$tclshbin\
792 '\"'\"'$::argv0'\"'\"' [getState shell] \\!*`;" : "eval\
793 \"`$tclshbin '\"'\"'$::argv0'\"'\"' [getState shell] \\!*:q`\";"}]
794 set pre_ex {set _exit="$status";}
795 set post_ex {test 0 = $_exit}
796
797 set fdef "if ( \$?histchars && \$?prompt )\
798 alias module '$pre_hi $pre_pr $eval_cmd $pre_ex $post_hi $post_pr $post_ex' ;
799 if ( \$?histchars && ! \$?prompt )\
800 alias module '$pre_hi $eval_cmd $pre_ex $post_hi $post_ex' ;
801 if ( ! \$?histchars && \$?prompt )\
802 alias module '$pre_pr $eval_cmd $pre_ex $post_pr $post_ex' ;
803 if ( ! \$?histchars && ! \$?prompt ) alias module '$eval_cmd' ;"
804 if {[getConf ml]} {
805 append fdef {
806 alias ml 'module ml \!*' ;}
807 }
808 if {$is_mogui_avail} {
809 append fdef "\nalias mogui 'eval \"`mogui-cmd [getState shell]\
810 \\!*:q`\"' ;"
811 }
812 }
813 sh {
814 # Considering the diversity of ways local variables are handled
815 # through the sh-variants ('local' known everywhere except on ksh,
816 # 'typeset' known everywhere except on pure-sh, and on some systems
817 # the pure-sh is in fact a 'ksh'), no local variables are defined and
818 # these variables that should have been local are unset at the end
819
820 # on zsh, word splitting should be enabled explicitly
821 set wsplit [expr {[getState shell] eq {zsh} ? {^^=} : {}}]
822 # build quarantine mechanism in module function
823 # an empty runtime variable is set even if no corresponding
824 # MODULES_RUNENV_* variable found, as var cannot be unset on
825 # modified environment command-line
826 set fdef "_module_raw() {"
827 if {[getConf silent_shell_debug]} {
828 append fdef {
829 unset _mlshdbg;
830 if [ "${MODULES_SILENT_SHELL_DEBUG:-0}" = '1' ]; then
831 case "$-" in
832 *v*x*) set +vx; _mlshdbg='vx' ;;
833 *v*) set +v; _mlshdbg='v' ;;
834 *x*) set +x; _mlshdbg='x' ;;
835 *) _mlshdbg='' ;;
836 esac;
837 fi;}
838 }
839 if {[getConf quarantine_support]} {
840 append fdef "
841 unset _mlre _mlIFS;
842 if \[ -n \"\${IFS+x}\" \]; then
843 _mlIFS=\$IFS;
844 fi;
845 IFS=' ';
846 for _mlv in \${${wsplit}MODULES_RUN_QUARANTINE:-}; do"
847 ##nagelfar ignore #4 Too long line
848 append fdef {
849 if [ "${_mlv}" = "${_mlv##*[!A-Za-z0-9_]}" ] && [ "${_mlv}" = "${_mlv#[0-9]}" ]; then
850 if [ -n "$(eval 'echo ${'"$_mlv"'+x}')" ]; then
851 _mlre="${_mlre:-}__MODULES_QUAR_${_mlv}='$(eval 'echo ${'"$_mlv"'}')' ";
852 fi;
853 _mlrv="MODULES_RUNENV_${_mlv}";
854 _mlre="${_mlre:-}${_mlv}='$(eval 'echo ${'"$_mlrv"':-}')' ";
855 fi;
856 done;
857 if [ -n "${_mlre:-}" ]; then
858 _mlre="${_mlre:-}__MODULES_QUARANTINE_SET=1 ";}
859 append fdef "\n eval \"\$(eval \${${wsplit}_mlre} $tclshbin\
860 '$::argv0' [getState shell] '\"\$@\"')\";
861 else
862 eval \"\$($tclshbin '$::argv0' [getState shell] \"\$@\")\";
863 fi;"
864 } else {
865 append fdef "
866 eval \"\$($tclshbin '$::argv0' [getState shell] \"\$@\")\";"
867 }
868 append fdef {
869 _mlstatus=$?;}
870 if {[getConf quarantine_support]} {
871 append fdef {
872 if [ -n "${_mlIFS+x}" ]; then
873 IFS=$_mlIFS;
874 else
875 unset IFS;
876 fi;
877 unset _mlre _mlv _mlrv _mlIFS;}
878 }
879 if {[getConf silent_shell_debug]} {
880 append fdef {
881 if [ -n "${_mlshdbg:-}" ]; then
882 set -"$_mlshdbg";
883 fi;
884 unset _mlshdbg;}
885 }
886 append fdef {
887 return $_mlstatus;}
888 # define both _module_raw and module functions in any cases to allow
889 # content redirection when command-line switch is used (--redirect or
890 # --no-redirect)
891 # content is redirected by default when shell session is attached to
892 # a terminal (non-terminal session are not redirected to avoid
893 # breaking things like scp or sftp transfer)
894 # use local/typeset variable in this context as we cannot unset it
895 # afterward (since _module_raw should be the cmd to return status)
896 set localcmd [expr {[getState shell] eq {ksh} ? {typeset} : {local}}]
897 ##nagelfar ignore Unescaped close brace
898 append fdef "\n};\nmodule() {
899 $localcmd _mlredir=[getState is_stderr_tty];\n"
900 append fdef { if [ -n "${MODULES_REDIRECT_OUTPUT+x}" ]; then
901 if [ "$MODULES_REDIRECT_OUTPUT" = '0' ]; then
902 _mlredir=0;
903 elif [ "$MODULES_REDIRECT_OUTPUT" = '1' ]; then
904 _mlredir=1;
905 fi;
906 fi;
907 case " $@ " in
908 *' --no-redirect '*) _mlredir=0 ;;
909 *' --redirect '*) _mlredir=1 ;;
910 esac;
911 if [ $_mlredir -eq 0 ]; then
912 _module_raw "$@";
913 else
914 _module_raw "$@" 2>&1;
915 fi;}
916 append fdef "\n};"
917 if {[getState shell] eq {bash}} {
918 append fdef {
919 export -f _module_raw;
920 export -f module;}
921 }
922 if {[getConf ml]} {
923 append fdef {
924 ml() { module ml "$@"; };}
925 if {[getState shell] eq {bash}} {
926 append fdef {
927 export -f ml;}
928 }
929 }
930 if {$is_mogui_avail} {
931 append fdef "\nmogui() { eval \"\$(mogui-cmd [getState shell]\
932 \"\$@\")\"; };"
933 if {[getState shell] eq {bash}} {
934 append fdef {
935 export -f mogui;}
936 }
937 }
938 }
939 fish {
940 set fdef "function _module_raw\n"
941 if {[getConf quarantine_support]} {
942 append fdef { set -l _mlre ''; set -l _mlv; set -l _mlrv;
943 for _mlv in (string split ' ' $MODULES_RUN_QUARANTINE)
944 if string match -r '^[A-Za-z_][A-Za-z0-9_]*$' $_mlv >/dev/null
945 if set -q $_mlv
946 set _mlre $_mlre"__MODULES_QUAR_"$_mlv"='$$_mlv' "
947 end
948 set _mlrv "MODULES_RUNENV_$_mlv"
949 set _mlre "$_mlre$_mlv='$$_mlrv' "
950 end
951 end
952 if [ -n "$_mlre" ]
953 set _mlre "env $_mlre __MODULES_QUARANTINE_SET=1"
954 end}
955 # use "| source -" rather than "eval" to be able
956 # to redirect stderr after stdout being evaluated
957 append fdef "\n eval \$_mlre $tclshbin \\'$::argv0\\' [getState\
958 shell] (string escape -- \$argv) | source -\n"
959 } else {
960 append fdef " eval $tclshbin \\'$::argv0\\' [getState shell]\
961 (string escape -- \$argv) | source -\n"
962 }
963 append fdef "end
964 function module
965 set _mlredir [getState is_stderr_tty]
966 if set -q MODULES_REDIRECT_OUTPUT
967 if \[ \"\$MODULES_REDIRECT_OUTPUT\" = '0' \]
968 set _mlredir 0
969 else if \[ \"\$MODULES_REDIRECT_OUTPUT\" = '1' \]
970 set _mlredir 1
971 end
972 end
973 if contains -- --no-redirect \$argv; or begin ; \[ \$_mlredir -eq 0\
974 \]; and not contains -- --redirect \$argv ; end
975 _module_raw \$argv
976 else
977 _module_raw \$argv 2>&1
978 end
979 end"
980 if {[getConf ml]} {
981 append fdef {
982 function ml
983 module ml $argv
984 end}
985 }
986 if {$is_mogui_avail} {
987 append fdef {
988 function mogui
989 eval mogui-cmd fish (string escape -- $argv) | source -
990 end}
991 }
992 }
993 tcl {
994 set fdef "proc module {args} {"
995 if {[getConf quarantine_support]} {
996 append fdef {
997 set _mlre {};
998 if {[info exists ::env(MODULES_RUN_QUARANTINE)]} {
999 foreach _mlv [split $::env(MODULES_RUN_QUARANTINE) " "] {
1000 if {[regexp {^[A-Za-z_][A-Za-z0-9_]*$} $_mlv]} {
1001 if {[info exists ::env($_mlv)]} {
1002 lappend _mlre "__MODULES_QUAR_${_mlv}=$::env($_mlv)"
1003 }
1004 set _mlrv "MODULES_RUNENV_${_mlv}"
1005 lappend _mlre [expr {[info exists ::env($_mlrv)] ?\
1006 "${_mlv}=$::env($_mlrv)" : "${_mlv}="}]
1007 }
1008 }
1009 if {[llength $_mlre]} {
1010 lappend _mlre "__MODULES_QUARANTINE_SET=1"
1011 set _mlre [linsert $_mlre 0 "env"]
1012 }
1013 }}
1014 }
1015 append fdef {
1016 set _mlstatus 1;}
1017 if {[getConf quarantine_support]} {
1018 append fdef "\n catch {exec {*}\$_mlre \"$tclshbin\"\
1019 \"$::argv0\" \"[getState shell]\" {*}\$args 2>@stderr}\
1020 script\n"
1021 } else {
1022 append fdef "\n catch {exec \"$tclshbin\" \"$::argv0\"\
1023 \"[getState shell]\" {*}\$args 2>@stderr} script\n"
1024 }
1025 append fdef { eval $script;
1026 return $_mlstatus}
1027 append fdef "\n}"
1028 if {[getConf ml]} {
1029 append fdef {
1030 proc ml {args} {
1031 return [module ml {*}$args]
1032 }}
1033 }
1034 }
1035 cmd {
1036 reportErrorAndExit {No autoinit mode available for 'cmd' shell}
1037 }
1038 perl {
1039 set fdef "sub module {"
1040 if {[getConf quarantine_support]} {
1041 append fdef {
1042 my $_mlre = '';
1043 if (defined $ENV{'MODULES_RUN_QUARANTINE'}) {
1044 foreach my $_mlv (split(' ', $ENV{'MODULES_RUN_QUARANTINE'})) {
1045 if ($_mlv =~ /^[A-Za-z_][A-Za-z0-9_]*$/) {
1046 if (defined $ENV{$_mlv}) {
1047 $_mlre .= "__MODULES_QUAR_${_mlv}='$ENV{$_mlv}' ";
1048 }
1049 my $_mlrv = "MODULES_RUNENV_$_mlv";
1050 $_mlre .= "$_mlv='$ENV{$_mlrv}' ";
1051 }
1052 }
1053 if ($_mlre ne "") {
1054 $_mlre = "env ${_mlre}__MODULES_QUARANTINE_SET=1 ";
1055 }
1056 }}
1057 }
1058 append fdef {
1059 my $args = '';
1060 if (@_ > 0) {
1061 $args = '"' . join('" "', @_) . '"';
1062 }
1063 my $_mlstatus = 1;}
1064 if {[getConf quarantine_support]} {
1065 append fdef "\n eval `\${_mlre}$tclshbin '$::argv0' perl\
1066 \$args`;\n"
1067 } else {
1068 append fdef "\n eval `$tclshbin '$::argv0' perl \$args`;\n"
1069 }
1070 append fdef { return $_mlstatus;}
1071 append fdef "\n}"
1072 if {[getConf ml]} {
1073 append fdef {
1074 sub ml {
1075 return module('ml', @_);
1076 }}
1077 }
1078 }
1079 python {
1080 set fdef {import sys, re, subprocess
1081 def module(*arguments):}
1082 if {[getConf quarantine_support]} {
1083 append fdef {
1084 _mlre = os.environ.copy()
1085 if 'MODULES_RUN_QUARANTINE' in os.environ:
1086 for _mlv in os.environ['MODULES_RUN_QUARANTINE'].split():
1087 if re.match('^[A-Za-z_][A-Za-z0-9_]*$', _mlv):
1088 if _mlv in os.environ:
1089 _mlre['__MODULES_QUAR_' + _mlv] = os.environ[_mlv]
1090 _mlrv = 'MODULES_RUNENV_' + _mlv
1091 if _mlrv in os.environ:
1092 _mlre[_mlv] = os.environ[_mlrv]
1093 else:
1094 _mlre[_mlv] = ''
1095 _mlre['__MODULES_QUARANTINE_SET'] = '1'}
1096 }
1097 append fdef {
1098 ns = {}}
1099 if {[getConf quarantine_support]} {
1100 append fdef "\n out, err = subprocess.Popen(\['$tclshbin',\
1101 '$::argv0', 'python'\] + list(arguments),\
1102 stdout=subprocess.PIPE, stderr=subprocess.PIPE,\
1103 env=_mlre).communicate()\n"
1104 } else {
1105 append fdef "\n out, err = subprocess.Popen(\['$tclshbin',\
1106 '$::argv0', 'python'\] + list(arguments),\
1107 stdout=subprocess.PIPE,\
1108 stderr=subprocess.PIPE).communicate()\n"
1109 }
1110 append fdef { exec(out, ns)
1111 if '_mlstatus' in ns:
1112 _mlstatus = ns['_mlstatus']
1113 else:
1114 _mlstatus = True
1115 if err.decode():
1116 print(err.decode(), end='', file=sys.stderr)
1117 return _mlstatus}
1118 if {[getConf ml]} {
1119 append fdef {
1120 def ml(*arguments):
1121 return module('ml', *arguments)
1122 }
1123 }
1124 }
1125 ruby {
1126 set fdef {class ENVModule
1127 def ENVModule.module(*args)}
1128 if {[getConf quarantine_support]} {
1129 ##nagelfar ignore +7 Too long line
1130 append fdef {
1131 _mlre = ''
1132 if ENV.has_key?('MODULES_RUN_QUARANTINE') then
1133 ENV['MODULES_RUN_QUARANTINE'].split(' ').each do |_mlv|
1134 if _mlv =~ /^[A-Za-z_][A-Za-z0-9_]*$/ then
1135 if ENV.has_key?(_mlv) then
1136 _mlre << "__MODULES_QUAR_" + _mlv + "='" + ENV[_mlv].to_s + "' "
1137 end
1138 _mlrv = 'MODULES_RUNENV_' + _mlv
1139 _mlre << _mlv + "='" + ENV[_mlrv].to_s + "' "
1140 end
1141 end
1142 unless _mlre.empty?
1143 _mlre = 'env ' + _mlre + '__MODULES_QUARANTINE_SET=1 '
1144 end
1145 end}
1146 }
1147 append fdef {
1148 if args[0].kind_of?(Array) then
1149 args = args[0]
1150 end
1151 if args.length == 0 then
1152 args = ''
1153 else
1154 args = "\"#{args.join('" "')}\""
1155 end
1156 _mlstatus = true}
1157 if {[getConf quarantine_support]} {
1158 ##nagelfar ignore +2 Suspicious # char
1159 append fdef "\n eval `#{_mlre}$tclshbin '$::argv0' ruby\
1160 #{args}`\n"
1161 } else {
1162 append fdef "\n eval `$tclshbin '$::argv0' ruby #{args}`\n"
1163 }
1164 append fdef { return _mlstatus
1165 end}
1166 if {[getConf ml]} {
1167 append fdef {
1168 def ENVModule.ml(*args)
1169 return ENVModule.module('ml', *args)
1170 end}
1171 }
1172 append fdef {
1173 end}
1174 }
1175 lisp {
1176 reportErrorAndExit {lisp mode autoinit not yet implemented}
1177 }
1178 cmake {
1179 if {[getConf quarantine_support]} {
1180 set pre_exec "COMMAND \${_mlre} $tclshbin \\\"$::argv0\\\" cmake"
1181 } else {
1182 set pre_exec "COMMAND $tclshbin \\\"$::argv0\\\" cmake"
1183 }
1184 set fdef {function(module)
1185 cmake_policy(SET CMP0007 NEW)}
1186 if {[getConf quarantine_support]} {
1187 append fdef {
1188 set(_mlre "")
1189 if(DEFINED ENV{MODULES_RUN_QUARANTINE})
1190 string(REPLACE " " ";" _mlv_list "$ENV{MODULES_RUN_QUARANTINE}")
1191 foreach(_mlv ${_mlv_list})
1192 if(${_mlv} MATCHES "^[A-Za-z_][A-Za-z0-9_]*$")
1193 if(DEFINED ENV{${_mlv}})
1194 string(APPEND _mlre
1195 " [===[__MODULES_QUAR_${_mlv}=$ENV{${_mlv}}]===]")
1196 endif()
1197 set(_mlrv "MODULES_RUNENV_${_mlv}")
1198 string(APPEND _mlre " [===[${_mlv}=$ENV{${_mlrv}}]===]")
1199 endif()
1200 endforeach()
1201 if (NOT "${_mlre}" STREQUAL "")
1202 set(_mlre "env ${_mlre} __MODULES_QUARANTINE_SET=1")
1203 endif()
1204 endif()}
1205 }
1206 append fdef {
1207 set(_mlstatus TRUE)
1208 execute_process(COMMAND mktemp -t moduleinit.cmake.XXXXXXXXXXXX
1209 OUTPUT_VARIABLE tempfile_name
1210 OUTPUT_STRIP_TRAILING_WHITESPACE)
1211 }
1212 append fdef " set(quotedArgs \"$pre_exec\")"
1213 append fdef {
1214 cmake_parse_arguments(PARSE_ARGV 0 FWD "" "" "")
1215 foreach(arg IN LISTS FWD_UNPARSED_ARGUMENTS)
1216 string(APPEND quotedArgs " [===[${arg}]===]")
1217 endforeach()
1218 string(APPEND quotedArgs " OUTPUT_FILE ${tempfile_name}")
1219 cmake_language(EVAL CODE "execute_process(${quotedArgs})")
1220 }
1221 append fdef { if(EXISTS ${tempfile_name})
1222 include(${tempfile_name})
1223 file(REMOVE ${tempfile_name})
1224 endif()
1225 set(module_result ${_mlstatus} PARENT_SCOPE)
1226 endfunction(module)}
1227 if {[getConf ml]} {
1228 append fdef {
1229 function(ml)
1230 module(ml ${ARGV})
1231 set(module_result ${module_result} PARENT_SCOPE)
1232 endfunction(ml)}
1233 }
1234 }
1235 r {
1236 set fdef "module <- function(...){"
1237 if {[getConf quarantine_support]} {
1238 ##nagelfar ignore +7 Too long line
1239 append fdef {
1240 mlre <- ''
1241 if (!is.na(Sys.getenv('MODULES_RUN_QUARANTINE', unset=NA))) {
1242 for (mlv in strsplit(Sys.getenv('MODULES_RUN_QUARANTINE'), ' ')[[1]]) {
1243 if (grepl('^[A-Za-z_][A-Za-z0-9_]*$', mlv)) {
1244 if (!is.na(Sys.getenv(mlv, unset=NA))) {
1245 mlre <- paste0(mlre, "__MODULES_QUAR_", mlv, "='", Sys.getenv(mlv), "' ")
1246 }
1247 mlrv <- paste0('MODULES_RUNENV_', mlv)
1248 mlre <- paste0(mlre, mlv, "='", Sys.getenv(mlrv), "' ")
1249 }
1250 }
1251 if (mlre != '') {
1252 mlre <- paste0('env ', mlre, '__MODULES_QUARANTINE_SET=1 ')
1253 }
1254 }}
1255 }
1256 append fdef {
1257 arglist <- as.list(match.call())
1258 arglist[1] <- 'r'
1259 args <- paste0('"', paste0(arglist, collapse='" "'), '"')}
1260 if {[getConf quarantine_support]} {
1261 append fdef "\n cmd <- paste(mlre, '$tclshbin', '\"$::argv0\"',\
1262 args, sep=' ')\n"
1263 } else {
1264 append fdef "\n cmd <- paste('$tclshbin', '\"$::argv0\"', args,\
1265 sep=' ')\n"
1266 }
1267 append fdef { mlstatus <- TRUE
1268 hndl <- pipe(cmd)
1269 eval(expr = parse(file=hndl))
1270 close(hndl)
1271 invisible(mlstatus)}
1272 append fdef "\n}"
1273 if {[getConf ml]} {
1274 append fdef {
1275 ml <- function(...){
1276 module('ml', ...)
1277 }}
1278 }
1279 }
1280 pwsh {
1281 if {[getState is_win]} {
1282 reportErrorAndExit {No autoinit mode available for 'pwsh' shell\
1283 on Windows}
1284 }
1285
1286 set fdef "function global:_envmodule_common {"
1287 append fdef {
1288 param([Parameter(ValueFromRemainingArguments)] [string[]] $allargs)
1289 $global:_mlstatus = $true
1290 $cmd_is_query = "$allargs" -match '(is-loaded|is-avail|is-used|is-saved)'}
1291 if {[getConf quarantine_support]} {
1292 append fdef {
1293 $_mlre_set = ''
1294 $_mlre_reset = ''
1295 if ($env:MODULES_RUN_QUARANTINE) {
1296 foreach ($_mlv in $env:MODULES_RUN_QUARANTINE -split ' ') {
1297 if ($_mlv -match '^[A-Za-z_][A-Za-z0-9_]*$') {
1298 $_mlv_value = [System.Environment]::GetEnvironmentVariable($_mlv)
1299 if ($_mlv_value) {
1300 $_mlre_set += "`$env:__MODULES_QUAR_${_mlv}='$_mlv_value';"
1301 $_mlre_reset = "Remove-Item -Path env:__MODULES_QUAR_${_mlv};"\
1302 + $_mlre_reset
1303 }
1304 $_mlrv = "MODULES_RUNENV_$_mlv"
1305 $_mlrv_value =\
1306 [System.Environment]::GetEnvironmentVariable($_mlrv)
1307 $_mlre_set += "`$env:$_mlv='$_mlrv_value';"
1308 $_mlre_reset = "`$env:$_mlv=`"`$env:__MODULES_QUAR_${_mlv}`";"\
1309 + $_mlre_reset
1310 }
1311 }
1312 if ($_mlre_set -ne '') {
1313 $_mlre_set += "`$env:__MODULES_QUARANTINE_SET=1"
1314 $_mlre_reset += "Remove-Item -Path env:__MODULES_QUARANTINE_SET"
1315 }
1316 }
1317 if ($_mlre_set -ne '') {
1318 Invoke-Expression "$_mlre_set"
1319 Remove-Variable "_mlre_set"
1320 }}
1321 }
1322 append fdef {
1323 $output = }
1324 append fdef "& \"$tclshbin\" \"$::argv0\" pwsh \$allargs 2>&1"
1325 if {[getConf quarantine_support]} {
1326 append fdef {
1327 if ($_mlre_reset -ne '') {
1328 Invoke-Expression "$_mlre_reset"
1329 Remove-Variable "_mlre_reset"
1330 }}
1331 }
1332 append fdef {
1333 $outmsg = ($output | ? {$_.gettype().Name -ne "ErrorRecord"}) -join "`n"
1334 $errmsg = ($output | ? {$_.gettype().Name -eq "ErrorRecord"}) -join "`n"
1335 $errmsg = $errmsg.replace(
1336 "System.Management.Automation.RemoteException", ""
1337 )
1338 if ($outmsg) {
1339 Invoke-Expression $outmsg
1340 }
1341 if (($_mlstatus -eq $false) -and (!$cmd_is_query)) {
1342 $global:LastExitCode = 1
1343 } else {
1344 $global:LastExitCode = 0
1345 }}
1346 append fdef "\n \$mlredir = \[bool\][getState is_stderr_tty]"
1347 append fdef {
1348 if ($env:MODULES_REDIRECT_OUTPUT -ne $null) {
1349 if ($env:MODULES_REDIRECT_OUTPUT -eq '0') {
1350 $mlredir = $false
1351 } elseif ($env:MODULES_REDIRECT_OUTPUT -eq '1') {
1352 $mlredir = $true
1353 }
1354 }
1355 if ("$allargs" -match '--no-redirect') {
1356 $mlredir = $false
1357 } elseif ("$allargs" -match '--redirect') {
1358 $mlredir = $true
1359 }
1360 if ($errmsg) {
1361 if ($_mlstatus -eq $false) {
1362 $global:LastExitCode = 1
1363 } else {
1364 if ($mlredir) {
1365 [Console]::WriteLine("$errmsg")
1366 } else {
1367 [Console]::Error.WriteLine("$errmsg")
1368 }
1369 $errmsg = $null
1370 }
1371 }
1372 if ((($_mlstatus -ne $true) -and ($_mlstatus -ne $false)) -or\
1373 ($cmd_is_query)) {
1374 return $errmsg,$_mlstatus
1375 }
1376 return $errmsg,$null}
1377 append fdef "\n}\nfunction global:envmodule {"
1378 append fdef {
1379 param([Parameter(ValueFromRemainingArguments)] [string[]] $allargs)
1380 $errmsg,$retmsg = & _envmodule_common $allargs
1381 if ("$errmsg" -ne "") {
1382 $PSCmdlet.ThrowTerminatingError(
1383 [System.Management.Automation.ErrorRecord]::new(
1384 ([System.Exception]"$errmsg"),
1385 'error while running modulecmd.tcl via envmodule',
1386 [System.Management.Automation.ErrorCategory]::FromStdErr,
1387 $null
1388 ))
1389 }
1390 if ("$retmsg" -ne "") {
1391 return $retmsg
1392 }}
1393 append fdef "\n}"
1394 if {[getConf ml]} {
1395 append fdef "\nfunction global:ml {"
1396 append fdef {
1397 param([Parameter(ValueFromRemainingArguments)] [string[]] $allargs)
1398 $mlargs = @('ml')
1399 if ($allargs.Length) {
1400 $mlargs += $allargs
1401 }
1402 $errmsg,$retmsg = _envmodule_common $mlargs
1403 if ("$errmsg" -ne "") {
1404 $PSCmdlet.ThrowTerminatingError(
1405 [System.Management.Automation.ErrorRecord]::new(
1406 ([System.Exception]"$errmsg"),
1407 'error while running modulecmd.tcl via ml',
1408 [System.Management.Automation.ErrorCategory]::FromStdErr,
1409 $null
1410 ))
1411 }
1412 if ("$retmsg" -ne "") {
1413 return $retmsg
1414 }}
1415 append fdef "\n}"
1416 }
1417 }
1418 }
1419
1420 # output function definition
1421 lappend ::g_shcode_out $fdef
1422 }
1423
1424 proc get-env {var {valifunset {}}} {
1425 if {[isEnvVarDefined $var] && ![isEnvVarCleared $var]} {
1426 return $::env($var)
1427 } else {
1428 return $valifunset
1429 }
1430 }
1431
1432 proc envVarEquals {var_name value} {
1433 return [expr {[isEnvVarDefined $var_name] && [get-env $var_name]\
1434 eq $value}]
1435 }
1436
1437 proc isEnvVarDefined {var_name} {
1438 return [info exists ::env($var_name)]
1439 }
1440
1441 # Get list of valid variable names found in run_quarantine configuration
1442 # option, cleared from duplicate entries. Warn about invalid names if asked
1443 proc getQuarantineVarList {{report_bad 0}} {
1444 set var_list {}
1445 foreach var [split [getConf run_quarantine]] {
1446 if {[regexp {^[A-Za-z_][A-Za-z0-9_]*$} $var]} {
1447 lappendNoDup var_list $var
1448 } elseif {$report_bad && [string length $var]} {
1449 reportWarning "Bad variable name set in MODULES_RUN_QUARANTINE\
1450 ($var)"
1451 }
1452 }
1453 return $var_list
1454 }
1455
1456 proc setEnvVarIfUndefined {var_name value} {
1457 if {![isEnvVarDefined $var_name]} {
1458 set ::env($var_name) $value
1459 }
1460 }
1461
1462 proc set-env {var val} {
1463 set mode [currentState mode]
1464 reportDebug "$var=$val"
1465
1466 if {![isEnvVarProtected $var]} {
1467 # an empty string value means unsetting variable on Windows platform, so
1468 # call unset-env to ensure variable will not be seen defined yet raising
1469 # an error when trying to access it
1470 if {[getState is_win] && $val eq {}} {
1471 unset-env $var
1472 } else {
1473 set ::env($var) $val
1474
1475 unsetEnvVarAsCleared $var
1476
1477 # propagate variable setup to shell environment on load and unload
1478 # mode
1479 if {$mode eq {load} || $mode eq {unload}} {
1480 set ::g_stateEnvVars($var) new
1481 }
1482 }
1483 } else {
1484 reportWarning "Modification of protected environment variable $var\
1485 ignored"
1486 }
1487 }
1488
1489 proc isEnvVarProtected {var_name} {
1490 return [expr {$var_name in [getConfList protected_envvars]}]
1491 }
1492
1493 proc hasEnvVarInitValue {var_name} {
1494 if {![isConfDefined init_envvars]} {
1495 getConf init_envvars
1496 }
1497 return [info exists ::g_initEnvvars($var_name)]
1498 }
1499
1500 proc envVarInitValue {var_name} {
1501 return $::g_initEnvvars($var_name)
1502 }
1503
1504 proc reset-to-unset-env {var {val {}}} {
1505 set ::env($var) $val
1506 # set var as cleared if val is empty
1507 if {$val eq {}} {
1508 setEnvVarAsCleared $var
1509 }
1510 }
1511
1512 proc setEnvVarAsCleared {var_name} {
1513 set ::g_clearedEnvVars($var_name) 1
1514 }
1515
1516 proc unsetEnvVarAsCleared {var_name} {
1517 if {[isEnvVarCleared $var_name]} {
1518 unset ::g_clearedEnvVars($var_name)
1519 }
1520 }
1521
1522 proc isEnvVarCleared {var_name} {
1523 return [info exists ::g_clearedEnvVars($var_name)]
1524 }
1525
1526 proc unset-env {var {internal 0} {val {}}} {
1527 set mode [currentState mode]
1528 reportDebug "$var (internal=$internal, val=$val)"
1529
1530 if {![isEnvVarProtected $var]} {
1531 # clear value instead of unset it not to break variable later reference
1532 # in modulefile. clear whether variable set or not to get a later usage
1533 # consistent behavior whatever env is setup
1534 if {!$internal} {
1535 reset-to-unset-env $var $val
1536 # internal variables (like ref counter var) are purely unset if they
1537 # exists
1538 } elseif {[isEnvVarDefined $var]} {
1539 unset ::env($var)
1540 set intwasset 1
1541 }
1542
1543 # propagate deletion in any case if variable is public and for internal
1544 # one only if variable was set
1545 if {($mode eq {load} || $mode eq {unload}) && (!$internal ||\
1546 [info exists intwasset])} {
1547 set ::g_stateEnvVars($var) del
1548 }
1549 } else {
1550 reportWarning "Modification of protected environment variable $var\
1551 ignored"
1552 }
1553 }
1554
1555 proc getPushenvVarName {var} {
1556 return __MODULES_PUSHENV_${var}
1557 }
1558
1559 proc getModshareVarName {var} {
1560 # no modshare variable for Modules-specific path variables as each entry
1561 # should be unique (no reference counting mechanism for these variables
1562 # expect for MODULEPATH)
1563 if {$var in {_LMFILES_ LOADEDMODULES} || [string equal -length 10\
1564 __MODULES_ $var] || [string equal -length 8 MODULES_ $var]} {
1565 return {}
1566 # specific modshare variable use a Modules-specific prefix (rather suffix
1567 # that may lead to warning message for instance for DYLD-related variables)
1568 } else {
1569 return __MODULES_SHARE_${var}
1570 }
1571 }
1572
1573 # path fiddling
1574 proc getReferenceCountArray {var separator} {
1575 # get reference counter set in environment
1576 set sharevar [getModshareVarName $var]
1577 array set refcount {}
1578 if {[isEnvVarDefined $sharevar]} {
1579 set modsharelist [psplit $::env($sharevar) [getState path_separator]]
1580 # ignore environment ref count variable if malformed
1581 if {([llength $modsharelist] % 2) == 0} {
1582 array set refcount $modsharelist
1583 } else {
1584 reportDebug "Reference counter value in '$sharevar' is malformed\
1585 ($modsharelist)"
1586 }
1587 }
1588
1589 array set countarr {}
1590 if {[isEnvVarDefined $var]} {
1591 # do not skip a bare empty path entry that can also be found in
1592 # reference counter array (sometimes var is cleared by setting it
1593 # empty not unsetting it, ignore var in this case)
1594 if {$::env($var) eq {} && [info exists refcount()]} {
1595 lappend eltlist {}
1596 } else {
1597 set eltlist [split $::env($var) $separator]
1598 }
1599
1600 # just go thought the elements of the variable, which means additional
1601 # elements part of the reference counter variable will be ignored
1602 foreach elt $eltlist {
1603 # no reference counter, means value has been set once
1604 if {![info exists refcount($elt)]} {
1605 set count 1
1606 # bad reference counter value is ignored
1607 } elseif {![string is digit -strict $refcount($elt)] ||\
1608 $refcount($elt) < 1} {
1609 reportDebug "Reference counter value for '$elt' in '$sharevar' is\
1610 erroneous ($refcount($elt))"
1611 set count 1
1612 } else {
1613 set count $refcount($elt)
1614 }
1615 set countarr($elt) $count
1616 }
1617 }
1618
1619 set count_list [array get countarr]
1620 reportDebug "(var=$var, delim=$separator) got '$count_list'"
1621
1622 return $count_list
1623 }
1624
1625 proc getPathReferenceCount {var path separator {resolv 0}} {
1626 array set ref_count_arr [getReferenceCountArray $var $separator]
1627 if {[info exists ref_count_arr($path)]} {
1628 set ref_count $ref_count_arr($path)
1629 } else {
1630 set ref_count 0
1631 if {$resolv} {
1632 set matching_path [getStringFromListMatchingResString [array names\
1633 ref_count_arr] $path]
1634 if {[string length $matching_path]} {
1635 set ref_count $ref_count_arr($matching_path)
1636 }
1637 }
1638 }
1639 return $ref_count
1640 }
1641
1642 # generate reference count value to export in user environment
1643 proc setReferenceCountRecordValue {sharevar countlist} {
1644 foreach {elt refcount} $countlist {
1645 # do not export elements with a reference count of 1 as no reference
1646 # count entry means a reference count of 1
1647 # exception made for empty string which is recorded even for a single
1648 # reference count to be able to distinguish between an empty path
1649 # variable and a path variable with an empty string as unique element
1650 if {$refcount > 1 || $elt eq {}} {
1651 lappend reclist $elt $refcount
1652 }
1653 }
1654
1655 if {[info exists reclist]} {
1656 set-env $sharevar [pjoin $reclist [getState path_separator]]
1657 # unset ref count var if found set whereas no counter should be recorded
1658 } elseif {[isEnvVarDefined $sharevar]} {
1659 unset-env $sharevar 1
1660 }
1661 }
1662
1663 proc unload-path {cmd mode dflbhv args} {
1664 reportDebug "($args) cmd=$cmd, mode=$mode, dflbhv=$dflbhv"
1665
1666 lassign [parsePathCommandArgs $cmd $mode $dflbhv {*}$args] separator\
1667 allow_dup idx_val ign_refcount val_set_is_delim glob_match bhv var\
1668 path_list
1669
1670 # indicate env var name to configured traces
1671 setState current_envvar $var
1672
1673 switch -- $bhv {
1674 noop {
1675 return [list $bhv $var]
1676 }
1677 append - prepend {
1678 # set paths instead of removing them
1679 add-path unload-path load $bhv $cmd $separator $var {*}$path_list
1680 return [list $bhv $var]
1681 }
1682 }
1683
1684 # clean any previously defined pushenv stack
1685 unset-env [getPushenvVarName $var] 1
1686
1687 # no reference count management when no share variable is returned
1688 set isrefcount [expr {[set sharevar [getModshareVarName $var]] ne {}}]
1689 if {$isrefcount} {
1690 array set countarr [getReferenceCountArray $var $separator]
1691 }
1692
1693 # Don't worry about dealing with this variable if it is already scheduled
1694 # for deletion
1695 if {[info exists ::g_stateEnvVars($var)] && $::g_stateEnvVars($var) eq\
1696 {del}} {
1697 return [list $bhv $var]
1698 }
1699
1700 # save initial variable content to match index arguments
1701 set dir_list [split [get-env $var] $separator]
1702 # detect if empty env value means empty path entry
1703 if {![llength $dir_list] && [info exists countarr()]} {
1704 lappend dir_list {}
1705 }
1706
1707 # match glob pattern against existing values
1708 if {$glob_match} {
1709 set new_path_list [list]
1710 foreach glob_pattern $path_list {
1711 set pattern_match_list [lsearch -glob -all -inline $dir_list\
1712 $glob_pattern]
1713 if {[llength $pattern_match_list]} {
1714 lappend new_path_list {*}$pattern_match_list
1715 }
1716 }
1717 set path_list $new_path_list
1718 }
1719
1720 # build list of index to remove from variable
1721 set del_idx_list [list]
1722 foreach dir $path_list {
1723 # retrieve dir value if working on an index list
1724 if {$idx_val} {
1725 set idx $dir
1726 # go to next index if this one is not part of the existing range
1727 # needed to distinguish an empty value to an out-of-bound value
1728 if {$idx < 0 || $idx >= [llength $dir_list]} {
1729 continue
1730 } else {
1731 set dir [lindex $dir_list $idx]
1732 }
1733 }
1734
1735 # update reference counter array
1736 if {[info exists countarr($dir)]} {
1737 # unload value in any case if counter ignored (--ignore-refcount set)
1738 if {$ign_refcount} {
1739 set countarr($dir) 0
1740 } else {
1741 incr countarr($dir) -1
1742 }
1743 if {$countarr($dir) <= 0} {
1744 unset countarr($dir)
1745 set newcount 0
1746 } else {
1747 set newcount $countarr($dir)
1748 }
1749 } else {
1750 set newcount 0
1751 }
1752
1753 # get all entry indexes corresponding to dir
1754 set found_idx_list [lsearch -all -exact $dir_list $dir]
1755
1756 # remove all found entries
1757 if {$newcount <= 0} {
1758 # only remove passed position in --index mode
1759 if {$idx_val} {
1760 lappend del_idx_list $idx
1761 } else {
1762 lappend del_idx_list {*}$found_idx_list
1763 }
1764 # if multiple entries found remove the extra entries compared to new
1765 # reference counter
1766 } elseif {[llength $found_idx_list] > $newcount} {
1767 # only remove passed position in --index mode
1768 if {$idx_val} {
1769 lappend del_idx_list $idx
1770 } else {
1771 # delete extra entries, starting from end of the list (on a path
1772 # variable, entries at the end have less priority than those at
1773 # the start)
1774 lappend del_idx_list {*}[lrange $found_idx_list $newcount end]
1775 }
1776 }
1777 }
1778
1779 # update variable if some element need to be removed
1780 if {[llength $del_idx_list]} {
1781 set del_idx_list [lsort -integer -unique $del_idx_list]
1782 set newpath [list]
1783 set nbelem [llength $dir_list]
1784 # rebuild list of element without indexes set for deletion
1785 for {set i 0} {$i < $nbelem} {incr i} {
1786 if {$i ni $del_idx_list} {
1787 lappend newpath [lindex $dir_list $i]
1788 }
1789 }
1790 } else {
1791 set newpath $dir_list
1792 }
1793
1794 # clear environment variable if new value equals initial value
1795 if {[hasEnvVarInitValue $var] && [envVarInitValue $var] eq [join $newpath\
1796 $separator]} {
1797 set init_value [envVarInitValue $var]
1798 if {!$isrefcount || ![info exists countarr($init_value)] ||\
1799 $countarr($init_value) <= 1} {
1800 set newpath [list]
1801 unset -nocomplain countarr($init_value)
1802 }
1803 }
1804
1805 # set env variable and corresponding reference counter in any case
1806 if {![llength $newpath]} {
1807 unset-env $var
1808 } else {
1809 set-env $var [join $newpath $separator]
1810 }
1811
1812 if {$isrefcount} {
1813 setReferenceCountRecordValue $sharevar [array get countarr]
1814 }
1815 return [list $bhv $var]
1816 }
1817
1818 proc add-path {cmd mode dflbhv args} {
1819 reportDebug "($args) cmd=$cmd, mode=$mode, dflbhv=$dflbhv"
1820
1821 # may be called from unload-path where argument parsing was already done
1822 if {$cmd eq {unload-path}} {
1823 set path_list [lassign $args cmd separator var]
1824 set allow_dup 0
1825 set ign_refcount 0
1826 set val_set_is_delim 0
1827 set bhv $dflbhv
1828 } else {
1829 lassign [parsePathCommandArgs $cmd $mode $dflbhv {*}$args] separator\
1830 allow_dup idx_val ign_refcount val_set_is_delim glob_match bhv var\
1831 path_list
1832 }
1833
1834 # indicate env var name to configured traces
1835 setState current_envvar $var
1836
1837 # clean any previously defined pushenv stack
1838 unset-env [getPushenvVarName $var] 1
1839
1840 set sharevar [getModshareVarName $var]
1841 set isrefcount [expr {$sharevar ne {}}]
1842
1843 # use initial value defined for env var if not yet defined
1844 if {![isEnvVarDefined $var] && [hasEnvVarInitValue $var]} {
1845 set init_value [envVarInitValue $var]
1846 set-env $var $init_value
1847 # setup reference counter in case of empty string entry
1848 if {$init_value eq {} && $isrefcount} {
1849 set-env $sharevar $init_value:1
1850 }
1851 }
1852
1853 # no reference count management when no share variable is returned
1854 if {$isrefcount} {
1855 array set countarr [getReferenceCountArray $var $separator]
1856 }
1857
1858 if {$bhv eq {prepend}} {
1859 set path_list [lreverse $path_list]
1860 }
1861
1862 set val [get-env $var]
1863
1864 foreach dir $path_list {
1865 # remove $dir from path only if path_entry_reorder is true and
1866 # $dir is already in path and duplicates are NOT allowed.
1867 if {[getConf path_entry_reorder] && [info exists countarr($dir)]\
1868 && ! $allow_dup} {
1869 set mpath_list [split $val $separator]
1870 set mpath_list [lsearch -inline -all -not -exact $mpath_list $dir]
1871 set val [join $mpath_list $separator]
1872 }
1873 # add $dir to beginning or end only if path_entry_reorder is true or
1874 # $dir is NOT in path or duplicates are allowed.
1875 # Please note: if path_entry_reorder is true and duplicates are not
1876 # allowed, $dir is not in path ($val) - either it was not in or it
1877 # had been removed. Hence we have to add it.
1878 if {[getConf path_entry_reorder] || ![info exists countarr($dir)]\
1879 || $allow_dup} {
1880 # ignore env var set empty if no empty entry found in reference
1881 # counter array (sometimes var is cleared by setting it empty not
1882 # unsetting it)
1883 if {$val ne {} || [info exists countarr()]} {
1884 set sep [expr {$val eq $separator ? {} : $separator}]
1885 set val [expr {$bhv eq {prepend} ? "$dir$sep$val" :\
1886 "$val$sep$dir"}]
1887 } else {
1888 set val $dir
1889 }
1890 }
1891 #### ref-counting
1892 # if $dir is NOT in path
1893 # set ref-count 1
1894 # else
1895 # do NOT increase counter if bare separator string is added or if
1896 # reference count is ignored (--ignore-refcount set) unless if
1897 # duplicate mode is enabled (--duplicates set)
1898 if {![info exists countarr($dir)]} {
1899 set countarr($dir) 1
1900 } elseif {!$val_set_is_delim && (!$ign_refcount || $allow_dup)} {
1901 incr countarr($dir)
1902 }
1903 }
1904
1905 set-env $var $val
1906 if {$isrefcount} {
1907 setReferenceCountRecordValue $sharevar [array get countarr]
1908 }
1909
1910 if {$var eq {MODULEPATH}} {
1911 registerCurrentModuleUse {*}$path_list
1912 }
1913
1914 return {}
1915 }
1916
1917 # analyze argument list passed to a path command to set default value or raise
1918 # error in case some attributes are missing
1919 proc parsePathCommandArgs {cmd mode dflbhv args} {
1920 # parse argument list
1921 set next_is_delim 0
1922 set next_is_ignored 0
1923 set next_is_reset 0
1924 set allow_dup 0
1925 set idx_val 0
1926 set ign_refcount 0
1927 set val_set_is_delim 0
1928 set glob_match 0
1929 set bhv $dflbhv
1930 foreach arg $args {
1931 # everything passed after variable name is considered a value
1932 if {[info exists var]} {
1933 switch -- $arg {
1934 --append-on-unload - --prepend-on-unload {
1935 if {$cmd ne {remove-path}} {
1936 knerror "invalid option '$arg' for $cmd"
1937 } elseif {$mode ne {unload}} {
1938 # ignore value set after this argument if not unloading
1939 # unless if no list is already set for load mode
1940 if {[info exists val_raw_list]} {
1941 set next_is_ignored 1
1942 }
1943 } else {
1944 set bhv [expr {$arg eq {--append-on-unload} ? {append} :\
1945 {prepend}}]
1946 # if another argument is set, current value list will be
1947 # withdrawn to start from new list set after this argument
1948 set next_is_reset 1
1949 }
1950 set bhvopt $arg
1951 }
1952 --remove-on-unload - --noop-on-unload {
1953 if {$cmd ne {remove-path}} {
1954 knerror "invalid option '$arg' for $cmd"
1955 } elseif {$mode eq {unload}} {
1956 set bhv [expr {$arg eq {--remove-on-unload} ? {remove} :\
1957 {noop}}]
1958 }
1959 set bhvopt $arg
1960 }
1961 default {
1962 if {$next_is_reset} {
1963 set next_is_reset 0
1964 set val_raw_list [list $arg]
1965 } elseif {!$next_is_ignored} {
1966 # set multiple passed values in a list
1967 lappend val_raw_list $arg
1968 }
1969 }
1970 }
1971 } else {
1972 switch -glob -- $arg {
1973 --index {
1974 if {$cmd ne {remove-path}} {
1975 reportWarning "--index option has no effect on $cmd"
1976 } else {
1977 set idx_val 1
1978 }
1979 }
1980 --duplicates {
1981 # raise warning when option is used by remove-path
1982 if {$cmd eq {remove-path}} {
1983 reportWarning "--duplicates option has no effect on $cmd"
1984 } else {
1985 set allow_dup 1
1986 }
1987 }
1988 --glob {
1989 # raise warning when option is not used by remove-path
1990 if {$cmd eq {remove-path}} {
1991 set glob_match 1
1992 } else {
1993 reportWarning "--glob option has no effect on $cmd"
1994 }
1995 }
1996 -d - -delim - --delim {
1997 set next_is_delim 1
1998 }
1999 --delim=* {
2000 set delim [string range $arg 8 end]
2001 }
2002 --ignore-refcount {
2003 set ign_refcount 1
2004 }
2005 --append-on-unload - --prepend-on-unload - --remove-on-unload -\
2006 --noop-on-unload {
2007 if {$cmd ne {remove-path}} {
2008 knerror "invalid option '$arg' for $cmd"
2009 } elseif {$mode eq {unload}} {
2010 switch -- [string range $arg 2 5] {
2011 noop { set bhv noop }
2012 remo { set bhv remove }
2013 appe { set bhv append }
2014 prep { set bhv prepend }
2015 }
2016 }
2017 set bhvopt $arg
2018 }
2019 -* {
2020 knerror "invalid option '$arg' for $cmd"
2021 }
2022 default {
2023 if {$next_is_delim} {
2024 set delim $arg
2025 set next_is_delim 0
2026 } else {
2027 set var $arg
2028 }
2029 }
2030 }
2031 }
2032 }
2033
2034 # adapt with default value or raise error if some arguments are missing
2035 if {![info exists delim]} {
2036 set delim [getState path_separator]
2037 } elseif {$delim eq {}} {
2038 knerror "$cmd should get a non-empty path delimiter"
2039 }
2040 if {![info exists var]} {
2041 knerror "$cmd should get an environment variable name"
2042 } elseif {$var eq {}} {
2043 knerror "$cmd should get a valid environment variable name"
2044 }
2045 if {![info exists val_raw_list]} {
2046 knerror "$cmd should get a value for environment variable $var"
2047 }
2048
2049 # some options cannot be mixed
2050 if {$idx_val != 0 && ([info exists bhvopt] && $bhvopt ne\
2051 {--noop-on-unload})} {
2052 knerror "--index and $bhvopt options cannot be simultaneously set"
2053 }
2054 if {$idx_val && $glob_match} {
2055 knerror "--index and --glob options cannot be simultaneously set"
2056 }
2057 if {$glob_match && ([info exists bhvopt] && $bhvopt in\
2058 {--append-on-unload --prepend-on-unload})} {
2059 knerror "--glob and $bhvopt options cannot be simultaneously set"
2060 }
2061
2062 set nb_path_eq_delim [llength [lsearch -all -exact $val_raw_list $delim]]
2063 if {$nb_path_eq_delim && $cmd eq {remove-path}} {
2064 knerror "$cmd cannot handle path equals to separator string"
2065 } elseif {$nb_path_eq_delim > 1} {
2066 knerror "$cmd cannot handle multiple paths equal to separator string"
2067 }
2068
2069 # set list of value to add
2070 set val_list [list]
2071 foreach val $val_raw_list {
2072 # check passed indexes are numbers
2073 if {$idx_val && ![string is integer -strict $val]} {
2074 knerror "$cmd should get valid number as index value"
2075 }
2076
2077 if {![string length $val]} {
2078 lappend val_list {}
2079 } elseif {$val eq $delim} {
2080 if {[llength $val_raw_list] > 1 || [get-env $var] ne {}} {
2081 lappend val_list {}
2082 # make separator string appear once in resulting value
2083 } elseif {[getPathReferenceCount $var {} $delim]} {
2084 lappend val_list {}
2085 set allow_dup 1
2086 } else {
2087 lappend val_list {} {}
2088 set val_set_is_delim 1
2089 set allow_dup 1
2090 set ign_refcount 1
2091 }
2092 } else {
2093 # split passed value with delimiter
2094 lappend val_list {*}[split $val $delim]
2095 }
2096 }
2097
2098 reportDebug "(delim=$delim, allow_dup=$allow_dup, idx_val=$idx_val,\
2099 ign_refcount=$ign_refcount, val_set_is_delim=$val_set_is_delim,\
2100 glob_match=$glob_match, bhv=$bhv, var=$var, val=$val_list,\
2101 nbval=[llength $val_list])"
2102
2103 return [list $delim $allow_dup $idx_val $ign_refcount $val_set_is_delim\
2104 $glob_match $bhv $var $val_list]
2105 }
2106
2107 # get list of Modules-specific environment variable in glob form
2108 proc getModulesEnvVarGlobList {{loaded_ctx 0}} {
2109 set envvar_glob_list [list LOADEDMODULES _LMFILES_]
2110 # only return list of variables related to module loaded context
2111 if {$loaded_ctx} {
2112 lappend envvar_glob_list __MODULES_*
2113 } else {
2114 lappend envvar_glob_list MODULE* __MODULES_* *_module*
2115 }
2116 return $envvar_glob_list
2117 }
2118
2119 # trace procedure to apply same env change procedure to linked env vars
2120 proc mirrorEnvVarChange {cmd_str code result op} {
2121 # skip mirror processing if initial command failed
2122 if {$code} {
2123 return
2124 }
2125 set envvar [getState current_envvar]
2126 if {[info exists ::g_linkedEnvvars($envvar)]} {
2127 # collect all direct and indirect linked env vars, avoiding cycle loop
2128 set linked_envvar_list $::g_linkedEnvvars($envvar)
2129 for {set i 0} {$i < [llength $linked_envvar_list]} {incr i} {
2130 set linked_envvar [lindex $linked_envvar_list $i]
2131 if {[info exists ::g_linkedEnvvars($linked_envvar)]} {
2132 lappendNoDup linked_envvar_list\
2133 {*}$::g_linkedEnvvars($linked_envvar)
2134 }
2135 }
2136
2137 if {![isTopEvaluation]} {
2138 set interp_eval_cmd [list interp eval [getCurrentModfileInterpName]]
2139 }
2140
2141 # apply same env var change command on linked env vars
2142 # no other trace hook will be triggered as we are processing this one
2143 foreach linked_envvar $linked_envvar_list {
2144 if {$linked_envvar eq $envvar} {
2145 continue
2146 }
2147 set linked_cmd_str [replaceFirstInStr $cmd_str $envvar\
2148 $linked_envvar]
2149 # adapt execution if called from modulefile interp
2150 if {[info exists interp_eval_cmd]} {
2151 set linked_cmd_str [list {*}$interp_eval_cmd $linked_cmd_str]
2152 }
2153 # execute in same context than initial command
2154 uplevel 1 $linked_cmd_str
2155 }
2156 }
2157 }
2158
2159 # ;;; Local Variables:
2160 # ;;; Mode: tcl-mode
2161 # ;;; tcl-indent-level: 3
2162 # ;;; tcl-continued-indent-level: 3
2163 # ;;; indent-tabs-mode: nil
2164 # ;;; End:
2165 # vim:set tabstop=3 shiftwidth=3 expandtab autoindent: