Debian Codegraph @

tcl/subcmd.tcl.in

raw
1 ##########################################################################
2
3 # SUBCMD.TCL, module sub-commands 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 cmdModuleList {show_oneperline show_mtime search_match args} {
24 set json [isStateEqual report_format json]
25
26 if {[llength $args]} {
27 # match passed name against any part of loaded module names
28 set mtest [expr {{contains} in $search_match ? {matchin} : {match}}]
29 set search_queries $args
30 # prepare header message which depend if search is performed
31 set loadedmsg {Currently Loaded Matching Modulefiles}
32 } else {
33 set search_queries {}
34 set loadedmsg {Currently Loaded Modulefiles}
35 }
36
37 set report_indesym [isEltInReport indesym 0]
38 set report_alias [expr {[isEltInReport alias 0] || [isEltInReport\
39 provided-alias 0]}]
40
41 # build list of loaded modules and symbolics and aliases if reported
42 set loadedmodlist [list]
43 foreach mod [getEnvLoadedModulePropertyParsedList name] {
44 set modfile [getModulefileFromLoadedModule $mod]
45 set mtime [expr {$show_mtime && [file exists $modfile] ?\
46 [getFileMtime $modfile] : {}}]
47 set mod_list($mod) [list modulefile $mtime $modfile]
48
49 # fetch symbols from loaded environment information
50 set modname [file dirname $mod]
51 set sym_list {}
52 foreach altname [getLoadedAltname $mod sym] {
53 # skip non-symbol entry
54 if {$altname ne $modname} {
55 lappend sym_list [file tail $altname]
56 # fill loaded list structure with symbolic versions in case
57 # indesym report is activated
58 if {$report_indesym} {
59 set mod_list($altname) [list version $mod]
60 lappend loadedmodlist $altname
61 }
62 }
63 }
64 set ::g_symbolHash($mod) [lsort -dictionary $sym_list]
65
66 # fetch aliases from loaded environment information
67 if {$report_alias} {
68 foreach altname [getLoadedAltname $mod alias] {
69 set mod_list($altname) [list alias $mod]
70 lappend loadedmodlist $altname
71 }
72 }
73
74 lappend loadedmodlist $mod
75 }
76
77 # filter-out hidden loaded modules unless all module should be seen
78 if {[getState hiding_threshold] <= 1} {
79 set newloadedmodlist [list]
80 foreach mod $loadedmodlist {
81 if {![isModuleTagged $mod hidden-loaded 1]} {
82 lappend newloadedmodlist $mod
83 }
84 }
85 set loadedmodlist $newloadedmodlist
86 }
87
88 # same header msg if no module loaded at all whether search is made or not
89 set noloadedmsg [expr {![llength $loadedmodlist] ? {No Modulefiles\
90 Currently Loaded.} : {No Matching Modulefiles Currently Loaded.}}]
91
92 # filter loaded modules not matching any of the mod spec passed
93 if {[llength $args]} {
94 # include alt name comparison (alias/sym) when checking module name
95 # depends if alias and/or sym are reported independently
96 set modeq_altname_mode [switch -- $report_indesym$report_alias {
97 11 {expr {0}}
98 10 {expr {7}}
99 01 {expr {6}}
100 00 {expr {2}}
101 }]
102 set matchlist [list]
103 foreach mod $loadedmodlist {
104 foreach pattern $args {
105 # compare pattern against loaded module, its variant set and its
106 # alternative names
107 if {[modEq $pattern $mod $mtest 1 $modeq_altname_mode 1 0 *]} {
108 lappend matchlist $mod
109 break
110 }
111 }
112 }
113 set loadedmodlist $matchlist
114 }
115
116 if {![llength $loadedmodlist]} {
117 if {!$json && [isEltInReport header]} {
118 report $noloadedmsg
119 }
120 } else {
121 set one_per_line [expr {$show_mtime || $show_oneperline}]
122 set show_idx [expr {!$show_mtime && [isEltInReport idx]}]
123 set header [expr {!$json && [isEltInReport header] ? $loadedmsg :\
124 {noheader}}]
125 set theader_cols [list hi Package 39 Versions 19 {Last mod.} 19]
126
127 reportModules $search_queries $header {} terse $show_mtime $show_idx\
128 $one_per_line $theader_cols loaded $loadedmodlist
129
130 # display output key
131 if {!$show_mtime && !$json && [isEltInReport key]} {
132 displayKey
133 }
134 }
135 }
136
137 proc cmdModuleDisplay {args} {
138 lappendState mode display
139 set first_report 1
140 foreach mod $args {
141 lassign [getPathToModule $mod] modfile modname modnamevr
142 if {$modfile ne {}} {
143 # only one separator lines between 2 modules
144 if {$first_report} {
145 displaySeparatorLine
146 set first_report 0
147 }
148 report [sgr hi $modfile]:\n
149 execute-modulefile $modfile $modname modnamevr $mod 1
150 displaySeparatorLine
151 }
152 }
153 lpopState mode
154 }
155
156 proc cmdModulePaths {mod} {
157 set dir_list [getModulePathList exiterronundef]
158 foreach dir $dir_list {
159 array unset mod_list
160 array set mod_list [getModules $dir $mod 0 [list rc_defs_included]]
161
162 # prepare list of dirs for alias/symbol target search, will first search
163 # in currently looked dir, then in other dirs following precedence order
164 set target_dir_list [list $dir {*}[replaceFromList $dir_list $dir]]
165
166 # forcibly enable implicit_default to resolve alias target when it
167 # points to a directory
168 setConf implicit_default 1
169
170 # build list of modulefile to print
171 foreach elt [array names mod_list] {
172 switch -- [lindex $mod_list($elt) 0] {
173 modulefile {
174 lappend ::g_return_text $dir/$elt
175 }
176 virtual {
177 lappend ::g_return_text [lindex $mod_list($elt) 2]
178 }
179 alias - version {
180 # resolve alias target
181 set aliastarget [lindex $mod_list($elt) 1]
182 lassign [getPathToModule $aliastarget $target_dir_list 0]\
183 modfile modname modnamevr
184 # add module target as result instead of alias
185 if {$modfile ne {} && ![info exists mod_list($modname)]} {
186 lappend ::g_return_text $modfile
187 }
188 }
189 }
190 }
191
192 # reset implicit_default to restore behavior defined
193 unsetConf implicit_default
194 }
195
196 # sort results if any and remove duplicates
197 if {[info exists ::g_return_text]} {
198 set ::g_return_text [lsort -dictionary -unique $::g_return_text]
199 } else {
200 # set empty value to return empty if no result
201 set ::g_return_text {}
202 }
203 }
204
205 proc cmdModulePath {mod} {
206 lassign [getPathToModule $mod] modfile modname modnamevr
207 # if no result set empty value to return empty
208 if {$modfile eq {}} {
209 set ::g_return_text {}
210 } else {
211 lappend ::g_return_text $modfile
212 }
213 }
214
215 proc cmdModuleSearch {args} {
216 # disable error report to avoid modulefile errors to mix with valid results
217 set mod_pattern_list [lassign $args search]
218
219 set json [isStateEqual report_format json]
220 set icase [isIcase]
221
222 lappend searchmod rc_defs_included
223 if {![llength $mod_pattern_list]} {
224 lappend mod_pattern_list {}
225 lappend searchmod wild
226 } else {
227 foreach mod_pattern $mod_pattern_list {
228 if {![string length $mod_pattern]} {
229 reportError [getEmptyNameMsg module]
230 return
231 }
232 }
233 }
234
235 inhibitErrorReport
236
237 set foundmod 0
238 lappendState mode whatis
239 set dir_list [getModulePathList exiterronundef]
240 foreach dir $dir_list {
241 array unset mod_list
242 array set mod_list [getMatchingAnyModules $dir $mod_pattern_list 0\
243 $searchmod {}]
244 array unset interp_list
245 array set interp_list {}
246
247 # forcibly enable implicit_default to resolve alias target when it
248 # points to a directory
249 setConf implicit_default 1
250
251 # build list of modulefile to interpret
252 foreach elt [array names mod_list] {
253 switch -- [lindex $mod_list($elt) 0] {
254 modulefile {
255 if {[isModuleTagged $elt forbidden 0 $dir/$elt]} {
256 # register any error occurring on element matching search
257 if {[modEqAny $mod_pattern_list $elt]} {
258 set err_list($elt) [list accesserr [getForbiddenMsg\
259 $elt $dir/$elt]]
260 }
261 } else {
262 set interp_list($elt) $dir/$elt
263 # register module name in a global list (shared across
264 # modulepaths) to get hints when solving aliases/version
265 set full_list($elt) 1
266 }
267 }
268 virtual {
269 if {[isModuleTagged $elt forbidden 0 [lindex $mod_list($elt)\
270 2]]} {
271 # register any error occurring on element matching search
272 if {[modEqAny $mod_pattern_list $elt]} {
273 set err_list($elt) [list accesserr [getForbiddenMsg\
274 $elt [lindex $mod_list($elt) 2]]]
275 }
276 } else {
277 set interp_list($elt) [lindex $mod_list($elt) 2]
278 set full_list($elt) 1
279 }
280 }
281 alias {
282 # resolve alias target
283 set elt_target [lindex $mod_list($elt) 1]
284 if {![info exists full_list($elt_target)]} {
285 lassign [getPathToModule $elt_target $dir 0]\
286 modfile modname modnamevr issuetype issuemsg
287 # add module target as result instead of alias
288 if {$modfile ne {} && ![info exists mod_list($modname)]} {
289 set interp_list($modname) $modfile
290 set full_list($modname) 1
291 } elseif {$modfile eq {}} {
292 # if module target not found in current modulepath add to
293 # list for global search after initial modulepath lookup
294 if {[string first {Unable to locate} $issuemsg] == 0} {
295 set extra_search($modname) [list $dir [modEqAny\
296 $mod_pattern_list $elt]]
297 # register resolution error if alias name matches search
298 } elseif {[modEqAny $mod_pattern_list $elt]} {
299 set err_list($modname) [list $issuetype $issuemsg]
300 }
301 }
302 }
303 }
304 version {
305 # report error of version target if matching query
306 set elt_target [getArrayKey mod_list [lindex $mod_list($elt)\
307 1] $icase]
308 if {[info exists mod_list($elt_target)] && [lindex\
309 $mod_list($elt_target) 0] in [list invalid accesserr] &&\
310 [modEqAny $mod_pattern_list $elt]} {
311 set err_list($elt_target) $mod_list($elt_target)
312 } elseif {![info exists mod_list($elt_target)]} {
313 set extra_search($elt_target) [list $dir [modEqAny\
314 $mod_pattern_list $elt]]
315 }
316 }
317 invalid - accesserr {
318 # register any error occurring on element matching search
319 if {[modEqAny $mod_pattern_list $elt]} {
320 set err_list($elt) $mod_list($elt)
321 }
322 }
323 }
324 }
325
326 # reset implicit_default to restore behavior defined
327 unsetConf implicit_default
328
329 # in case during modulepath lookup we find an alias target we were
330 # looking for in previous modulepath, remove this element from global
331 # search list
332 foreach elt [array names extra_search] {
333 if {[info exists full_list($elt)]} {
334 unset extra_search($elt)
335 }
336 }
337
338 # save results from this modulepath for interpretation step as there
339 # is an extra round of search to match missing alias target, we cannot
340 # process modulefiles found immediately
341 if {[array size interp_list]} {
342 set interp_save($dir) [array get interp_list]
343 }
344 }
345
346 # forcibly enable implicit_default to resolve alias target when it points
347 # to a directory
348 setConf implicit_default 1
349
350 # find target of aliases in all modulepath except the one already tried
351 foreach elt [array names extra_search] {
352 lassign [getPathToModule $elt {} 0 no [lindex $extra_search($elt) 0]]\
353 modfile modname modnamevr issuetype issuemsg issuefile
354 # found target so append it to results in corresponding modulepath
355 if {$modfile ne {}} {
356 # get belonging modulepath dir depending of module kind
357 if {[isModuleVirtual $modname $modfile]} {
358 set dir [findModulepathFromModulefile\
359 $::g_sourceVirtual($modname)]
360 } else {
361 set dir [getModulepathFromModuleName $modfile $modname]
362 }
363 array unset interp_list
364 if {[info exists interp_save($dir)]} {
365 array set interp_list $interp_save($dir)
366 }
367 set interp_list($modname) $modfile
368 set interp_save($dir) [array get interp_list]
369 # register resolution error if primal alias name matches search
370 } elseif {$modfile eq {} && [lindex $extra_search($elt) 1]} {
371 set err_list($modname) [list $issuetype $issuemsg $issuefile]
372 }
373 }
374
375 # reset implicit_default to restore behavior defined
376 unsetConf implicit_default
377
378 # prepare string translation to highlight search query string
379 set matchmodmap [prepareMapToHightlightSubstr {*}$mod_pattern_list]
380 set matchsearchmap [prepareMapToHightlightSubstr $search]
381
382 # interpret all modulefile we got for each modulepath
383 foreach dir $dir_list {
384 if {[info exists interp_save($dir)]} {
385 array unset interp_list
386 array set interp_list $interp_save($dir)
387 set foundmod 1
388 set display_list {}
389 # interpret every modulefiles obtained to get their whatis text
390 foreach elt [lsort -dictionary [array names interp_list]] {
391 set ::g_whatis {}
392 ##nagelfar ignore Suspicious variable name
393 execute-modulefile $interp_list($elt) $elt $elt $elt 0 0
394
395 # treat whatis as a multi-line text
396 if {$search eq {} || [regexp -nocase $search $::g_whatis]} {
397 if {$json} {
398 lappend display_list [formatListEltToJsonDisplay $elt\
399 whatis a $::g_whatis 1]
400 } else {
401 set eltsgr [string map $matchmodmap $elt]
402 foreach line $::g_whatis {
403 set linesgr [string map $matchsearchmap $line]
404 lappend display_list "[string repeat { } [expr {20 -\
405 [string length $elt]}]]$eltsgr: $linesgr"
406 }
407 }
408 }
409 }
410
411 displayElementList $dir mp sepline 1 0 0 $display_list
412 }
413 }
414 lpopState mode
415
416 uninhibitErrorReport
417
418 # report errors if a modulefile was searched but not found
419 if {{wild} ni $searchmod && !$foundmod} {
420 # no error registered means nothing was found to match search
421 if {![array exists err_list]} {
422 foreach mod_pattern $mod_pattern_list {
423 set err_list($mod_pattern) [list none "Unable to locate a\
424 modulefile for '$mod_pattern'"]
425 }
426 }
427 foreach elt [array names err_list] {
428 reportIssue {*}$err_list($elt)
429 }
430 }
431 }
432
433 # Intermediate procedure between module and cmdModuleSwitch
434 # Adapt options and arguments depending on context to call cmdModuleSwitch
435 proc cmdModuleIntSwitch {mode tag_list args} {
436 # pass 'user asked state' to switch procedure
437 set uasked [isTopEvaluation]
438 # CAUTION: it is not recommended to use the `switch` sub-command in
439 # modulefiles as this command is intended for the command-line for a 2in1
440 # operation. Could be removed from the modfile scope in a future release.
441 # Use `module unload` and `module load` commands in modulefiles instead.
442 if {$uasked || $mode eq {load}} {
443 set ret [cmdModuleSwitch $uasked $tag_list {*}$args]
444 if {!$uasked && $ret && ![getState force]} {
445 knerror {} MODULES_ERR_SUBFAILED
446 }
447 } else {
448 # find what has been asked for unload and load
449 lassign $args swunmod swlomod
450 if {$swlomod eq {} && $swunmod ne {}} {
451 set swlomod $swunmod
452 }
453
454 # apply same mechanisms than for 'module load' and 'module unload' for
455 # an unload evaluation: nothing done for switched-off module and unload
456 # of switched-on module. If auto handling is enabled switched-on module
457 # is handled via UReqUn mechanism (unless if implicit_requirement has
458 # been inhibited). Also unloads are triggered by ongoing reload, purge,
459 # restore, reset, stash or stashpop cmds
460 if {(![getConf auto_handling] || [getState inhibit_req_record] eq\
461 [currentState evalid]) && $swlomod ne {} && [aboveCommandName] ni\
462 [list purge reload restore reset stash stashpop]} {
463 # unload mod if it was loaded prior this mod, not user asked and not
464 # required by another loaded module
465 set modlist [getEnvLoadedModulePropertyParsedList name]
466 set modidx [lsearch -exact $modlist [currentState modulename]]
467 if {$modidx != 0} {
468 set priormodlist [lrange $modlist 0 $modidx]
469 if {[set unmod [getLoadedMatchingName $swlomod {} 0\
470 $priormodlist]] ne {}} {
471 cmdModuleUnload urequn match 1 s 1 $unmod
472 }
473 }
474 }
475 }
476 }
477
478 proc cmdModuleSwitch {uasked tag_list old {new {}}} {
479 # if a single name is provided it matches for the module to load and in
480 # this case the module to unload is searched to find the closest match
481 # (loaded module that shares at least the same root name)
482 if {$new eq {}} {
483 set new $old
484 set unload_match close
485 } else {
486 set unload_match match
487 }
488 # save orig names to register them as deps if called from modulefile
489 set argnew $new
490 if {$new eq $old} {
491 set argold {}
492 } else {
493 set argold $old
494 }
495
496 reportDebug "old='$old' new='$new' (uasked=$uasked)"
497
498 # extend requirement recording inhibition to switch subcontext
499 set inhibit_req_rec [expr {[currentState inhibit_req_record] ==\
500 [currentState evalid]}]
501
502 # record sumup messages from underlying unload/load actions under the same
503 # switch message record id to report (evaluation messages still go under
504 # their respective unload/load block
505 if {$uasked} {
506 pushMsgRecordId switch-$old-$new-[depthState modulename]
507 }
508 if {$inhibit_req_rec} {
509 lappendState inhibit_req_record [currentState evalid]
510 }
511
512 pushSettings
513
514 # enable unload of sticky mod if stickiness is preserved on swapped-on mod
515 # need to resolve swapped-off module here to get stickiness details
516 lassign [getPathToModule $old {} 0 $unload_match] modfile oldmod oldmodvr
517 set swunmod_is_supersticky [isModuleTagged $oldmod super-sticky 1 $modfile]
518 lassign [getPathToModule $new {} 0] newmodfile newmod newmodvr
519 set sticky_reload [isStickinessReloading $oldmodvr [list $newmodvr]]
520 set supersticky_reload [isStickinessReloading $oldmodvr [list $newmodvr]\
521 super-sticky]
522 set report_newmod_issue 0
523
524 # do not set sticky or supersticky reload states if swap-on module cannot
525 # be found
526 if {($supersticky_reload || $sticky_reload) && $newmodfile eq {}} {
527 set report_newmod_issue 1
528 set sticky_reload 0
529 set supersticky_reload 0
530 }
531 if {$sticky_reload} {
532 lappendState reloading_sticky $oldmod
533 }
534 if {$supersticky_reload} {
535 lappendState reloading_supersticky $oldmod
536 }
537 ##nagelfar implicitvarcmd {cmdModuleUnload swunload *} oldhidden olduasked\
538 oldmsgrecid
539 set ret_unload [cmdModuleUnload swunload $unload_match 1 s 0 $old]
540 if {$sticky_reload} {
541 lpopState reloading_sticky
542 }
543 if {$supersticky_reload} {
544 lpopState reloading_supersticky
545 }
546
547 # register modulefile to unload as conflict if an unload module is
548 # mentioned on this module switch command set in a modulefile
549 # skip conflict declaration if old spec matches new as in this case switch
550 # means *replace loaded version of mod by this specific version*
551 if {!$uasked && $argold ne {} && ($newmod eq {} || ![modEq $argold $newmod\
552 eqstart])} {
553 registerCurrentModuleConflict $argold
554 }
555
556 # attempt load and depre reload only if unload succeed (or if top switch
557 # evaluation has "continue on error" behavior enabled and switched-off
558 # module is not super-sticky or if sub-evaluation is forced)
559 if {!$ret_unload || ([isTopEvaluation] && ![commandAbortOnError] &&\
560 ![commandAbortOnError switch_unload] && !$swunmod_is_supersticky) ||
561 (![isTopEvaluation] && [getState force])} {
562 ##nagelfar implicitvarcmd {cmdModuleLoad swload *} newhidden newmsgrecid
563 set ret_load [cmdModuleLoad swload $uasked 0 0 $tag_list {} $new]
564
565 # rollback settings if load evaluation went wrong and abort behavior is
566 # enabled for this switch phase
567 if {$ret_load && [commandAbortOnError]} {
568 restoreSettings
569 } else {
570 set ret_auto 0
571 if {[getConf auto_handling] && [isTopEvaluation]} {
572 removeUReqUnFromDepReAndConvertEval
573 unloadUReqUnModules
574
575 # DepRe load phase now other mechanisms are done
576 # Try DepRe load phase: load failure will not make switch fail
577 if {[set ret_auto [catch {
578 reloadDepReModules
579 } errMsg]]} {
580 reportError $errMsg
581 restoreSettings
582 }
583 }
584
585 # report a summary of automated evaluations if no error
586 if {!$ret_auto && $uasked} {
587 reportModuleEval
588 }
589 }
590 } else {
591 # re-run switched-on module search to report locating issue
592 if {$report_newmod_issue} {
593 getPathToModule $new
594 }
595 # initialize dummy load phase msg rec id to query designation
596 set newmsgrecid {}
597 }
598
599 popSettings
600
601 # report all recorded sumup messages for this evaluation unless both old
602 # and new modules are set hidden, old was auto loaded and this switch is
603 # done by a modfile
604 if {$uasked} {
605 reportMsgRecord "Switching from [getModuleDesignation $oldmsgrecid {}\
606 2] to [getModuleDesignation $newmsgrecid $new 2]" [expr {$oldhidden\
607 && !$olduasked && $newhidden && !$uasked}]
608 popMsgRecordId
609 }
610 if {$inhibit_req_rec} {
611 lpopState inhibit_req_record
612 }
613
614 # register modulefile load attempt as prereq when called from modulefile
615 if {!$uasked && [info exists ret_load] && $argnew ne {}} {
616 prereqAnyModfileCmd 0 0 $argnew
617 }
618
619 return [expr {$ret_unload || $ret_load}]
620 }
621
622 proc cmdModuleSave {{coll default}} {
623 if {![areModuleConstraintsSatisfied]} {
624 reportErrorAndExit {Cannot save collection, some module constraints are\
625 not satisfied}
626 }
627
628 # format collection content, version number of modulefile are saved if
629 # version pinning is enabled
630 if {[getConf collection_pin_version]} {
631 set curr_mod_list [getLoadedModuleWithVariantList]
632 set curr_tag_arrser [getLoadedModuleWithVariantSaveTagArrayList]
633 } else {
634 lassign [getSimplifiedLoadedModuleList] curr_mod_list curr_tag_arrser
635 }
636 # generate collection content with header indicating oldest Modules version
637 # compatible with collection syntax
638 ##nagelfar ignore Bad expression
639 set coll_header [expr {[llength $curr_tag_arrser] ? {#%Module5.1} : {}}]
640
641 set save [formatCollectionContent [getModulePathList returnempty 0]\
642 $curr_mod_list $curr_tag_arrser $coll_header]
643
644 if {![string length $save]} {
645 reportErrorAndExit {Nothing to save in a collection}
646 }
647
648 # get corresponding filename and its directory
649 lassign [findCollections $coll name] collfile colldesc
650 set colldir [file dirname $collfile]
651
652 if {![file exists $colldir]} {
653 reportDebug "Creating $colldir"
654 if {[catch {file mkdir $colldir} errMsg]} {
655 reportErrorAndExit "Collection directory cannot be created.\n$errMsg"
656 }
657 } elseif {![file isdirectory $colldir]} {
658 reportErrorAndExit "$colldir exists but is not a directory"
659 }
660
661 reportDebug "Saving $collfile"
662
663 if {[catch {
664 set fid [open $collfile w]
665 puts $fid $save
666 close $fid
667 } errMsg ]} {
668 reportErrorAndExit "Collection $colldesc cannot be saved.\n$errMsg"
669 }
670 }
671
672 proc cmdModuleRestore {args} {
673 # distinguish between zero and one argument provided
674 if {![llength $args]} {
675 set arg_provided 0
676 set coll default
677 } else {
678 set arg_provided 1
679 set coll [lindex $args 0]
680 }
681
682 # get corresponding collection, raise error if it does not exist unless
683 # if no collection name has been provided or if __init__
684 lassign [findCollections $coll exact [expr {!$arg_provided}]\
685 $arg_provided] collfile colldesc
686
687 # forcibly enable implicit_default to restore colls saved in this mode
688 setConf implicit_default 1
689
690 # fetch collection content and differences compared current environment
691 lassign [getDiffBetweenCurEnvAndColl $collfile $colldesc] coll_path_list\
692 coll_mod_list coll_tag_arrser coll_nuasked_list mod_to_unload\
693 mod_to_load path_to_unuse path_to_use is_tags_diff
694 array set coll_tag_arr $coll_tag_arrser
695
696 # create an eval id to track successful/failed module evaluations
697 pushMsgRecordId restore-$coll-[depthState modulename] 0
698
699 # unload modules one by one (no dependency auto unload)
700 foreach mod [lreverse $mod_to_unload] {
701 # test stickiness over full module name version variant designation
702 set modvr [getAndParseLoadedModuleWithVariant $mod]
703 # sticky modules can be unloaded when restoring collection
704 lappendState unloading_sticky $mod
705 if {[set supersticky_reload [isStickinessReloading $modvr $mod_to_load\
706 super-sticky]]} {
707 lappendState reloading_supersticky $mod
708 }
709 cmdModuleUnload unload match 0 s 0 $mod
710 lpopState unloading_sticky
711 if {$supersticky_reload} {
712 lpopState reloading_supersticky
713 }
714 }
715 # unuse paths
716 if {[llength $path_to_unuse]} {
717 cmdModuleUnuse load {*}[lreverse $path_to_unuse]
718 }
719
720 # since unloading a module may unload other modules or
721 # paths, what to load/use has to be determined after
722 # the undo phase, so current situation is fetched again
723 set curr_path_list [getModulePathList returnempty 0]
724
725 set curr_mod_list [getEnvLoadedModulePropertyParsedList name]
726 set curr_nuasked_list [getTaggedLoadedModuleList auto-loaded]
727
728 # update tags sets on the modules already loaded at correct position
729 # remove extra tags that are not defined in collection
730 foreach modvr [getLoadedModuleWithVariantList] {
731 if {[info exists coll_tag_arr($modvr)]} {
732 set tag_list $coll_tag_arr($modvr)
733 } else {
734 set tag_list {}
735 }
736 # indicate if module has been asked by user
737 cmdModuleTag 1 [expr {![isModuleTagged $modvr auto-loaded 1]}]\
738 $tag_list $modvr
739 }
740
741 # determine what module to load to restore collection from current
742 # situation with preservation of the load order
743 # list of alternative and simplified names for loaded modules has been
744 # gathered and cached during the previous getMovementBetweenList call on
745 # modules, so here the getMovementBetweenList call will correctly get these
746 # alternative names for module comparison even if no modulepath is left set
747 lassign [getMovementBetweenList $curr_mod_list $coll_mod_list\
748 $curr_nuasked_list $coll_nuasked_list modeq] mod_to_unload mod_to_load
749
750 # proceed as well for modulepath
751 lassign [getMovementBetweenList $curr_path_list $coll_path_list] \
752 path_to_unuse path_to_use
753
754 # reset implicit_default to restore behavior defined
755 unsetConf implicit_default
756
757 # use paths
758 if {[llength $path_to_use]} {
759 # always append path here to guaranty the order
760 # computed above in the movement lists
761 cmdModuleUse load append {*}$path_to_use
762 }
763
764 # load modules one by one with user asked state preserved
765 foreach mod $mod_to_load {
766 cmdModuleLoad load [expr {$mod ni $coll_nuasked_list}] 0 0\
767 $coll_tag_arr($mod) {} $mod
768 }
769
770 popMsgRecordId 0
771 }
772
773 proc cmdModuleSaverm {{coll default}} {
774 # avoid to remove any kind of file with this command
775 if {[string first / $coll] > -1} {
776 reportErrorAndExit {Command does not remove collection specified as\
777 filepath}
778 }
779
780 # get corresponding collection, raise error if it does not exist, but do
781 # not check if collection is valid
782 lassign [findCollections $coll exact 0 1 0] collfile colldesc
783
784 # attempt to delete specified collection
785 if {[catch {
786 file delete $collfile
787 } errMsg ]} {
788 reportErrorAndExit "Collection $colldesc cannot be removed.\n$errMsg"
789 }
790 }
791
792 proc cmdModuleSaveshow {args} {
793 # distinguish between zero and one argument provided
794 if {![llength $args]} {
795 set arg_provided 0
796 set coll default
797 } else {
798 set arg_provided 1
799 set coll [lindex $args 0]
800 }
801
802 # get corresponding collection, raise error if it does not exist unless
803 # if no collection name has been provided or if __init__
804 lassign [findCollections $coll exact [expr {!$arg_provided}]\
805 $arg_provided] collfile colldesc
806
807 # read specific __init__ collection from __MODULES_LMINIT env var
808 if {$collfile eq {__init__}} {
809 lassign [parseCollectionContent [getEnvLoadedModulePropertyParsedList\
810 init]] coll_path_list coll_mod_list coll_tag_arrser
811 set collfile {initial environment}
812 set coll __init__
813 } else {
814 lassign [readCollectionContent $collfile $colldesc] coll_path_list\
815 coll_mod_list coll_tag_arrser
816 }
817
818 # collection should at least define a path or a mod, but initial env may be
819 # totally empty
820 if {$coll ne {__init__} && ![llength $coll_path_list] && ![llength\
821 $coll_mod_list]} {
822 reportErrorAndExit "$colldesc is not a valid collection"
823 }
824
825 displaySeparatorLine
826 report [sgr hi $collfile]:\n
827 report [formatCollectionContent $coll_path_list $coll_mod_list\
828 $coll_tag_arrser {} 1]
829 displaySeparatorLine
830 }
831
832 proc cmdModuleSavelist {show_oneperline show_mtime search_match args} {
833 # if a target is set, only list collection matching this target (means
834 # having target as suffix in their name) unless if --all option is set
835 set colltarget [getConf collection_target]
836 if {$colltarget ne {} && [getState hiding_threshold] < 2} {
837 set suffix .$colltarget
838 set targetdesc " (for target \"$colltarget\")"
839 } else {
840 set suffix {}
841 set targetdesc {}
842 }
843
844 set json [isStateEqual report_format json]
845
846 reportDebug "list collections$targetdesc"
847
848 # if only stash collection are expected, start result index at 0, sort
849 # results in reverse order (latest first) and ensure only collection from
850 # current target (and no-target if none set) are returned.
851 if {[getCallingProcName] eq {cmdModuleStashlist}} {
852 set start_idx 0
853 set sort_opts [list -dictionary -decreasing]
854 set find_no_other_target 1
855 set typedesc stash
856 # no icase match as stash collections are only lowercases
857 set icase 0
858 } else {
859 set start_idx 1
860 set sort_opts [list -dictionary]
861 set find_no_other_target 0
862 set typedesc named
863 set icase [isIcase]
864 }
865
866 if {[llength $args]} {
867 defineModEqProc $icase 0
868 # match passed name against any part of collection names
869 set mtest [expr {{contains} in $search_match ? {matchin} : {match}}]
870 }
871
872 # prepare header message which depend if search is performed (no search
873 # considered if listing stash collections)
874 if {[llength $args] && $typedesc ne {stash}} {
875 set collmsg "Matching $typedesc collection list$targetdesc:"
876 } else {
877 set collmsg "[string totitle $typedesc] collection list$targetdesc:"
878 }
879
880 foreach collfile [findCollections * glob 0 0 1 $find_no_other_target] {
881 # remove target suffix from names to display
882 regsub $suffix$ [file tail $collfile] {} coll
883 # filter stash collections unless called by stashlist or --all opt set
884 if {$typedesc ne {named} || ![regexp {stash-\d+} $coll] || [getState\
885 hiding_threshold] >= 2} {
886 set coll_arr($coll) $collfile
887 }
888 }
889
890 # same header msg if no collection at all whether search is made or not
891 if {![array exists coll_arr] || $typedesc eq {stash}} {
892 set nocollmsg "No $typedesc collection$targetdesc."
893 } else {
894 set nocollmsg "No matching $typedesc collection$targetdesc."
895 }
896
897 # filter collection not matching any of the passed specification
898 if {[llength $args]} {
899 set matchlist [list]
900 foreach coll [array names coll_arr] {
901 set match 0
902 foreach pattern $args {
903 # compare pattern against collections using comparison module proc
904 # useful for suffix/prefix/icase checks, disabling module-specific
905 # checks (variants, alternative names, etc)
906 if {[modEq $pattern $coll $mtest 0 0 0 0 *]} {
907 set match 1
908 break
909 }
910 }
911 if {!$match} {
912 unset coll_arr($coll)
913 }
914 }
915 }
916
917 if {![array size coll_arr]} {
918 if {!$json} {
919 report $nocollmsg
920 }
921 } else {
922 if {!$json} {
923 if {$show_mtime} {
924 displayTableHeader hi Collection 59 {Last mod.} 19
925 }
926 report $collmsg
927 }
928 set display_list {}
929 set len_list {}
930 set one_per_line [expr {$show_mtime || $show_oneperline}]
931 set show_idx [expr {!$one_per_line}]
932 # prepare query to highlight
933 set himatchmap [prepareMapToHightlightSubstr {*}$args]
934
935 foreach coll [lsort {*}$sort_opts [array names coll_arr]] {
936 if {$json} {
937 lappend display_list [formatListEltToJsonDisplay $coll target s\
938 $colltarget 1 pathname s $coll_arr($coll) 1]
939 # no need to test coll consistency as findCollections does not return
940 # collection whose name starts with "."
941 } else {
942 set collsgr [sgr {} $coll $himatchmap]
943 if {$show_mtime} {
944 set filetime [clock format [getFileMtime $coll_arr($coll)]\
945 -format {%Y/%m/%d %H:%M:%S}]
946 lappend display_list [format %-60s%19s $collsgr $filetime]
947 } else {
948 lappend display_list $collsgr
949 lappend len_list [set len [string length $coll]]
950 }
951 }
952 }
953
954 displayElementList noheader {} {} $one_per_line $show_idx $start_idx\
955 $display_list $len_list
956 }
957 }
958
959
960 proc cmdModuleSource {mode args} {
961 foreach mod $args {
962 set rawarg [getRawArgumentFromVersSpec $mod]
963 if {$mod eq {}} {
964 reportErrorAndExit {File name empty}
965 # first check if raw specification is an existing file
966 } elseif {[file exists [set absfpath [getAbsolutePath $rawarg]]]} {
967 set modfile $absfpath
968 set modname $absfpath
969 set modnamevr $absfpath
970 # unset module specification not to confuse specific char in file
971 # path (like '+') with variant specification
972 unsetModuleVersSpec $mod
973 set mod $absfpath
974 # if not a path specification, try to resolve a modulefile
975 } elseif {![isModuleFullPath $rawarg]} {
976 lassign [getPathToModule $mod] modfile modname modnamevr
977 # stop if no module found, issue has been reported by getPathToModule
978 if {$modfile eq {}} {
979 break
980 }
981 } else {
982 reportErrorAndExit "File $rawarg does not exist"
983 }
984
985 ##nagelfar ignore Found constant
986 lappendState mode $mode
987 # sourced file must also have a magic cookie set at their start
988 ##nagelfar ignore Suspicious variable name
989 execute-modulefile $modfile $modname $modnamevr $mod 1 0 0
990 ##nagelfar ignore Found constant
991 lpopState mode
992 }
993 }
994
995 # Intermediate procedure between module and cmdModuleLoad/prereq
996 # Adapt options and arguments depending on context to call cmdModuleLoad or
997 # one of the prereq procedures
998 proc cmdModuleIntLoad {topcall command mode tag_list args} {
999 # ignore flag used in collection to track non-user asked state
1000 lrem args --notuasked
1001 # no error raised on empty argument list to cope with initadd command that
1002 # may expect this behavior
1003 if {![llength $args]} {
1004 return
1005 }
1006
1007 set ret 0
1008 # if top command is source, consider module load commands made within
1009 # sourced file evaluation as top load command
1010 if {[isTopEvaluation]} {
1011 # is eval a regular attempt or a try (silence not found error)
1012 set tryload [expr {$command in {try-load load-any}}]
1013 set loadany [expr {$command eq {load-any}}]
1014 set ret [cmdModuleLoad load 1 $tryload $loadany $tag_list {} {*}$args]
1015 } elseif {$mode eq {load}} {
1016 # auto load is inhibited if currently in DepRe context only register
1017 # requirement
1018 set subauto [expr {[currentModuleEvalContext] eq {depre} ? {0} : {1}}]
1019 if {$command eq {try-load}} {
1020 # attempt load of not already loaded modules
1021 if {$subauto} {
1022 foreach arg $args {
1023 lassign [loadRequirementModuleList 1 0 $tag_list {} $arg] retlo
1024 # update return value if an issue occurred unless force mode is
1025 # enabled
1026 if {$retlo != 0 && ![getState force]} {
1027 set ret $retlo
1028 }
1029 # record requirement prior raising error
1030 prereqAllModfileCmd 1 0 --optional --tag [join $tag_list :]\
1031 $arg
1032 # report error message and raise error
1033 if {$retlo != 0} {
1034 reportMissingPrereqError [currentState modulenamevr] {} $arg
1035 }
1036 }
1037 } else {
1038 # record requirement as optional: no error if not loaded but
1039 # reload will be triggered if loaded later on
1040 prereqAllModfileCmd 1 0 --optional --tag [join $tag_list :]\
1041 {*}$args
1042 }
1043 } elseif {$command eq {load-any}} {
1044 # load and register requirement in a OR-operation
1045 prereqAnyModfileCmd 1 $subauto --tag [join $tag_list :] {*}$args
1046 } else {
1047 # load and register requirement in a AND-operation
1048 prereqAllModfileCmd 0 $subauto --tag [join $tag_list :] {*}$args
1049 }
1050 # mods unload is handled via UReqUn mechanism when auto enabled (unless if
1051 # implicit_requirement has been inhibited) also unloads are triggered by
1052 # ongoing reload, purge, restore, reset, stash or stashpop cmds
1053 } elseif {(![getConf auto_handling] || [getState inhibit_req_record] eq\
1054 [currentState evalid]) && [aboveCommandName] ni [list purge reload\
1055 restore reset stash stashpop]} {
1056 # on unload mode, unload mods in reverse order, if loaded prior this
1057 # mod, if not user asked and not required by other loaded mods
1058 set modlist [getEnvLoadedModulePropertyParsedList name]
1059 set modidx [lsearch -exact $modlist [currentState modulename]]
1060 if {$modidx != 0} {
1061 set priormodlist [lrange $modlist 0 $modidx]
1062 foreach arg [lreverse $args] {
1063 if {[set unmod [getLoadedMatchingName $arg {} 0 $priormodlist]]\
1064 ne {}} {
1065 cmdModuleUnload urequn match 1 s 1 $unmod
1066 }
1067 }
1068 }
1069 }
1070 # sub-module interpretation failed, raise error
1071 if {$ret && !$topcall} {
1072 knerror {} MODULES_ERR_SUBFAILED
1073 }
1074 }
1075
1076 proc cmdModuleLoad {context uasked tryload loadany tag_list modulepath_list\
1077 args} {
1078 reportDebug "loading $args (context=$context, uasked=$uasked,\
1079 tryload=$tryload, loadany=$loadany, tag_list=$tag_list,\
1080 modulepath_list=$modulepath_list)"
1081
1082 set ret 0
1083 set one_mod_loaded 0
1084
1085 # if a switch action is ongoing...
1086 if {$context eq {swload}} {
1087 set swprocessing 1
1088 # context is ReqLo if switch is called from a modulefile
1089 if {![isTopEvaluation]} {
1090 set context reqlo
1091 }
1092 upvar newhidden hidden
1093 upvar newmsgrecid msgrecid
1094 }
1095
1096 lappendState mode load
1097 lappendState eval_context $context
1098
1099 foreach mod $args {
1100 set mod_load_in_error 0
1101 # stop when first module in list is loaded if any mode enabled
1102 if {$one_mod_loaded && $loadany} {
1103 break
1104 }
1105
1106 # loading module is visible by default
1107 set hidden 0
1108 # error if module not found or forbidden
1109 set notfounderr [expr {!$tryload}]
1110
1111 # first try to resolve over loaded mods unless spec corresponds to
1112 # multiple module designations, otherwise search avail mods
1113 unset -nocomplain modfile
1114 if {[getCmpSpecFromVersSpec $mod] eq {eq}} {
1115 lassign [getPathToModule $mod $modulepath_list 0 exact] modfile\
1116 modname modnamevr
1117 }
1118 if {![info exists modfile] || ![string length $modfile]} {
1119 lassign [getPathToModule $mod $modulepath_list $notfounderr] modfile\
1120 modname modnamevr
1121 }
1122
1123 # record evaluation attempt on specified module name
1124 registerModuleEvalAttempt $context $mod $modfile
1125
1126 # set a unique id to record messages related to this evaluation.
1127 set msgrecid load-$modnamevr-[depthState modulename]
1128
1129 # go to next module to load if not matching module found
1130 if {$modfile eq {}} {
1131 set ret $notfounderr
1132 continue
1133 }
1134
1135 if {[isModuleEvalFailed load $modnamevr]} {
1136 reportDebug "$modnamevr ($modfile) load was already tried and failed"
1137 # nullify this evaluation attempt to avoid duplicate issue report
1138 unregisterModuleEvalAttempt $context $mod $modfile
1139 continue
1140 }
1141
1142 # if a switch action is ongoing...
1143 if {[info exists swprocessing]} {
1144 # transmit loaded mod name for switch report summary
1145 uplevel 1 set new "{$modnamevr}"
1146 }
1147
1148 # register record message unique id (now we know mod will be evaluated)
1149 pushMsgRecordId $msgrecid
1150
1151 # record evaluation attempt on actual module name
1152 registerModuleEvalAttempt $context $modnamevr $modfile
1153 registerModuleEvalAttempt $context $modfile $modfile
1154
1155 # check if passed modname correspond to an already loaded modfile
1156 # and get its loaded name (in case it has been loaded as full path)
1157 set loadedmodname [getLoadedMatchingName $modnamevr]
1158 if {$loadedmodname ne {}} {
1159 set modname $loadedmodname
1160 set modnamevr [getAndParseLoadedModuleWithVariant $modname]
1161 }
1162
1163 # record module title (with the variant specified on load call, and no
1164 # tag list) prior module evaluation to get this title ready in case of
1165 # eval error
1166 registerModuleDesignation $msgrecid $modname [getVariantList $mod 7 0\
1167 1] {}
1168
1169 pushSettings
1170 if {[set errCode [catch {
1171 if {[set isloaded [isModuleLoaded $modname]]} {
1172 set isloading 0
1173 } else {
1174 set isloading [isModuleLoading $modname]
1175 }
1176 if {$isloaded || $isloading} {
1177 # stop if same mod is loaded but from a modulepath not part of
1178 # constrained list
1179 if {($isloaded && ![isLoadedMatchSpecificPath $modname\
1180 $modulepath_list]) || ($isloading &&\
1181 ![isLoadingMatchSpecificPath $modname $modulepath_list])} {
1182 # no error if ConUn mechanism handles unload of this module
1183 if {![getConf auto_handling] || ![getConf conflict_unload] ||\
1184 $isloading} {
1185 knerror [getModFromDiffPathIsLoadedMsg]
1186 }
1187 # stop if same mod is loaded but with a different set of variants
1188 } elseif {[isOtherVariantOfModuleLoaded $modnamevr] ||\
1189 [isOtherVariantOfModuleLoading $modnamevr]} {
1190 # no error if ConUn mechanism handles unload of this module
1191 if {![getConf auto_handling] || ![getConf conflict_unload] ||\
1192 $isloading} {
1193 knerror [getModWithAltVrIsLoadedMsg $modname $isloading]
1194 }
1195 } else {
1196 reportDebug "$modname ($modfile) already loaded/loading"
1197 # apply missing tag to loaded module
1198 set rettag [cmdModuleTag 0 $uasked $tag_list $modname]
1199
1200 # report module is already loaded if verbose2 or higher level
1201 # and no new tag set
1202 if {$isloaded && $rettag != 2 && [isVerbosityLevel verbose2]} {
1203 reportInfo "Module '$modname' is already loaded"
1204 registerModuleDesignation $msgrecid $modname\
1205 [getVariantList $modname 7] [getExportTagList $modname]
1206 reportMsgRecord "Loading [getModuleDesignation $msgrecid {}\
1207 2]"
1208 }
1209
1210 # exit treatment but no need to restore settings
1211 set one_mod_loaded 1
1212 continue
1213 }
1214 }
1215
1216 if {[isTopEvaluation] && ![info exists swprocessing]} {
1217 clearLoadedReqOfReloadingModuleList
1218 clearLoadedReqOfUnloadingModuleList
1219 clearUReqUnFromDepReList
1220 clearDepReList
1221 }
1222
1223 set unload_mod_list {}
1224
1225 # register altname of modname prior any conflict check
1226 setLoadedAltname $modname {*}[getAllModuleResolvedName $modname 1\
1227 $mod]
1228
1229 if {[getConf auto_handling]} {
1230 if {[getConf conflict_unload]} {
1231 # get loaded conflicting modules and unload them (ConUn)
1232 set conun_mod_list [getModuleLoadedConflict $modnamevr\
1233 $modulepath_list]
1234 reportDebug "conun mod list is '$conun_mod_list'"
1235 if {[llength $conun_mod_list]} {
1236 foreach conun_mod $conun_mod_list {
1237 if {[cmdModuleUnload conun match 1 s 0 $conun_mod]} {
1238 # error message already sent within cmdModuleUnload
1239 knerrorOrWarningIfForced {}
1240 }
1241 }
1242 }
1243 lappend unload_mod_list {*}$conun_mod_list
1244 }
1245
1246 # get loaded modules holding a requirement on modname and able to
1247 # be reloaded
1248 set depre_list [getUnmetDependentLoadedModuleList $modnamevr\
1249 $modfile]
1250 reportDebug "depre mod list is '$depre_list'"
1251
1252 if {[isTopEvaluation]} {
1253 saveLoadedReqOfReloadingModuleList $depre_list $unload_mod_list
1254 identityUReqUnFromDepRe $depre_list $unload_mod_list
1255 }
1256
1257 # Reload all modules that have declared a prereq on mod as they
1258 # may take benefit from their prereq availability if it is newly
1259 # loaded. First perform unload phase of the reload, prior mod load
1260 # to ensure these dependent modules are unloaded with the same
1261 # loaded prereq as when they were loaded
1262 unloadDepUnDepReModules {} $depre_list
1263 }
1264
1265 # record additional tags passed through --tag option prior mod eval
1266 # to make them known within evaluation
1267 if {[llength $tag_list]} {
1268 # record tags set with --tag as extra tag excluding tags relative
1269 # to the way module is loaded (auto, keep)
1270 lassign [getDiffBetweenList $tag_list [list auto-loaded\
1271 keep-loaded]] extratag_list
1272 setModuleAndVariantsTag $modname $modnamevr {*}$tag_list
1273 if {[llength $extratag_list]} {
1274 setModuleAndVariantsExtraTag $modname $modnamevr\
1275 {*}$extratag_list
1276 }
1277 }
1278
1279 if {!$uasked} {
1280 # set auto-loaded tag now to be able to query it during eval
1281 setModuleAndVariantsTag $modname $modnamevr auto-loaded
1282 # hide auto loaded modules if hide_auto_loaded config is enabled
1283 if {[getConf hide_auto_loaded]} {
1284 setModuleAndVariantsTag $modname $modnamevr hidden-loaded
1285 }
1286 }
1287
1288 if {[execute-modulefile $modfile $modname modnamevr $mod $uasked]} {
1289 break
1290 }
1291
1292 # register this evaluation on the main one that triggered it (after
1293 # load evaluation to report correct order with other evaluations)
1294 registerModuleEval $context $msgrecid
1295
1296 # loading visibility depends on hidden-loaded tag
1297 set hidden [isModuleTagged $modnamevr hidden-loaded 1 $modfile]
1298
1299 append-path LOADEDMODULES $modname
1300 # allow duplicate modfile entries for virtual modules
1301 append-path --duplicates _LMFILES_ $modfile
1302 # update cache arrays
1303 setLoadedModule $modname $modfile $uasked $modnamevr [expr {$modname\
1304 in [getState refresh_qualified]}]
1305
1306 # register declared source-sh in environment
1307 setEnvLoadedModuleProperty $modname sourcesh [getLoadedSourceSh\
1308 $modname]
1309
1310 # register declared conflict in environment
1311 setEnvLoadedModuleProperty $modname conflict [getLoadedConflict\
1312 $modname]
1313
1314 # declare the prereq of this module
1315 setEnvLoadedModuleProperty $modname prereq [getLoadedPrereq\
1316 $modname]
1317 setEnvLoadedModuleProperty $modname prereqpath [getLoadedPrereqPath\
1318 $modname]
1319
1320 setEnvLoadedModuleProperty $modname use [getLoadedUse $modname]
1321
1322 # declare the alternative names of this module
1323 setEnvLoadedModuleProperty $modname altname [getLoadedAltname\
1324 $modname {sym alias autosym} 1]
1325
1326 # declare the variant of this module
1327 setEnvLoadedModuleProperty $modname variant [getLoadedVariant\
1328 $modname]
1329
1330 # declare the tags of this module
1331 setEnvLoadedModuleProperty $modname tag [getExportTagList $modnamevr\
1332 $modfile]
1333 setEnvLoadedModuleProperty $modname extratag [getExtraTagList\
1334 $modnamevr]
1335 setEnvLoadedModuleProperty $modname stickyrule [getStickyRuleList\
1336 $modnamevr $modfile]
1337
1338 # declare module qualified for refresh evaluation
1339 if {[isModuleRefreshQualified $modname]} {
1340 append-path __MODULES_LMREFRESH $modname
1341 }
1342
1343 if {[getConf auto_handling] && [isTopEvaluation] && ![info exists\
1344 swprocessing]} {
1345 # UReqUn: Useless Requirement to Unload (autoloaded requirements
1346 # not required by any remaining mods)
1347 removeUReqUnFromDepReAndConvertEval
1348 unloadUReqUnModules
1349
1350 # Load phase of dependent module reloading. These modules now can
1351 # adapt since mod is seen loaded.
1352 reloadDepReModules
1353 }
1354
1355 # record module title (name, variants and tags)
1356 registerModuleDesignation $msgrecid $modname [getVariantList\
1357 $modname 7] [getExportTagList $modname $modfile]
1358
1359 # consider evaluation hidden if hidden loaded module is auto loaded
1360 # and no specific messages are recorded for this evaluation
1361 if {$hidden && !$uasked && ![isMsgRecorded]} {
1362 registerModuleEvalHidden $context $msgrecid
1363 }
1364
1365 # report a summary of automated evaluations if no error
1366 reportModuleEval
1367 } errMsg]] != 0 && $errCode != 4} {
1368 set mod_load_in_error 1
1369 # in case of error report module info even if set hidden
1370 set hidden 0
1371 reportError $errMsg
1372 # rollback settings if some evaluation went wrong
1373 set ret 1
1374 restoreSettings
1375 # remove from successfully evaluated module list
1376 registerModuleEval $context $msgrecid $modnamevr load
1377 }
1378 popSettings
1379
1380 # report all recorded messages for this evaluation except if module were
1381 # already loaded
1382 if {$errCode != 4} {
1383 reportMsgRecord "Loading [getModuleDesignation $msgrecid {} 2]"\
1384 [expr {$hidden && !$uasked}]
1385 }
1386 popMsgRecordId
1387
1388 if {$mod_load_in_error} {
1389 # report load issue on the message block of the above action
1390 switch -- $context {
1391 swload {
1392 reportError "Load of switched-on [getModuleDesignation\
1393 $msgrecid] failed"
1394 }
1395 }
1396 }
1397
1398 if {!$mod_load_in_error} {
1399 set one_mod_loaded 1
1400 }
1401
1402 # abort evaluation if error and behavior configured this way (abort
1403 # means stop to evaluate modulefile and flush changes of previous ones)
1404 # applies to top evaluation context for supported sub-commands
1405 if {$ret && $context eq {load} && [commandAbortOnError]} {
1406 flushEnvSettings
1407 break
1408 }
1409 }
1410 lpopState eval_context
1411 lpopState mode
1412
1413 # raise error if no module has been loaded or has produced an error during
1414 # its load attempt in case of top-level load-any sub-command
1415 if {!$ret && !$one_mod_loaded && $context eq {load} && $loadany} {
1416 knerror "No module has been loaded"
1417 }
1418
1419 return $ret
1420 }
1421
1422 # Intermediate procedure between module and cmdModuleUnload
1423 # Adapt options and arguments depending on context to call cmdModuleUnload
1424 proc cmdModuleIntUnload {mode args} {
1425 # if top command is source, consider module load commands made within
1426 # sourced file evaluation as top load command
1427 if {[isTopEvaluation]} {
1428 set ret [cmdModuleUnload unload match 1 s 0 {*}$args]
1429 } elseif {$mode eq {load}} {
1430 # unload mods only on load mode, nothing done on unload mode as the
1431 # registered conflict guarantees the target module cannot be loaded
1432 # unless forced
1433 # enable auto unload and allow force mode if both auto handling and
1434 # conflict unload features are enabled
1435 if {[getConf conflict_unload] && [getConf auto_handling]} {
1436 set conun_mod_list {}
1437 foreach conun_arg $args {
1438 # unload attempt in reverse load order
1439 lappendNoDup conun_mod_list {*}[lreverse [getLoadedMatchingName\
1440 $conun_arg returnall]]
1441 }
1442 set ret 0
1443 foreach conun_mod $conun_mod_list {
1444 if {[cmdModuleUnload conun match 1 s 0 $conun_mod] && ![getState\
1445 force]} {
1446 set ret 1
1447 break
1448 }
1449 }
1450 # otherwise module required by others are not unloaded and force mode is
1451 # disabled
1452 } else {
1453 set ret [cmdModuleUnload conun match 0 0 0 {*}$args]
1454 }
1455
1456 # register modulefiles to unload as individual conflicts
1457 registerCurrentModuleConflict {*}$args
1458
1459 # sub-module interpretation failed, raise error unless if forced
1460 if {$ret && ![getState force]} {
1461 knerror {} MODULES_ERR_SUBFAILED
1462 }
1463 }
1464 }
1465
1466 proc cmdModuleUnload {context match auto force onlyureq args} {
1467 reportDebug "unloading $args (context=$context, match=$match, auto=$auto,\
1468 force=$force, onlyureq=$onlyureq)"
1469
1470 # inherit force mode from force state if asked through arg
1471 if {$force eq {s}} {
1472 ##nagelfar ignore Found constant
1473 set force [getState force]
1474 }
1475 set ret 0
1476
1477 # if a switch action is ongoing...
1478 if {$context eq {swunload}} {
1479 set swprocessing 1
1480 # context is ConUn if switch is called from a modulefile
1481 if {![isTopEvaluation]} {
1482 set context conun
1483 }
1484 upvar oldhidden hidden
1485 upvar olduasked uasked
1486 upvar oldmsgrecid msgrecid
1487 }
1488
1489 lappendState mode unload
1490 lappendState eval_context $context
1491
1492 foreach mod $args {
1493 set mod_unload_in_error 0
1494 # unloading module is visible by default
1495 set hidden 0
1496 set uasked 1
1497
1498 # resolve by also looking at matching loaded module and update mod
1499 # specification to fully match obtained loaded module
1500 # enable report_issue flag to report empty module name issue
1501 lassign [getPathToModule $mod {} 1 $match] modfile modname\
1502 modnamevr errkind
1503
1504 # record evaluation attempt on specified module name
1505 registerModuleEvalAttempt $context $mod $modfile
1506
1507 # set a unique id to record messages related to this evaluation.
1508 set msgrecid unload-$modnamevr-[depthState modulename]
1509
1510 # record module title (with the variant specified on unload call, and no
1511 # tag list) prior module evaluation to get this title ready in case of
1512 # eval error
1513 registerModuleDesignation $msgrecid $modname [getVariantList $modnamevr\
1514 7 0 1] {}
1515
1516 # if a switch action is ongoing...
1517 if {[info exists swprocessing]} {
1518 # transmit unloaded mod name for switch report summary
1519 uplevel 1 set old "{$modnamevr}"
1520 }
1521
1522 if {$modfile eq {}} {
1523 # no error return if module is not loaded
1524 if {$errkind eq {notloaded}} {
1525 reportDebug "$modname is not loaded"
1526 # report module is not loaded if >=verbose2 and not auto context
1527 if {[isVerbosityLevel verbose2] && $context ni {urequn}} {
1528 pushMsgRecordId $msgrecid
1529 reportInfo "Module '$modname' is not loaded"
1530 reportMsgRecord "Unloading [getModuleDesignation $msgrecid {}\
1531 2]"
1532 popMsgRecordId
1533 }
1534 } else {
1535 # return error code in case of empty module name
1536 set ret 1
1537 }
1538 # go to next module to unload
1539 continue
1540 }
1541
1542 if {$onlyureq && ![isModuleUnloadable $modname\
1543 [getUnloadingModuleList]]} {
1544 reportDebug "$modname ($modfile) is required by loaded module or\
1545 asked by user"
1546 continue
1547 }
1548
1549 if {[isModuleEvalFailed unload $modnamevr]} {
1550 reportDebug "$modnamevr ($modfile) unload was already tried and\
1551 failed"
1552 # nullify this evaluation attempt to avoid duplicate issue report
1553 unregisterModuleEvalAttempt $context $mod $modfile
1554 set ret 1
1555 continue
1556 }
1557
1558 # register record message unique id (now we know mod will be evaluated)
1559 pushMsgRecordId $msgrecid
1560
1561 # record evaluation attempt on actual module name
1562 registerModuleEvalAttempt $context $modnamevr $modfile
1563 registerModuleEvalAttempt $context $modfile $modfile
1564
1565 # record module title (name, variants and tags)
1566 registerModuleDesignation $msgrecid $modname [getVariantList $modname\
1567 7] [getExportTagList $modname]
1568
1569 pushSettings
1570 if {[set errCode [catch {
1571 if {[failOrSkipUnloadIfSticky $modname $modfile]} {
1572 continue
1573 }
1574
1575 # stop unless forced or auto handling mode enabled if unloading
1576 # module violates a registered prereq
1577 set prereq_list [getDependentLoadedModuleList [list $modname]]
1578 set prereq_loaded_list [getDependentLoadedModuleList [list $modname]\
1579 1 1 0 0]
1580 if {[llength $prereq_loaded_list] && (![getConf auto_handling] ||\
1581 !$auto)} {
1582 # force mode should not affect if we only look for mods w/o dep
1583 if {$force} {
1584 # in case unload is called for a DepRe mechanism do not warn
1585 # about prereq violation enforced as it is due to the dependent
1586 # module which is already in a violation state
1587 if {$context ne {depre_un}} {
1588 reportWarning [getDepLoadedMsg $prereq_loaded_list]
1589 }
1590 } else {
1591 knerror [expr {[isModuleEvaluated any $modnamevr {}\
1592 {*}$prereq_loaded_list] ? [getDepLoadedMsg\
1593 $prereq_loaded_list] : [getErrPrereqMsg $prereq_loaded_list\
1594 0]}]
1595 }
1596 }
1597 # stop unless forced if loading module are part of dependent modules
1598 # to unload (means module dependencies are inconsistent)
1599 lassign [getDiffBetweenList $prereq_list $prereq_loaded_list]\
1600 prereq_loading_list
1601 if {[llength $prereq_loading_list]} {
1602 knerrorOrWarningIfForced [getDepLoadingMsg $prereq_loading_list]
1603 }
1604
1605 if {[getConf auto_handling] && $auto} {
1606 # compute lists of modules to update due to modname unload prior
1607 # unload to get requirement info before it vanishes
1608
1609 # DepUn: Dependent to Unload (modules actively requiring modname
1610 # or a module part of this DepUn batch)
1611 set depun_list [getDepUnModuleList $modname]
1612 reportDebug "depun mod list is '$depun_list'"
1613
1614 if {[isTopEvaluation]} {
1615 clearLoadedReqOfReloadingModuleList
1616 clearLoadedReqOfUnloadingModuleList
1617 clearUReqUnFromDepReList
1618 clearDepReList
1619 }
1620
1621 set unload_mod_list [list {*}$depun_list $modname]
1622
1623 # DepRe: Dependent to Reload (modules optionally dependent or in
1624 # conflict with modname, DepUn modules + modules dependent of a
1625 # module part of this DepRe batch)
1626 set depre_list [getDependentLoadedModuleList $unload_mod_list 0 0\
1627 1 0 1 1]
1628
1629 # DepUn mods are merged into the DepRe list if this is a conflict
1630 # unload or an ongoing switch
1631 if {[info exists swprocessing] || $context eq {conun}} {
1632 set depre_list [sortModulePerLoadedAndDepOrder [list\
1633 {*}$depun_list {*}$depre_list] 1]
1634 set depun_list {}
1635 set unload_mod_list [list $modname]
1636 reportDebug "updated depun mod list is '$depun_list'"
1637 reportDebug "updated depre mod list is '$depre_list'"
1638 }
1639
1640 if {[isTopEvaluation]} {
1641 saveLoadedReqOfReloadingModuleList $depre_list $unload_mod_list
1642 identityUReqUnFromDepRe $depre_list $unload_mod_list
1643 }
1644
1645 # Unload DepUn modules and unload DepRe modules (unload phase of
1646 # their reload process). These modules are unloaded prior main mod
1647 # unload and they are mixed to be unloaded in their reverse load
1648 # order. They are unloaded this way prior eventually unloading any
1649 # of their requirements.
1650 unloadDepUnDepReModules $depun_list $depre_list
1651 }
1652
1653 # register this evaluation on the main one that triggered it (prior
1654 # unload evaluation to report correct order with other evaluations)
1655 registerModuleEval $context $msgrecid
1656
1657 # module was asked by user if tagged loaded instead of auto-loaded
1658 set uasked [isModuleTagged $modname loaded 1]
1659
1660 # no need to update modnamevr and tags after evaluation as these
1661 # information were already complete in persistent environment
1662 ##nagelfar ignore Suspicious variable name
1663 if {[execute-modulefile $modfile $modname $modnamevr $mod $uasked 0\
1664 0]} {
1665 break
1666 }
1667
1668 # unloading visibility depends on hidden-loaded tag
1669 set hidden [isModuleTagged $modname hidden-loaded 1]
1670
1671 # unset module from list of loaded modules qualified for refresh eval
1672 if {[isModuleRefreshQualified $modname]} {
1673 remove-path __MODULES_LMREFRESH $modname
1674 }
1675
1676 saveLoadedReqOfUnloadingModule $modname
1677
1678 # get module position in loaded list to remove corresponding loaded
1679 # modulefile (entry at same position in _LMFILES_)
1680 # need the unfiltered loaded module list to get correct index
1681 set lmidx [lsearch -exact [getEnvLoadedModulePropertyList name]\
1682 $modname]
1683 remove-path LOADEDMODULES $modname
1684 remove-path --index _LMFILES_ $lmidx
1685 # update cache arrays
1686 unsetLoadedModule $modname $modfile
1687
1688 if {[array exists ::g_isLoadedMatchSpecificPathMemCache]} {
1689 array unset ::g_isLoadedMatchSpecificPathMemCache
1690 }
1691 if {[array exists ::g_isLoadingMatchSpecificPathMemCache]} {
1692 array unset ::g_isLoadingMatchSpecificPathMemCache
1693 }
1694 if {[array exists ::g_loadRequirementModuleListMemCache]} {
1695 array unset ::g_loadRequirementModuleListMemCache
1696 }
1697
1698 # unregister declared source-sh
1699 unsetEnvLoadedModuleProperty $modname sourcesh
1700 unsetLoadedSourceSh $modname
1701
1702 # unregister declared conflict
1703 unsetEnvLoadedModuleProperty $modname conflict
1704 unsetLoadedConflict $modname
1705
1706 # unset prereq declared for this module
1707 unsetEnvLoadedModuleProperty $modname prereq
1708 unsetLoadedPrereq $modname
1709 unsetEnvLoadedModuleProperty $modname prereqpath
1710 unsetLoadedPrereqPath $modname
1711
1712 unsetEnvLoadedModuleProperty $modname use
1713 unsetLoadedUse $modname
1714
1715 # unset alternative names declared for this module
1716 unsetEnvLoadedModuleProperty $modname altname
1717 unsetLoadedAltname $modname
1718
1719 # unset variant declared for this module
1720 unsetEnvLoadedModuleProperty $modname variant
1721 unsetLoadedVariant $modname
1722
1723 # unset tags declared for this module
1724 unsetEnvLoadedModuleProperty $modname tag
1725 # also remove tags from in-memory knowledge not to re-apply them if
1726 # module is reloaded in other conditions
1727 unsetModuleAndVariantsTag $modname $modnamevr
1728 unsetEnvLoadedModuleProperty $modname extratag
1729 unsetModuleAndVariantsExtraTag $modname $modnamevr
1730 unsetEnvLoadedModuleProperty $modname stickyrule
1731
1732 if {[getConf auto_handling] && $auto && [isTopEvaluation] &&\
1733 ![info exists swprocessing]} {
1734 # UReqUn: Useless Requirement to Unload (autoloaded requirements
1735 # not required by any remaining mods)
1736 removeUReqUnFromDepReAndConvertEval
1737 unloadUReqUnModules
1738
1739 # DepRe modules load phase now DepUn+UReqUn+main mods are unloaded
1740 reloadDepReModules
1741 }
1742
1743 # consider evaluation hidden if hidden loaded module was auto loaded
1744 # and no specific messages are recorded for this evaluation
1745 if {$hidden && !$uasked && ![isMsgRecorded]} {
1746 registerModuleEvalHidden $context $msgrecid
1747 }
1748
1749 # report a summary of automated evaluations if no error
1750 reportModuleEval
1751 } errMsg]] != 0 && $errCode != 4} {
1752 set mod_unload_in_error 1
1753 # report module error even if set hidden
1754 set hidden 0
1755 reportError $errMsg
1756 # rollback settings if some evaluation went wrong
1757 set ret 1
1758 restoreSettings
1759 # remove from successfully evaluated module list
1760 registerModuleEval $context $msgrecid $modnamevr unload
1761 }
1762 popSettings
1763
1764 # report all recorded messages for this evaluation (hide evaluation if
1765 # loaded mod is set hidden, has been automatically loaded and unloaded)
1766 reportMsgRecord "Unloading [getModuleDesignation $msgrecid {} 2]" [expr\
1767 {$hidden && !$uasked && [depthState evalid] != 1}]
1768 popMsgRecordId
1769
1770 if {$mod_unload_in_error} {
1771 # report unload issue on the message block of the above action
1772 switch -- $context {
1773 swunload {
1774 reportError "Unload of switched-off [getModuleDesignation\
1775 loaded $modname] failed"
1776 }
1777 conun {
1778 setConflictErrorAsReported $modname
1779 reportErrorOrWarningIfForced [getErrConUnMsg\
1780 [getModuleDesignation loaded $modname]]
1781 }
1782 urequn {
1783 # warn and do not count urequn unload error
1784 reportWarning "Unload of useless requirement\
1785 [getModuleDesignation loaded $modname] failed"
1786 decrErrorCount
1787 }
1788 }
1789 }
1790
1791 # abort evaluation if error and behavior configured this way (abort
1792 # means stop to evaluate modulefile and flush changes of previous ones)
1793 # applies to top evaluation context for supported sub-commands
1794 if {$ret && $context eq {unload} && [commandAbortOnError]} {
1795 flushEnvSettings
1796 break
1797 }
1798 }
1799 lpopState eval_context
1800 lpopState mode
1801
1802 return $ret
1803 }
1804
1805 proc cmdModulePurge {} {
1806 # create an eval id to track successful/failed module evaluations
1807 pushMsgRecordId purge-[depthState modulename] 0
1808
1809 # unload one by one to ensure same behavior whatever auto_handling state
1810 # force it to handle loaded modules in violation state
1811 # remove dependent modules if force mode enabled
1812 cmdModuleUnload unload match 0 s 0 {*}[lreverse\
1813 [getEnvLoadedModulePropertyParsedList name]]
1814
1815 popMsgRecordId 0
1816 }
1817
1818 proc cmdModuleReload {} {
1819 # reload all loaded modules
1820 set loaded_mod_list [getEnvLoadedModulePropertyParsedList name]
1821 reportDebug "reloading $loaded_mod_list"
1822
1823 # create an eval id to track successful/failed module evaluations
1824 pushMsgRecordId reload-[depthState modulename] 0
1825
1826 # no reload of all loaded modules attempt if constraints are violated
1827 if {![areModuleConstraintsSatisfied]} {
1828 reportError {Cannot reload modules, some of their constraints are not\
1829 satisfied}
1830 } else {
1831 pushSettings
1832 if {[set errCode [catch {
1833 # run unload then load-again phases
1834 set loaded_mod_list [reloadModuleListUnloadPhase $loaded_mod_list]
1835 reloadModuleListLoadPhase $loaded_mod_list
1836 } errMsg]] == 1} {
1837 # rollback settings if some evaluation went wrong
1838 restoreSettings
1839 }
1840 popSettings
1841 }
1842
1843 popMsgRecordId 0
1844 }
1845
1846 proc cmdModuleAliases {} {
1847 # disable error reporting to avoid modulefile errors
1848 # to mix with avail results
1849 inhibitErrorReport
1850
1851 # parse paths to fill g_moduleAlias and g_moduleVersion
1852 foreach dir [getModulePathList exiterronundef] {
1853 getModules $dir {} 0 {}
1854 }
1855
1856 uninhibitErrorReport
1857
1858 set display_list {}
1859 foreach name [lsort -dictionary [array names ::g_moduleAlias]] {
1860 # exclude hidden aliases from result
1861 if {![isModuleHidden $name]} {
1862 lappend display_list "[sgr al $name] -> $::g_moduleAlias($name)"
1863 }
1864 }
1865 displayElementList Aliases hi sepline 1 0 0 $display_list
1866
1867 set display_list {}
1868 foreach name [lsort -dictionary [array names ::g_moduleVersion]] {
1869 # exclude hidden versions or versions targeting an hidden module
1870 if {![isModuleHidden $name] && ![isModuleHidden\
1871 $::g_moduleVersion($name)]} {
1872 lappend display_list "[sgr sy $name] -> $::g_moduleVersion($name)"
1873 }
1874 }
1875 displayElementList Versions hi sepline 1 0 0 $display_list
1876 }
1877
1878 proc cmdModuleAvail {show_oneperline show_mtime show_filter search_filter\
1879 search_match modpath_list args} {
1880 if {![llength $args]} {
1881 lappend args *
1882 }
1883
1884 if {$show_mtime || $show_oneperline} {
1885 set one_per_line 1
1886 set hstyle terse
1887 set theader_cols [list hi Package/Alias 39 Versions 19 {Last mod.} 19]
1888 } else {
1889 set one_per_line 0
1890 set hstyle sepline
1891 set theader_cols {}
1892 }
1893
1894 # set a default filter (do not print dirs with no sym) if none set
1895 if {$show_filter eq {}} {
1896 set show_filter noplaindir
1897 }
1898
1899 # elements to include in output
1900 set report_modulepath [isEltInReport modulepath]
1901
1902 # consolidate search filters
1903 lappend search_filter $search_match wild
1904 set search_rc_filter $search_filter
1905 lappend search_rc_filter rc_alias_only
1906
1907 # disable error report to avoid modulefile errors to mix with avail results
1908 inhibitErrorReport
1909
1910 # look if aliases have been defined in the global or user-specific rc
1911 array set mod_list [getMatchingAnyModules {} $args $show_mtime\
1912 $search_rc_filter $show_filter]
1913 if {$report_modulepath} {
1914 reportModules $args {global/user modulerc} hi $hstyle $show_mtime 0\
1915 $one_per_line $theader_cols hidden-loaded
1916 }
1917
1918 foreach dir $modpath_list {
1919 set dir_mod_list [getMatchingAnyModules $dir $args $show_mtime\
1920 $search_filter $show_filter]
1921 if {$report_modulepath} {
1922 array unset mod_list
1923 array set mod_list $dir_mod_list
1924 reportModules $args $dir mp $hstyle $show_mtime 0 $one_per_line\
1925 $theader_cols hidden-loaded
1926 } else {
1927 # add result if not already added from an upper priority modpath
1928 foreach {elt props} $dir_mod_list {
1929 if {![info exists mod_list($elt)]} {
1930 set mod_list($elt) $props
1931 }
1932 }
1933 }
1934 }
1935
1936 # no report by modulepath, mix all aggregated results
1937 if {!$report_modulepath} {
1938 reportModules $args noheader {} {} $show_mtime 0 $one_per_line\
1939 $theader_cols hidden-loaded
1940 }
1941
1942 # display output key
1943 if {!$show_mtime && ![isStateEqual report_format json] && [isEltInReport\
1944 key]} {
1945 displayKey
1946 }
1947
1948 uninhibitErrorReport
1949 }
1950
1951 proc runModuleUse {cmd mode pos args} {
1952 if {$args eq {}} {
1953 showModulePath
1954 } else {
1955 foreach path $args {
1956 switch -glob -- $path {
1957 --remove-on-unload - --append-on-unload - --prepend-on-unload -\
1958 --noop-on-unload {
1959 if {$cmd ne {unuse}} {
1960 knerror "Invalid option '$path'"
1961 } else {
1962 lappend pathlist $path
1963 }
1964 }
1965 -* {
1966 knerror "Invalid option '$path'"
1967 }
1968 {} {
1969 reportError [getEmptyNameMsg directory]
1970 }
1971 $* {
1972 lappend pathlist $path
1973 }
1974 default {
1975 if {$pos eq {remove}} {
1976 # transmit path as registered in MODULEPATH env var, where
1977 # variable references are kept as-is. even if not found,
1978 # transmit given path to remove-path in case several path
1979 # elements have been joined as one string
1980 if {[set usedpath [getUsedModulePathEntry $path 0]] ne\
1981 {}} {
1982 lappend pathlist $usedpath
1983 } else {
1984 lappend pathlist $path
1985 }
1986 } else {
1987 # transform given path in an absolute path to avoid
1988 # dependency to the current work directory. except if this
1989 # path starts with a variable reference
1990 lappend pathlist [getAbsolutePath $path]
1991 }
1992 }
1993 }
1994 }
1995
1996 # added directory may not exist at this time
1997 # pass all paths specified at once to append-path/prepend-path
1998 if {[info exists pathlist]} {
1999 set optlist [list]
2000 # define path command to call
2001 set pathcmd [expr {$pos eq {remove} ? {unload-path} : {add-path}}]
2002
2003 # by-pass any reference counter in case use is called from top level
2004 # not to increase reference counter if paths are already defined
2005 if {[isTopEvaluation]} {
2006 lappend optlist --ignore-refcount
2007 }
2008
2009 if {[isTopEvaluation]} {
2010 ##nagelfar ignore Found constant
2011 lappendState mode load
2012 }
2013 $pathcmd $pos-path $mode $pos {*}$optlist MODULEPATH {*}$pathlist
2014 if {[isTopEvaluation]} {
2015 ##nagelfar ignore Found constant
2016 lpopState mode
2017 }
2018 }
2019 }
2020 }
2021
2022 proc cmdModuleUse {mode pos args} {
2023 if {$mode eq {unload}} {
2024 set pos remove
2025 }
2026 runModuleUse use $mode $pos {*}$args
2027 }
2028
2029 proc cmdModuleUnuse {mode args} {
2030 runModuleUse unuse $mode remove {*}$args
2031 }
2032
2033 proc cmdModuleAutoinit {} {
2034 # skip autoinit process if found already ongoing in current environment
2035 if {[envVarEquals __MODULES_AUTOINIT_INPROGRESS 1]} {
2036 return
2037 }
2038
2039 # set environment variable to state autoinit process is ongoing
2040 setenv __MODULES_AUTOINIT_INPROGRESS 1
2041
2042 # flag to make renderSettings define the module command
2043 setState autoinit 1
2044
2045 # initialize env variables around module command
2046 lappendState mode load
2047
2048 # register command location
2049 setenv MODULES_CMD [getAbsolutePath $::argv0]
2050
2051 # define current Modules version if versioning enabled
2052 ##nagelfar ignore #4 Strange command
2053 ##nagelfar ignore +3 Too long line
2054 @VERSIONING@if {![isEnvVarDefined MODULE_VERSION]} {
2055 @VERSIONING@ setenv MODULE_VERSION @MODULES_RELEASE@@MODULES_BUILD@
2056 @VERSIONING@ setenv MODULE_VERSION_STACK @MODULES_RELEASE@@MODULES_BUILD@
2057 @VERSIONING@}
2058
2059 # initialize MODULEPATH and LOADEDMODULES if found unset
2060 if {![isEnvVarDefined MODULEPATH]} {
2061 setenv MODULEPATH {}
2062 }
2063 if {![isEnvVarDefined LOADEDMODULES]} {
2064 setenv LOADEDMODULES {}
2065 }
2066
2067 # initialize user environment if found undefined (both MODULEPATH and
2068 # LOADEDMODULES empty)
2069 if {[get-env MODULEPATH] eq {} && [get-env LOADEDMODULES] eq {}} {
2070 # set modpaths defined in modulespath config file if it exists
2071 # use .modulespath file in initdir if conf file are located in this dir
2072 if {[file readable {@modulespath@}]} {
2073 set fdata [split [readFile {@modulespath@}] \n]
2074 foreach fline $fdata {
2075 if {[regexp {^\s*(.*?)\s*(#.*|)$} $fline match patharg] &&\
2076 $patharg ne {}} {
2077 foreach path [split $patharg :] {
2078 # resolve path directory in case wildcard character used
2079 set globlist [glob -types d -nocomplain $path]
2080 if {![llength $globlist]} {
2081 lappend pathlist $path
2082 } else {
2083 lappend pathlist {*}$globlist
2084 }
2085 }
2086 }
2087 }
2088 if {[info exists pathlist]} {
2089 cmdModuleUse load append {*}$pathlist
2090 }
2091 }
2092
2093 # source initialization initrc after modulespaths if it exists
2094 # use modulerc file in initdir if conf files are located in this dir
2095 if {[file exists {@initrc@}]} {
2096 lappendState commandname source
2097 cmdModuleSource load {@initrc@}
2098 lpopState commandname
2099 }
2100
2101 # record what has just been loaded in the virtual init collection
2102 setenv __MODULES_LMINIT [getLoadedInit]
2103 # if user environment is already initialized, refresh already loaded mods
2104 } else {
2105 cmdModuleRefresh
2106 }
2107
2108 # default MODULESHOME
2109 setenv MODULESHOME [getConf home]
2110
2111 # append dir where to find module function for ksh (to get it defined in
2112 # interactive and non-interactive sub-shells). also applies for shells
2113 # listed in shells_with_ksh_fpath conf
2114 if {[getState shell] in [list {*}[getConfList shells_with_ksh_fpath] \
2115 ksh]} {
2116 append-path FPATH {@initdir@/ksh-functions}
2117 }
2118
2119 # define Modules init script as shell startup file
2120 if {[getConf set_shell_startup] && [getState shelltype] in [list sh csh\
2121 fish]} {
2122 # setup ENV variables to get module defined in sub-shells (works for
2123 # 'sh' and 'ksh' in interactive mode and 'sh' (zsh-compat), 'bash' and
2124 # 'ksh' (zsh-compat) in non-interactive mode.
2125 setenv ENV {@initdir@/profile.sh}
2126 setenv BASH_ENV {@initdir@/bash}
2127 }
2128
2129 if {[getState shelltype] in {sh csh fish}} {
2130 # add Modules bin directory to PATH if enabled but do not increase ref
2131 # counter variable if already there
2132 ##nagelfar ignore #26 Strange command
2133 @setbinpath@if {{@bindir@} ni [split [get-env PATH] :]} {
2134 @setbinpath@@appendbinpath@-path --ignore-refcount PATH {@bindir@}
2135 @setbinpath@}
2136
2137 # add Modules man directory to MANPATH if enabled
2138 # initialize MANPATH if not set with a value that preserves manpath
2139 # system configuration even after addition of paths to this variable by
2140 # modulefiles
2141 @setmanpath@set manpath {}
2142 # use manpath tool if found at configure step, use MANPATH otherwise
2143 ##nagelfar ignore +2 Too long line
2144 ##nagelfar ignore Found constant
2145 @setmanpath@@usemanpath@catch {set manpath [exec -ignorestderr 2>/dev/null manpath]}
2146 @setmanpath@@notusemanpath@if {[isEnvVarDefined MANPATH]} {
2147 @setmanpath@@notusemanpath@ set manpath $::env(MANPATH)
2148 @setmanpath@@notusemanpath@}
2149 @setmanpath@if {{@mandir@} ni [split $manpath :]} {
2150 @setmanpath@ if {![isEnvVarDefined MANPATH]} {
2151 @setmanpath@ if {![hasEnvVarInitValue MANPATH] || [envVarInitValue MANPATH] ne\
2152 @setmanpath@ {}} {
2153 @setmanpath@ append-path MANPATH {}
2154 @setmanpath@ }
2155 @setmanpath@ # ensure no duplicate ':' is set
2156 @setmanpath@ } elseif {[envVarEquals MANPATH :]} {
2157 @setmanpath@ remove-path MANPATH {}
2158 @setmanpath@ append-path MANPATH {}
2159 @setmanpath@ }
2160 @setmanpath@ @appendmanpath@-path MANPATH {@mandir@}
2161 @setmanpath@}
2162 }
2163
2164 # add env_modules python module directory to PYTHONPATH if enabled
2165 @setpythonpath@if {{@pythondir@} ni [split [get-env PYTHONPATH] :]} {
2166 @setpythonpath@ @appendpythonpath@-path PYTHONPATH {@pythondir@}
2167 @setpythonpath@}
2168
2169 # source shell completion script if available, not installed in default
2170 # completion locations and only if shell is interactive
2171 if {[getState shell] in {@shellcompsource@} && [getState is_stderr_tty]} {
2172 set compfile "@initdir@/[getState shell]_completion"
2173 if {[file readable $compfile]} {
2174 putsModfileCmd dummy "source '$compfile';"
2175 }
2176 }
2177
2178 # clear in progress flag
2179 unsetenv __MODULES_AUTOINIT_INPROGRESS
2180
2181 lpopState mode
2182 }
2183
2184 proc cmdModuleInit {args} {
2185 set init_list [lassign $args init_cmd]
2186 set notdone 1
2187 set nomatch 1
2188
2189 # Define startup files for each shell
2190 set files(csh) [list .modules .cshrc .cshrc_variables .login]
2191 set files(tcsh) [list .modules .tcshrc .cshrc .cshrc_variables .login]
2192 set files(sh) [list .modules .bash_profile .bash_login .profile .bashrc]
2193 set files(bash) $files(sh)
2194 set files(ksh) $files(sh)
2195 set files(fish) [list .modules .config/fish/config.fish]
2196 set files(zsh) [list .modules .zshrc .zshenv .zlogin]
2197
2198 # Process startup files for this shell
2199 set current_files $files([getState shell])
2200 foreach filename $current_files {
2201 if {$notdone} {
2202 set filepath $::env(HOME)
2203 append filepath / $filename
2204
2205 reportDebug "Looking at $filepath"
2206 if {[file readable $filepath] && [file isfile $filepath]} {
2207 set newinit {}
2208 set thismatch 0
2209
2210 foreach curline [split [readFile $filepath] \n] {
2211 # Find module load/add command in startup file
2212 set comments {}
2213 if {$notdone && [regexp {^([ \t]*module[ \t]+(load|add)[\
2214 \t]*)(.*)} $curline match cmd subcmd modules]} {
2215 set nomatch 0
2216 set thismatch 1
2217 regexp {([ \t]*\#.+)} $modules match comments
2218 regsub {\#.+} $modules {} modules
2219
2220 # remove existing references to the named module from
2221 # the list Change the module command line to reflect the
2222 # given command
2223 switch -- $init_cmd {
2224 list {
2225 if {![info exists notheader]} {
2226 report "[getState shell] initialization file\
2227 \$HOME/$filename loads modules:"
2228 set notheader 0
2229 }
2230 report \t$modules
2231 }
2232 add {
2233 foreach newmodule $init_list {
2234 lrem modules $newmodule
2235 }
2236 lappend newinit "$cmd$modules $init_list$comments"
2237 # delete new modules in potential next lines
2238 set init_cmd rm
2239 }
2240 prepend {
2241 foreach newmodule $init_list {
2242 lrem modules $newmodule
2243 }
2244 lappend newinit "$cmd$init_list $modules$comments"
2245 # delete new modules in potential next lines
2246 set init_cmd rm
2247 }
2248 rm {
2249 set oldmodcount [llength $modules]
2250 foreach oldmodule $init_list {
2251 lrem modules $oldmodule
2252 }
2253 set modcount [llength $modules]
2254 lappend newinit [expr {$modcount ?\
2255 "$cmd$modules$comments" : [string trim $cmd]}]
2256 if {$oldmodcount > $modcount} {
2257 set notdone 0
2258 }
2259 }
2260 switch {
2261 set oldmodule [lindex $init_list 0]
2262 set newmodule [lindex $init_list 1]
2263 set newmodules [replaceFromList $modules\
2264 $oldmodule $newmodule]
2265 lappend newinit $cmd$newmodules$comments
2266 if {$modules ne $newmodules} {
2267 set notdone 0
2268 }
2269 }
2270 clear {
2271 lappend newinit [string trim $cmd]
2272 }
2273 }
2274 } elseif {$curline ne {}} {
2275 # copy the line from the old file to the new
2276 lappend newinit $curline
2277 }
2278 }
2279
2280 if {$init_cmd ne {list} && $thismatch} {
2281 reportDebug "Writing $filepath"
2282 if {[catch {
2283 set fid [open $filepath w]
2284 puts $fid [join $newinit \n]
2285 close $fid
2286 } errMsg ]} {
2287 reportErrorAndExit "Init file $filepath cannot be\
2288 written.\n$errMsg"
2289 }
2290 }
2291 }
2292 }
2293 }
2294
2295 # quit in error if command was not performed due to no match
2296 if {$nomatch && $init_cmd ne {list}} {
2297 reportErrorAndExit "Cannot find a 'module load' command in any of the\
2298 '[getState shell]' startup files"
2299 }
2300 }
2301
2302 # provide access to modulefile specific commands from the command-line, making
2303 # them standing as a module sub-command (see module procedure)
2304 proc cmdModuleResurface {cmd args} {
2305 lappendState mode load
2306 lappendState commandname $cmd
2307
2308 set optlist [list]
2309 switch -- $cmd {
2310 prepend-path - append-path - remove-path {
2311 # by-pass any reference counter, as call is from top level
2312 # append/prepend-path: not to increase reference counter if paths are
2313 # already defined. remove-path: to ensure paths are removed whatever
2314 # their reference counter value
2315 lappend optlist --ignore-refcount
2316
2317 # sync environment variable changes if some links are defined
2318 if {[llength [getState linked_envvars]]} {
2319 trace add execution $cmd leave mirrorEnvVarChange
2320 }
2321 }
2322 }
2323
2324 # run modulefile command and get its result
2325 if {[catch {$cmd {*}$optlist {*}$args} res]} {
2326 # report error if any and return false
2327 reportError $res
2328 } else {
2329 # register result depending of return kind (false or text)
2330 switch -- $cmd {
2331 module-info {
2332 set ::g_return_text $res
2333 }
2334 default {
2335 if {$res == 0} {
2336 # render false if command returned false
2337 setState return_false 1
2338 }
2339 }
2340 }
2341 }
2342
2343 lpopState commandname
2344 lpopState mode
2345 }
2346
2347 proc cmdModuleTest {args} {
2348 lappendState mode test
2349 set first_report 1
2350 foreach mod $args {
2351 lassign [getPathToModule $mod] modfile modname modnamevr
2352 if {$modfile ne {}} {
2353 # only one separator lines between 2 modules
2354 if {$first_report} {
2355 displaySeparatorLine
2356 set first_report 0
2357 }
2358 report "Module Specific Test for [sgr hi $modfile]:\n"
2359 execute-modulefile $modfile $modname modnamevr $mod 1
2360 displaySeparatorLine
2361 }
2362 }
2363 lpopState mode
2364 }
2365
2366 proc cmdModuleClear {args} {
2367 # fetch confirmation if no arg passed and force mode disabled
2368 if {![llength $args] && ![getState force]} {
2369 # ask for it if stdin is attached to a terminal
2370 if {![catch {fconfigure stdin -mode}]} {
2371 report "Are you sure you want to clear all loaded modules!? \[n\] " 1
2372 flush [getState reportfd]
2373 }
2374 # fetch stdin content even if not attached to terminal in case some
2375 # content has been piped to this channel
2376 set doit [gets stdin]
2377 } else {
2378 set doit [lindex $args 0]
2379 }
2380
2381 # should be confirmed or forced to proceed
2382 if {[string equal -nocase -length 1 $doit y] || [getState force]} {
2383 lappendState mode load
2384 # unset all Modules runtime variables
2385 foreach globvar [getModulesEnvVarGlobList 1] {
2386 foreach var [array names ::env -glob $globvar] {
2387 unset-env $var
2388 }
2389 }
2390 lpopState mode
2391 } else {
2392 reportInfo "Modules runtime information were not cleared"
2393 }
2394 }
2395
2396 proc cmdModuleState {args} {
2397 if {[llength $args]} {
2398 set name [lindex $args 0]
2399 }
2400
2401 if {[info exists name] && $name ni [concat [array names ::g_state_defs]\
2402 [array names ::g_states]]} {
2403 knerror "State '$name' does not exist"
2404 }
2405
2406 # report module version unless if called by cmdModuleConfig
2407 if {[getCallingProcName] ne {cmdModuleConfig}} {
2408 reportVersion
2409 reportSeparateNextContent
2410 }
2411
2412 displayTableHeader hi {State name} 24 {Value} 54
2413
2414 # fetch specified state or all states
2415 if {[info exists name]} {
2416 if {$name in [array names ::g_state_defs]} {
2417 set stateval($name) [getState $name <undef> 1]
2418 } else {
2419 set stateval($name) [getState $name]
2420 }
2421 } else {
2422 # define each attribute/fetched state value pair
2423 foreach state [array names ::g_state_defs] {
2424 set stateval($state) [getState $state <undef> 1]
2425 }
2426 # also get dynamic states (with no prior definition)
2427 foreach state [array names ::g_states] {
2428 if {![info exists stateval($state)]} {
2429 set stateval($state) [getState $state]
2430 }
2431 }
2432 }
2433
2434 foreach state [lsort [array names stateval]] {
2435 append displist [format {%-25s %s} $state $stateval($state)] \n
2436 }
2437 report $displist 1
2438 reportSeparateNextContent
2439
2440 # only report specified state if any
2441 if {[info exists name]} {
2442 return
2443 }
2444
2445 # report environment variable set related to Modules
2446 displayTableHeader hi {Env. variable} 24 {Value} 54
2447 set envvar_list {}
2448 foreach var [getModulesEnvVarGlobList] {
2449 lappend envvar_list {*}[array names ::env -glob $var]
2450 }
2451 unset displist
2452 foreach var [lsort -unique $envvar_list] {
2453 append displist [format {%-25s %s} $var $::env($var)] \n
2454 }
2455 report $displist 1
2456 }
2457
2458 proc cmdModuleConfig {dump_state args} {
2459 # parse arguments
2460 set nameunset 0
2461 switch -- [llength $args] {
2462 1 {
2463 lassign $args name
2464 }
2465 2 {
2466 lassign $args name value
2467 # check if configuration should be set or unset
2468 if {$name eq {--reset}} {
2469 set name $value
2470 set nameunset 1
2471 unset value
2472 }
2473 }
2474 }
2475
2476 reportDebug "dump_state='$dump_state', reset=$nameunset,\
2477 name=[expr {[info exists name] ? "'$name'" : {<undef>}}], value=[expr\
2478 {[info exists value] ? "'$value'" : {<undef>}}]"
2479
2480 foreach option [array names ::g_config_defs] {
2481 lassign $::g_config_defs($option) confvar($option) defval\
2482 conflockable($option) confkind($option) confvalid($option) vtrans\
2483 initproc confvalidkind($option)
2484 set confval($option) [getConf $option <undef>]
2485 set confvtrans($option) {}
2486 for {set i 0} {$i < [llength $vtrans]} {incr i} {
2487 lappend confvtrans($option) [lindex $vtrans $i] [lindex\
2488 $confvalid($option) $i]
2489 }
2490 }
2491
2492 # catch any environment variable set for modulecmd run-time execution
2493 foreach runenvvar [array names ::env -glob MODULES_RUNENV_*] {
2494 set runenvconf [string tolower [string range $runenvvar 8 end]]
2495 set confval($runenvconf) [get-env $runenvvar]
2496 # enable modification of runenv conf
2497 set confvar($runenvconf) $runenvvar
2498 set confvalid($runenvconf) {}
2499 set conflockable($runenvconf) {}
2500 set confkind($runenvconf) s
2501 set confvtrans($runenvconf) {}
2502 set confvalidkind($runenvconf) {}
2503 }
2504
2505 if {[info exists name] && ![info exists confval($name)]} {
2506 reportErrorAndExit "Configuration option '$name' does not exist"
2507 # set configuration
2508 } elseif {[info exists name] && ($nameunset || [info exists value])} {
2509 # append or subtract value to existing configuration value if new value
2510 # starts with '+' or '-' (for colon-separated list option only)
2511 if {[info exists value] && $confkind($name) eq {l}} {
2512 set curconfvallist [getConfList $name]
2513 switch -- [string index $value 0] {
2514 + {
2515 lappendNoDup curconfvallist {*}[split [string range $value 1\
2516 end] :]
2517 set value [join $curconfvallist :]
2518 }
2519 - {
2520 lassign [getDiffBetweenList $curconfvallist [split [string\
2521 range $value 1 end] :]] curconfvallist
2522 set value [join $curconfvallist :]
2523 }
2524 }
2525 }
2526
2527 if {$confvar($name) eq {}} {
2528 reportErrorAndExit "Configuration option '$name' cannot be altered"
2529 } elseif {$conflockable($name) eq {1} && [isConfigLocked $name]} {
2530 reportErrorAndExit "Configuration option '$name' is locked"
2531 } elseif {$nameunset} {
2532 # unset configuration variable
2533 lappendState mode load
2534 unsetenv $confvar($name)
2535 lpopState mode
2536 } elseif {[llength $confvalid($name)]} {
2537 switch -- $confvalidkind($name) {
2538 eltlist {
2539 # check each element in value list
2540 if {[isDiffBetweenList [split $value :] $confvalid($name)]} {
2541 reportErrorAndExit "Invalid element in value list for\
2542 config. option '$name'\nAllowed elements are:\
2543 $confvalid($name) (separated by ':')"
2544 } else {
2545 set validval 1
2546 }
2547 }
2548 intbe {
2549 if {[string is integer -strict $value] && $value >= [lindex\
2550 $confvalid($name) 0] && $value <= [lindex $confvalid($name)\
2551 1]} {
2552 set validval 1
2553 } else {
2554 reportErrorAndExit "Invalid value for configuration option\
2555 '$name'\nValue should be an integer comprised between\
2556 [lindex $confvalid($name) 0] and [lindex\
2557 $confvalid($name) 1]"
2558 }
2559 }
2560 {} {
2561 ##nagelfar ignore +2 Non static subcommand
2562 if {([llength $confvalid($name)] == 1 && ![string is\
2563 $confvalid($name) -strict $value]) || ([llength\
2564 $confvalid($name)] > 1 && $value ni $confvalid($name))} {
2565 reportErrorAndExit "Valid values for configuration option\
2566 '$name' are: $confvalid($name)"
2567 } else {
2568 set validval 1
2569 }
2570 }
2571 }
2572 } else {
2573 set validval 1
2574 }
2575
2576 if {[info exists validval]} {
2577 # effectively set configuration variable
2578 lappendState mode load
2579 setenv $confvar($name) $value
2580 lpopState mode
2581 }
2582 # clear cached value for config if any
2583 unsetConf $name
2584 # report configuration
2585 } else {
2586 reportVersion
2587 reportSeparateNextContent
2588 displayTableHeader hi {Config. name} 24 {Value (set by if default\
2589 overridden)} 54
2590
2591 # report all configs or just queried one
2592 if {[info exists name]} {
2593 set varlist [list $name]
2594 } else {
2595 set varlist [lsort [array names confval]]
2596 }
2597
2598 foreach var $varlist {
2599 ##nagelfar ignore +2 Suspicious variable name
2600 set valrep [displayConfig $confval($var) $confvar($var) [info exists\
2601 ::asked_$var] $confvtrans($var) [expr {$conflockable($var) eq {1}\
2602 && [isConfigLocked $var]}]]
2603 append displist [format {%-25s %s} $var $valrep] \n
2604 }
2605 report $displist 1
2606 reportSeparateNextContent
2607
2608 if {$dump_state} {
2609 cmdModuleState
2610 }
2611 }
2612 }
2613
2614 proc cmdModuleShToMod {args} {
2615 set scriptargs [lassign $args shell script]
2616
2617 # evaluate script and get the environment changes it performs translated
2618 # into modulefile commands
2619 set modcontent [sh-to-mod {} {*}$args]
2620
2621 # output resulting modulefile
2622 if {[llength $modcontent]} {
2623 report "#%Module"
2624 # format each command with tabs and colors if enabled
2625 foreach modcmd $modcontent {
2626 reportCmd -nativeargrep {*}$modcmd
2627 }
2628 }
2629 }
2630
2631 proc cmdModuleEdit {mod} {
2632 lassign [getPathToModule $mod] modfile modname
2633
2634 # error message has already been produced if mod not found or forbidden
2635 if {$modfile ne {}} {
2636 # redirect stdout to stderr as stdout is evaluated by module shell func
2637 if {[catch {runCommand [getConf editor] $modfile >@stderr 2>@stderr}\
2638 errMsg]} {
2639 # re-throw error but as an external one (not as a module issue)
2640 knerror $errMsg
2641 }
2642 }
2643 }
2644
2645 proc cmdModuleRefresh {} {
2646 lappendState mode refresh
2647 # create an eval id to track successful/failed module evaluations
2648 pushMsgRecordId refresh-[depthState modulename] 0
2649
2650 foreach lm [getEnvLoadedModulePropertyParsedList refresh] {
2651 # prepare info to execute modulefile
2652 set lmvr [getAndParseLoadedModuleWithVariant $lm]
2653 set lmfile [getModulefileFromLoadedModule $lm]
2654 set taglist [getExportTagList $lm]
2655
2656 # refreshing module is visible by default
2657 set hidden 0
2658 set uasked 1
2659
2660 # set a unique id to record messages related to this evaluation.
2661 set msgrecid refresh-$lmvr-[depthState modulename]
2662
2663 # register record message unique id (now we know mod will be evaluated)
2664 pushMsgRecordId $msgrecid
2665
2666 # record module title (with the variants and tags of loaded module)
2667 # prior module evaluation to get this title ready in case of eval error
2668 registerModuleDesignation $msgrecid $lm [getVariantList $lm 7]\
2669 $taglist
2670
2671 # run modulefile, restore settings prior evaluation if error and
2672 # continue to evaluate the remaining loaded modules
2673 pushSettings
2674 if {[set errCode [catch {
2675 if {[execute-modulefile $lmfile $lm lmvr $lm 0]} {
2676 break
2677 }
2678
2679 # unloading visibility depends on hidden-loaded tag
2680 set hidden [isModuleTagged $lm hidden-loaded 1]
2681
2682 # module was asked by user if tagged loaded instead of auto-loaded
2683 set uasked [isModuleTagged $lm loaded 1]
2684 } errMsg]] != 0 && $errCode != 4} {
2685 restoreSettings
2686 }
2687 popSettings
2688
2689 # report all recorded messages for this evaluation (hide evaluation if
2690 # loaded mod is set hidden, has been automatically loaded and unloaded)
2691 reportMsgRecord "Refreshing [getModuleDesignation $msgrecid {} 2]"\
2692 [expr {$hidden && !$uasked && [depthState evalid] != 1}]
2693 popMsgRecordId
2694 }
2695
2696 popMsgRecordId 0
2697 lpopState mode
2698 }
2699
2700 proc cmdModuleHelp {args} {
2701 lappendState mode help
2702 set first_report 1
2703 foreach arg $args {
2704 lassign [getPathToModule $arg] modfile modname modnamevr
2705
2706 if {$modfile ne {}} {
2707 # only one separator lines between 2 modules
2708 if {$first_report} {
2709 displaySeparatorLine
2710 set first_report 0
2711 }
2712 report "Module Specific Help for [sgr hi $modfile]:\n"
2713 execute-modulefile $modfile $modname modnamevr $arg 1
2714 displaySeparatorLine
2715 }
2716 }
2717 lpopState mode
2718 if {![llength $args]} {
2719 reportUsage
2720 }
2721 }
2722
2723 proc cmdModuleTag {unset_extra uasked tag_list args} {
2724 reportDebug "tagging $args (unset_extra=$unset_extra, uasked=$uasked,\
2725 tag_list=$tag_list)"
2726
2727 set ret 0
2728 foreach mod $args {
2729 # find mod among loaded modules
2730 lassign [getPathToModule $mod {} 1 match] modfile modname modnamevr\
2731 errkind
2732
2733 if {$modfile eq {}} {
2734 set ret 1
2735 # go to next module to unload
2736 continue
2737 }
2738
2739 # record tags not already set and if asked unset extra tags not set
2740 # anymore
2741 lassign [getDiffBetweenList $tag_list [getTagList $modname]] diff_list
2742 lassign [getDiffBetweenList [getExtraTagList $modname] $tag_list] \
2743 unset_list
2744 if {[llength $diff_list] || ($unset_extra && [llength $unset_list])} {
2745 # set a unique id to record messages related to this evaluation.
2746 set msgrecid tag-$modnamevr-[depthState modulename]
2747 pushMsgRecordId $msgrecid
2748 # record module title (with the variant but no tag list) prior
2749 # evaluation to get this title ready in case of error
2750 registerModuleDesignation $msgrecid $modname [getVariantList\
2751 $modnamevr 7] {}
2752
2753 lappendState mode unload
2754 # first unset tags declared for this module on LM env var
2755 unsetEnvLoadedModuleProperty $modname tag
2756 unsetEnvLoadedModuleProperty $modname extratag
2757 lpopState mode
2758
2759 # remove extra tags currently set not part of tag list if asked
2760 if {$unset_extra && [llength $unset_list]} {
2761 unsetModuleAndVariantsTag $modname $modnamevr {*}$unset_list
2762 unsetModuleAndVariantsExtraTag $modname $modnamevr {*}$unset_list
2763 }
2764
2765 # ensure auto-loaded tag is not preserved if not part of target tags
2766 if {$unset_extra && {auto-loaded} ni $tag_list} {
2767 unsetModuleAndVariantsTag $modname $modnamevr auto-loaded
2768 }
2769
2770 # record new tags as extra tag excluding tags relative to the way
2771 # module is loaded (auto, keep)
2772 lassign [getDiffBetweenList $diff_list [list auto-loaded\
2773 keep-loaded]] extradiff_list
2774 setModuleAndVariantsTag $modname $modnamevr {*}$diff_list
2775 if {[llength $extradiff_list]} {
2776 setModuleAndVariantsExtraTag $modname $modnamevr\
2777 {*}$extradiff_list
2778 }
2779
2780 # set the new tag set for module on LM env var
2781 lappendState mode load
2782 setEnvLoadedModuleProperty $modname tag [getExportTagList $modnamevr]
2783 setEnvLoadedModuleProperty $modname extratag [getExtraTagList\
2784 $modnamevr]
2785 lpopState mode
2786
2787 # update module designation now the additional tags are set
2788 registerModuleDesignation $msgrecid $modname [getVariantList\
2789 $modname 7] [getExportTagList $modname]
2790 # report tagging evaluation unless hidden and auto-loaded
2791 set hidden [isModuleTagged $modnamevr hidden-loaded 1]
2792 reportMsgRecord "Tagging [getModuleDesignation $msgrecid {} 2]"\
2793 [expr {$hidden && !$uasked}]
2794 popMsgRecordId
2795
2796 # indicates that new tags have been applied
2797 set ret 2
2798 }
2799 }
2800
2801 return $ret
2802 }
2803
2804 proc cmdModuleLint {args} {
2805 # stop if no linter defined
2806 if {![llength [getConf tcl_linter]]} {
2807 knerror {No Tcl linter program configured}
2808 }
2809
2810 # extract linter program name
2811 set linter [file rootname [file tail [lindex [getConf tcl_linter] 0]]]
2812 # build command line
2813 set linter_mfile [getConf tcl_linter]
2814 set linter_mrc [getConf tcl_linter]
2815 set linter_gmrc [getConf tcl_linter]
2816 set linter_mcache [getConf tcl_linter]
2817 # add module-specific syntax database in addition to regular Tcl one
2818 ##nagelfar ignore #11 Strange command
2819 @nagelfaraddons@if {$linter eq {nagelfar}} {
2820 @nagelfaraddons@ lappend linter_mfile -s _\
2821 @nagelfaraddons@ -s {@nagelfardatadir@/syntaxdb_modulefile.tcl}\
2822 @nagelfaraddons@ -plugin {@nagelfardatadir@/plugin_modulefile.tcl}
2823 @nagelfaraddons@ lappend linter_mrc -s _\
2824 @nagelfaraddons@ -s {@nagelfardatadir@/syntaxdb_modulerc.tcl}\
2825 @nagelfaraddons@ -plugin {@nagelfardatadir@/plugin_modulerc.tcl}
2826 @nagelfaraddons@ lappend linter_gmrc -s _\
2827 @nagelfaraddons@ -s {@nagelfardatadir@/syntaxdb_modulefile.tcl}\
2828 @nagelfaraddons@ -plugin {@nagelfardatadir@/plugin_globalrc.tcl}
2829 @nagelfaraddons@ lappend linter_mcache -s _\
2830 @nagelfaraddons@ -s {@nagelfardatadir@/syntaxdb_modulecache.tcl}\
2831 @nagelfaraddons@ -plugin {@nagelfardatadir@/plugin_modulecache.tcl}
2832 @nagelfaraddons@}
2833 set global_rclist [getGlobalRcFileList]
2834
2835 set modfilelist {}
2836 # fetch every available modulefiles if no argument provided
2837 if {![llength $args]} {
2838 # add global RC files
2839 foreach rc $global_rclist {
2840 set tolint($rc) gmrc
2841 }
2842
2843 inhibitErrorReport
2844 foreach dir [getModulePathList exiterronundef] {
2845 set cachefile [getModuleCacheFilename $dir]
2846 if {[file readable $cachefile]} {
2847 set tolint($cachefile) mcache
2848 }
2849
2850 # fetch all existing rc file current user has access to
2851 foreach {elt props} [findModules $dir * 0 0] {
2852 switch -- [lindex $props 0] {
2853 modulerc {
2854 set tolint($dir/$elt) mrc
2855 }
2856 }
2857 }
2858 # collect all modulefile from dir that current user has access to
2859 # getModules will reuse the result collected for findModules
2860 foreach {elt props} [getModules $dir *] {
2861 switch -- [lindex $props 0] {
2862 modulefile - virtual {
2863 set tolint([lindex $props 2]) mfile
2864 }
2865 }
2866 }
2867 }
2868 uninhibitErrorReport
2869 } else {
2870 foreach mod $args {
2871 lassign [getPathToModule $mod] modfile modname modnamevr
2872 # error mesg has already been produced if mod not found or forbidden
2873 if {$modfile ne {}} {
2874 if {$modfile in $global_rclist} {
2875 set mkind gmrc
2876 } else {
2877 switch -- [file tail $modfile] {
2878 .modulerc - .version {
2879 set mkind mrc
2880 }
2881 .modulecache {
2882 set mkind mcache
2883 }
2884 default {
2885 set mkind mfile
2886 }
2887 }
2888 }
2889 set tolint($modfile) $mkind
2890 }
2891 }
2892 }
2893
2894 # execute linter program over every gathered file
2895 foreach lintfile [lsort -dictionary [array names tolint]] {
2896 # set a record message unique id and record modulefile title
2897 set msgrecid lint-$lintfile
2898 pushMsgRecordId $msgrecid
2899 registerModuleDesignation $msgrecid $lintfile {} {}
2900
2901 ##nagelfar ignore Suspicious variable name
2902 if {[catch {set out [runCommand {*}[set linter_$tolint($lintfile)]\
2903 $lintfile]} errMsg]} {
2904 # re-throw error but as an external one (not as a module issue)
2905 knerror $errMsg
2906 }
2907
2908 # report linting messages
2909 displayLinterOutput $linter $out
2910
2911 # report all lint messages for this modulefile
2912 reportMsgRecord "Linting [getModuleDesignation $msgrecid {} 2]"
2913 popMsgRecordId
2914 }
2915 }
2916
2917 proc cmdModuleModToSh {shell args} {
2918 # save shell modulecmd is initialized to
2919 ##nagelfar ignore Found constant
2920 setState modtosh_real_shell [getState shell]
2921
2922 # set shell and shellType states to mod-to-sh target value
2923 if {$shell ni [getState supported_shells]} {
2924 reportErrorAndExit "Unsupported shell type '$shell'"
2925 }
2926 ##nagelfar ignore Found constant
2927 setState shell $shell
2928 unsetState shelltype
2929
2930 # silence message report (avoid mix with produced shell code) unless if
2931 # a debugging mode is set
2932 if {![isVerbosityLevel trace]} {
2933 unsetConf verbosity
2934 set ::asked_verbosity silent
2935 }
2936
2937 # modulefile evaluation is done against mod-to-sh target shell which means
2938 # module-info will return mod-to-sh shell value
2939 return [cmdModuleLoad load 1 0 0 {} {} {*}$args]
2940
2941 # after evaluation, renderSettings will produce shell code for mod-to-sh
2942 # target shell. modtosh_real_shell state helps to know that shell code has
2943 # to be output on report message channel
2944 }
2945
2946 proc cmdModuleReset {} {
2947 # use reset_target_state configuration option to know the environment state
2948 # to restore
2949 if {[getConf reset_target_state] eq {__purge__}} {
2950 cmdModulePurge
2951 } else {
2952 cmdModuleRestore [getConf reset_target_state]
2953 }
2954 }
2955
2956 proc cmdModuleStash {} {
2957 # check if there is something to stash
2958 if {[getConf reset_target_state] eq {__purge__}} {
2959 # current environment differs from initial 'purge' state when at least
2960 # a module is loaded and it is not super-sticky and not sticky or force
2961 # mode is enabled to allow sticky tag unload
2962 set diff_from_init 0
2963 foreach mod [getEnvLoadedModulePropertyParsedList name] {
2964 if {![isModuleSticky $mod]} {
2965 set diff_from_init 1
2966 break
2967 }
2968 }
2969 } else {
2970 # compare current environment against initial collection to check if
2971 # something differ
2972 set coll [getConf reset_target_state]
2973 # get corresponding collection or init, raise error if it does not exist
2974 lassign [findCollections $coll exact 0 1] collfile colldesc
2975
2976 # fetch collection content and differences compared current environment
2977 lassign [getDiffBetweenCurEnvAndColl $collfile $colldesc]\
2978 coll_path_list coll_mod_list coll_tag_arrser coll_nuasked_list\
2979 mod_to_unload mod_to_load path_to_unuse path_to_use is_tags_diff
2980 array set coll_tag_arr $coll_tag_arrser
2981
2982 set diff_from_init [expr {[llength $mod_to_unload] || [llength\
2983 $mod_to_load] || [llength $path_to_unuse] || [llength $path_to_use]\
2984 || $is_tags_diff}]
2985 }
2986
2987 if {!$diff_from_init} {
2988 reportWarning {No specific environment to save}
2989 return
2990 }
2991
2992 # record current environment
2993 cmdModuleSave stash-[clock milliseconds]
2994
2995 # restore initial environment
2996 cmdModuleReset
2997 }
2998
2999 proc cmdModuleStashpop {{stash 0}} {
3000 # determine stash collection name from argument
3001 set coll [getCollectionFromStash $stash]
3002
3003 # restore stash collection environment state
3004 cmdModuleRestore $coll
3005
3006 # delete stash collection file
3007 cmdModuleSaverm $coll
3008 }
3009
3010 proc cmdModuleStashrm {{stash 0}} {
3011 # determine stash collection name from argument
3012 set coll [getCollectionFromStash $stash]
3013
3014 # delete stash collection file
3015 cmdModuleSaverm $coll
3016 }
3017
3018 proc cmdModuleStashshow {{stash 0}} {
3019 # determine stash collection name from argument
3020 set coll [getCollectionFromStash $stash]
3021
3022 # display stash collection file
3023 cmdModuleSaveshow $coll
3024 }
3025
3026 proc cmdModuleStashclear {} {
3027 # get all stash collections (only from current target)
3028 set collfile_list [findCollections stash-* glob 0 0 1 1]
3029
3030 # delete all stash collections starting from most recent
3031 foreach collfile [lsort -decreasing $collfile_list] {
3032 # extract collection name (without path and target extension)
3033 set coll [file rootname [file tail $collfile]]
3034
3035 # delete stash collection file
3036 cmdModuleSaverm $coll
3037 }
3038 }
3039
3040 proc cmdModuleStashlist {show_oneperline show_mtime} {
3041 cmdModuleSavelist $show_oneperline $show_mtime {} stash-*
3042 }
3043
3044 proc cmdModuleCachebuild {args} {
3045 # use enabled modulepaths when no arg is provided
3046 if {[llength $args]} {
3047 set modpath_list $args
3048 } else {
3049 set modpath_list [getModulePathList exiterronundef]
3050 }
3051
3052 # record cache with module header check options enabled
3053 setConf mcookie_check always
3054 setConf mcookie_version_check 1
3055
3056 # ignore cache when building cache
3057 setConf ignore_cache 1
3058
3059 foreach modpath $modpath_list {
3060 set cachefile [getModuleCacheFilename $modpath]
3061 # set a record message unique id and record cachefile title
3062 set msgrecid cachebuild-$cachefile
3063 pushMsgRecordId $msgrecid
3064 registerModuleDesignation $msgrecid $cachefile {} {}
3065
3066 if {[file isdirectory $modpath]} {
3067 if {[file writable $modpath]} {
3068 if {[catch {
3069 # get cache content for modulepath
3070 set cache [formatModuleCacheContent $modpath]
3071 if {![string length $cache]} {
3072 reportWarning {Nothing to record in cache file}
3073 } else {
3074 # record cache content in file
3075 set fid [open $cachefile w]
3076 # use defined buffer size to limit num of write system call
3077 fconfigure $fid -buffersize [getConf cache_buffer_bytes]
3078 puts $fid $cache
3079 close $fid
3080 }
3081 } errMsg]} {
3082 # report error occurring during cache content format or cache
3083 # file write
3084 reportError $errMsg
3085 }
3086 } else {
3087 reportWarning {Cannot build cache file, directory is not writable}
3088 }
3089 } else {
3090 reportError "'$modpath' is not a directory"
3091 }
3092
3093 # report all messages for this cachefile creation
3094 reportMsgRecord "Creating [getModuleDesignation $msgrecid {} 2]"
3095 popMsgRecordId
3096 }
3097 }
3098
3099 proc cmdModuleCacheclear {} {
3100 foreach modpath [getModulePathList exiterronundef] {
3101 set cachefile [getModuleCacheFilename $modpath]
3102 if {[file exists $cachefile]} {
3103 # set a record message unique id and record cachefile title
3104 set msgrecid cacheclear-$cachefile
3105 pushMsgRecordId $msgrecid
3106 registerModuleDesignation $msgrecid $cachefile {} {}
3107
3108 if {[file writable $modpath]} {
3109 if {[catch {file delete $cachefile} errMsg]} {
3110 reportError $errMsg
3111 }
3112 } else {
3113 reportWarning {Cannot remove cache file, directory is not\
3114 writable}
3115 }
3116
3117 # report all messages for this cachefile deletion
3118 reportMsgRecord "Deleting [getModuleDesignation $msgrecid {} 2]"
3119 popMsgRecordId
3120 }
3121 }
3122 }
3123
3124 proc cmdModuleSpider {show_oneperline show_mtime show_filter search_filter\
3125 search_match args} {
3126
3127 # recursively collect all modulepath used among available modules
3128 inhibitErrorReport
3129 setConf advanced_version_spec 1
3130 defineParseModuleSpecificationProc 1
3131 set modpath_list [getModulePathList exiterronundef]
3132 set use_xt_query [parseModuleSpecification 0 1 1 0 use:*]
3133 for {set i -1} {$i < [llength $modpath_list]} {incr i} {
3134 if {$i < 0} {
3135 set modpath {}
3136 getModules $modpath $use_xt_query 0 {rc_alias_only}
3137 } else {
3138 set modpath [lindex $modpath_list $i]
3139 getModules $modpath $use_xt_query
3140 }
3141 foreach {new_modpath from_mod_list} [getScanModuleElt $modpath use] {
3142 if {[string length $new_modpath] && $new_modpath ni $modpath_list} {
3143 lappend modpath_list $new_modpath
3144 set via_mod [lindex $from_mod_list 0]
3145 setLoadedUse $via_mod $new_modpath
3146 setViaModuleModulepath $via_mod $modpath
3147 }
3148 }
3149 }
3150 unsetConf advanced_version_spec
3151 defineParseModuleSpecificationProc [getConf advanced_version_spec]
3152 uninhibitErrorReport
3153 reportTrace $modpath_list {Collect modulepaths}
3154
3155 # perform an avail on all collected modulepaths
3156 cmdModuleAvail $show_oneperline $show_mtime $show_filter $search_filter\
3157 $search_match $modpath_list {*}$args
3158 }
3159
3160 # ;;; Local Variables:
3161 # ;;; Mode: tcl-mode
3162 # ;;; tcl-indent-level: 3
3163 # ;;; tcl-continued-indent-level: 3
3164 # ;;; indent-tabs-mode: nil
3165 # ;;; End:
3166 # vim:set tabstop=3 shiftwidth=3 expandtab autoindent: