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