Debian Codegraph @

tcl/report.tcl.in

raw
1 ##########################################################################
2
3 # REPORT.TCL, output handling procedures
4 # Copyright (C) 2002-2004 Mark Lakata
5 # Copyright (C) 2004-2017 Kent Mein
6 # Copyright (C) 2016-2026 Xavier Delaruelle
7 #
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 2 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20
21 ##########################################################################
22
23 #
24 # Debug, Info, Warnings and Error message handling.
25 #
26
27 # save message when report is not currently initialized as we do not
28 # know yet if debug mode is enabled or not
29 proc reportDebug {message {caller _undef_}} {
30 set caller [getCallingProcName]
31 lappend ::errreport_buffer [list reportDebug $message $caller]
32 }
33
34 # regular procedure to use once error report is initialized
35 proc __reportDebug {message {caller _undef_}} {
36 # display active interp details if not the main one
37 set prefix [currentState debug_msg_prefix]
38 if {$caller eq {_undef_}} {
39 set caller [getCallingProcName]
40 }
41 # display caller name as prefix
42 if {$caller ne {}} {
43 append prefix "$caller: "
44 }
45 report [sgr db "DEBUG $prefix$message"] 0 1
46 }
47
48 # alternative procedure used when debug is disabled
49 proc __reportDebugNop {message {caller _undef_}} {}
50
51 proc reportWarning {message} {
52 reportError $message WARNING wa 0
53 }
54
55 proc reportError {message {severity ERROR} {sgrkey er} {incr_count 1}} {
56 lappend ::errreport_buffer [list reportError $message $severity $sgrkey\
57 $incr_count]
58 }
59
60 proc __reportError {message {severity ERROR} {sgrkey er} {incr_count 1}} {
61 # if report disabled, also disable error raise to get a coherent behavior
62 # (if no message printed, no error code change). also no report if no msg
63 if {![getState inhibit_errreport] && [string length $message]} {
64 if {$incr_count} {
65 incrErrorCount
66 }
67 set msgsgr "[sgr $sgrkey $severity]: $message"
68 # record message to report it later on if a record id is found
69 if {[currentState msgrecordid] ne {}} {
70 recordMessage $msgsgr
71 # skip message report if silent
72 } elseif {[isVerbosityLevel concise]} {
73 # save error messages to render them all together in JSON format
74 if {[isStateEqual report_format json]} {
75 lappend ::g_report_erralist $severity $message
76 } else {
77 report $msgsgr 0 0 1
78 }
79 }
80 }
81 }
82
83 # throw known error (call error with 'known error' code)
84 proc knerror {message {code MODULES_ERR_KNOWN}} {
85 error $message {} $code
86 }
87
88 proc knerrorOrWarningIfForced {message {code MODULES_ERR_KNOWN}} {
89 if {[getState force]} {
90 reportWarning $message
91 } else {
92 knerror $message $code
93 }
94 }
95
96 proc knerrorModule {topcall message} {
97 if {$topcall} {
98 append message "\nTry 'module --help' for more information."
99 } else {
100 set message "module: $message"
101 }
102 knerror $message
103 }
104
105 # save message if report is not yet initialized
106 proc reportErrorAndExit {message} {
107 lappend ::errreport_buffer [list reportErrorAndExit $message]
108 }
109
110 # regular procedure to use once error report is initialized
111 proc __reportErrorAndExit {message} {
112 incrErrorCount
113 renderFalse
114 error $message {} MODULES_ERR_RENDERED
115 }
116
117 proc reportErrorOrWarningIfForced {message} {
118 if {[getState force]} {
119 reportWarning $message
120 } else {
121 reportError $message
122 }
123 }
124
125 proc reportInternalBug {message {modfile {}} {title {Module ERROR}}} {
126 reportError [formatInternalBugMsg $message $modfile] $title me
127 }
128
129 proc reportInternalBugWarning {message {modfile {}} {title {Module\
130 WARNING}}} {
131 reportError [formatInternalBugMsg $message $modfile] $title wa 0
132 }
133
134 proc reportInternalBugOrWarningIfForced {message {modfile {}}} {
135 if {[getState force]} {
136 reportInternalBugWarning $message $modfile
137 } else {
138 reportInternalBug $message $modfile
139 }
140 }
141
142 proc formatInternalBugMsg {message modfile} {
143 if {$modfile ne {}} {
144 set message [formatMessageInModule $message $modfile]
145 }
146 return "$message\nPlease contact <[getConf contact]>"
147 }
148
149 proc formatMessageInModule {message modfile} {
150 return "$message\nIn '$modfile'"
151 }
152
153 proc reportInfo {message {title INFO}} {
154 if {[isVerbosityLevel normal]} {
155 # use reportError for convenience but there is no error here
156 reportError $message $title in 0
157 }
158 }
159
160 proc reportTrace {message {title TRACE}} {
161 if {[isVerbosityLevel trace]} {
162 # use reportError for convenience but there is no error here
163 reportError [sgr tr $message] $title tr 0
164 }
165 }
166
167 proc reportTimer {message timestr start_us stop_us} {
168 set elapsed_ms [expr {($stop_us - $start_us) / 1000.0}]
169 report [sgr db "TIMER $message [format $timestr $elapsed_ms]"] 0 1
170 }
171
172 # trace procedure execution start
173 proc reportTraceExecEnter {cmdstring op} {
174 reportDebug $cmdstring [getCallingProcName]
175 }
176
177 # time procedure execution duration
178 proc reportTimerExecEnter {cmdstring op} {
179 uplevel 1 set proc_timer_start [clock microseconds]
180 }
181
182 proc reportTimerExecLeave {cmdstring code result op} {
183 reportTimer $cmdstring {(%.3f ms)} [uplevel 1 set proc_timer_start]\
184 [clock microseconds]
185 }
186
187 # record messages on the eventual additional module evaluations that have
188 # occurred during the current evaluation
189 proc reportModuleEval {} {
190 set evalid [currentState evalid]
191 array set contexttitle {conun {Unloading conflict} reqlo {Loading\
192 requirement} depre {Reloading dependent} depun {Unloading dependent}\
193 urequn {Unloading useless requirement}}
194
195 if {[info exists ::g_moduleEval($evalid)]} {
196 foreach contextevallist $::g_moduleEval($evalid) {
197 set msgrecidlist [lassign $contextevallist context]
198 # skip context with no description title
199 if {[info exists contexttitle($context)]} {
200 # exclude hidden modules from report unless an high level of
201 # verbosity is set
202 if {[info exists ::g_moduleHiddenEval($evalid:$context)] &&\
203 ![isVerbosityLevel verbose2]} {
204 lassign [getDiffBetweenList $msgrecidlist\
205 $::g_moduleHiddenEval($evalid:$context)] msgrecidlist
206 }
207
208 if {[llength $msgrecidlist]} {
209 set moddesiglist {}
210 foreach msgrecid $msgrecidlist {
211 lappend moddesiglist [getModuleDesignation $msgrecid]
212 }
213 reportInfo [join $moddesiglist] $contexttitle($context)
214 }
215 }
216 }
217 # purge list in case same evaluation is re-done afterward
218 unset ::g_moduleEval($evalid)
219 }
220 }
221
222 # render messages related to current record id under an header block
223 proc reportMsgRecord {header {hidden 0}} {
224 set recid [currentState msgrecordid]
225 if {[info exists ::g_msgRecord($recid)]} {
226 # skip message report if silent (report even if hidden as soon as msgs
227 # are associated to hidden module evaluation)
228 if {[isVerbosityLevel concise]} {
229 set tty_cols [getState term_columns]
230 set padding { }
231
232 set dispmsg $header
233 foreach msg $::g_msgRecord($recid) {
234 # split lines if too large for terminal
235 set first 1
236 set max_idx [tcl::mathfunc::max [expr {$tty_cols - [string length\
237 $padding]}] 1]
238 set linelist [list]
239 foreach line [split $msg \n] {
240 set lineadd {}
241 while {$lineadd ne $line} {
242 set line_max_idx $max_idx
243 # sgr tags consume no length
244 set eidx 0
245 while {[set sidx [string first "\033\[" $line $eidx]] !=\
246 -1} {
247 set eidx [string first m $line $sidx]
248 incr line_max_idx [expr {1 + $eidx - $sidx}]
249 }
250
251 # no split if no whitespace found to slice
252 if {[string length $line] > $line_max_idx && [set cut_idx\
253 [string last { } $line $line_max_idx]] != -1} {
254 set lineadd [string range $line 0 $cut_idx-1]
255 set line [string range $line $cut_idx+1 end]
256 } else {
257 set lineadd $line
258 }
259 # skip empty line
260 if {[string trim $lineadd] ne {}} {
261 lappend linelist $lineadd
262 }
263 if {$first} {
264 set first 0
265 incr max_idx -[string length $padding]
266 if {$max_idx < 1} {set max_idx 1}
267 }
268 }
269 }
270
271 # display each line
272 set first 1
273 foreach line $linelist {
274 append dispmsg \n
275 if {$first} {
276 set first 0
277 } else {
278 append dispmsg $padding
279 }
280 append dispmsg $padding$line
281 }
282 }
283 reportSeparateNextContent
284 report $dispmsg
285 reportSeparateNextContent
286 }
287
288 # purge message list in case same evaluation is re-done afterward
289 unset ::g_msgRecord($recid)
290 # report header if no other specific msg to output in verbose mode or in
291 # normal verbosity mode if currently processing a cmd which triggers
292 # multiple module evaluations that cannot be guessed by the user (excluding
293 # dependency evaluations which are reported by triggering top evaluation)
294 # if hidden flag is enabled report only if verbosity >= verbose2
295 } elseif {(!$hidden && ([isVerbosityLevel verbose] || ([isVerbosityLevel\
296 normal] && ([ongoingCommandName restore] || [ongoingCommandName source]\
297 || [ongoingCommandName reset] || [ongoingCommandName stash] ||\
298 [ongoingCommandName stashpop] || [ongoingCommandName cacheclear] ||\
299 [ongoingCommandName cachebuild]) && $recid eq [topState msgrecordid])))\
300 || ($hidden && [isVerbosityLevel verbose2])} {
301 report $header
302 }
303 }
304
305 # separate next content produced if any
306 proc reportSeparateNextContent {} {
307 lappend ::errreport_buffer [list reportSeparateNextContent]
308 }
309
310 # regular procedure to use once error report is initialized
311 proc __reportSeparateNextContent {} {
312 # hold or apply
313 if {[depthState reportholdid] > 0} {
314 lappend ::g_holdReport([currentState reportholdid]) [list\
315 reportSeparateNextContent]
316 } else {
317 setState report_sep_next 1
318 }
319 }
320
321 # save message for block rendering
322 proc recordMessage {message} {
323 set recid [currentState msgrecordid]
324
325 if {$recid eq [currentState reportholdrecid]} {
326 lappend ::g_holdReport([currentState reportholdid]) [list\
327 recordMessage $message]
328 } else {
329 lappend ::g_msgRecord($recid) $message
330 }
331 }
332
333 # check if some msg have been recorded for current evaluation
334 proc isMsgRecorded {} {
335 return [info exists ::g_msgRecord([currentState msgrecordid])]
336 }
337
338 # filter and format error stack trace to only report useful content
339 proc formatErrStackTrace {errmsg loc {cmdlist {}}} {
340 set headstr "\n while executing\n"
341 set splitstr "\n invoked from within\n"
342 set splitstrlen [string length $splitstr]
343 set aftheadidx [string first $headstr $errmsg]
344 if {$aftheadidx != -1} {
345 incr aftheadidx [string length $headstr]
346 }
347
348 # get name of invalid command name to maintain it in error stack trace
349 if {[string equal -length 22 {invalid command name "} $errmsg]} {
350 set unkcmd [lindex [split [string range $errmsg 0 $aftheadidx] {"}] 1]
351 } else {
352 set unkcmd {}
353 }
354
355 # get list of modulecmd.tcl internal procedure to filter out from stack
356 # also add the way subcmds are launched through module proc ($cmdprocname)
357 # skip this when no interp command list is provided
358 if {[llength $cmdlist]} {
359 lassign [getDiffBetweenList [list {*}[info commands] {*}[info procs]\
360 {$cmdprocname}] $cmdlist] filtercmdlist keepcmdlist
361 } else {
362 set filtercmdlist {}
363 }
364
365 # define commands to filter out from bottom of stack
366 set filtercmdendlist [list {eval [getModuleContent\
367 $::ModulesCurrentModulefile]} "source $loc" {uplevel 1 source\
368 $siteconfig} {eval $cachecontent}]
369 # define commands to filter out from middle of stack
370 set filtercmdmidlist [list {interp eval $itrp $::source_cache($filename)}]
371
372 # filter out modulecmd internal references at beginning of stack
373 set internals 1
374 while {$internals && $aftheadidx != -1} {
375 # fetch erroneous command and its caller
376 set stackelt [string range $errmsg $aftheadidx [string first\
377 $splitstr $errmsg $aftheadidx]]
378 lassign [split [lindex [split $stackelt {"}] 1]] cmd1 cmd2
379 set cmdcaller [lindex [split [string range $stackelt [string last\
380 {(procedure } $stackelt] end] {"}] 1]
381 if {$cmd1 eq {eval}} {
382 set cmd1 $cmd2
383 # remove some calling prefix
384 } elseif {[string range $cmd1 0 3] eq {{*}[}} {
385 set cmd1 [string range $cmd1 4 end]
386 }
387
388 # filter out stack element referring to or called by an unknown
389 # procedure (ie. a modulecmd.tcl internal procedure)
390 if {$cmd1 ne $unkcmd && ($cmdcaller in $filtercmdlist || $cmd1 in\
391 $filtercmdlist)} {
392 set errmsg [string replace $errmsg $aftheadidx [expr {[string first\
393 $splitstr $errmsg] + $splitstrlen - 1}]]
394 } else {
395 set internals 0
396 }
397 }
398
399 # filter out modulecmd internal references at end of stack
400 set internals 1
401 while {$internals} {
402 set beffootidx [string last $splitstr $errmsg]
403 set stackelt [string range $errmsg $beffootidx end]
404 set cmd [lindex [split $stackelt {"}] 1]
405
406 if {$cmd in $filtercmdendlist} {
407 set errmsg [string replace $errmsg $beffootidx end]
408 } else {
409 set internals 0
410 }
411 }
412
413 # filter out modulecmd internal references in middle of stack
414 foreach filtercmdmid $filtercmdmidlist {
415 set filterstartidx [string first \"$filtercmdmid\" $errmsg]
416 if {$filterstartidx != -1} {
417 set filterendidx [expr {[string first $splitstr $errmsg\
418 $filterstartidx] + [string length $splitstr] - 1}]
419 set errmsg [string replace $errmsg $filterstartidx $filterendidx]
420 }
421 }
422
423 # replace error location at end of stack
424 set lastnl [string last \n $errmsg]
425 set lastline [string range $errmsg $lastnl+1 end]
426 if {[string match { ("eval" body line*} $lastline]} {
427 set errmsg [string replace $errmsg $lastnl $lastnl+[string length\
428 " (\"eval\" body line"] "\n (file \"$loc\" line"]
429 } elseif {![string match { (file *} $lastline]} {
430 # add error location at end of stack
431 append errmsg "\n (file \"$loc\")"
432 }
433
434 return $errmsg
435 }
436
437 # Test if color is enabled and passed sgrkey is defined and not null
438 proc isSgrkeyColored {sgrkey} {
439 return [expr {[getConf color] && [info exists ::g_colors($sgrkey)] &&\
440 $::g_colors($sgrkey) ne {}}]
441 }
442
443 # Select Graphic Rendition of a string with passed sgr keys (if color enabled)
444 proc sgr {keylist str {himatchmap {}} {othkeylist {}}} {
445 if {[getConf color]} {
446 set sgrreset 22
447 foreach sgrkey $keylist {
448 if {[info exists ::g_colors($sgrkey)]} {
449 # track color key that have been used
450 if {![info exists ::g_used_colors($sgrkey)]} {
451 set ::g_used_colors($sgrkey) 1
452 }
453 if {[info exists sgrset]} {
454 append sgrset {;}
455 }
456 append sgrset $::g_colors($sgrkey)
457 # if render bold or faint just reset that attribute, not all
458 if {$sgrreset != 0 && $sgrset != 1 && $sgrset != 2} {
459 set sgrreset 0
460 }
461 }
462 }
463 if {![llength $othkeylist]} {
464 # highlight matching substring
465 if {[llength $himatchmap]} {
466 set str [string map $himatchmap $str]
467 }
468 if {[info exists sgrset]} {
469 set str "\033\[${sgrset}m$str\033\[${sgrreset}m"
470 }
471 } else {
472 if {![info exists sgrset]} {
473 set sgrset {}
474 } else {
475 append sgrset {;}
476 }
477 # determine each chunk where the other sgr keys apply
478 set tagsgrlen [expr {int(ceil([string length $str]/[llength\
479 $othkeylist]))}]
480 for {set i 0} {$i < [llength $othkeylist]} {incr i} {
481 set idx [expr {$i*$tagsgrlen}]
482 set sgrkey [lindex $othkeylist $i]
483 lappend sgridxlist $idx $::g_colors($sgrkey)
484 # track color key that have been used
485 if {![info exists ::g_used_colors($sgrkey)]} {
486 set ::g_used_colors($sgrkey) 1
487 }
488 }
489 # determine each chunk where the highlight applies
490 set hiidxlist {}
491 foreach {mstr sgrmstr} $himatchmap {
492 set idx 0
493 while {$idx != -1} {
494 if {[set idx [string first $mstr $str $idx]] != -1} {
495 lappend hiidxlist $idx
496 incr idx [string length $mstr]
497 # add highlight end index unless if end of string
498 if {$idx < [string length $str]} {
499 lappend hiidxlist $idx
500 }
501 }
502 }
503 # no need to look at next match string if this one was found
504 if {[llength $hiidxlist]} {
505 break
506 }
507 }
508
509 # mix other sgr chunks with highlighted chunks to define sgr codes
510 set i 0
511 set j 0
512 set sgridx [lindex $sgridxlist 0]
513 set hiidx [lindex $hiidxlist 0]
514 set hicur 0
515 set sgrcur {}
516 set sgrrst {0;}
517 while {$i < [llength $sgridxlist] || $j < [llength $hiidxlist]} {
518 set sgrcode {}
519 set cursgridx $sgridx
520 # sgr chunk change
521 if {$sgridx ne {} && ($hiidx eq {} || $sgridx <= $hiidx)} {
522 incr i
523 set sgrcur $sgrset[lindex $sgridxlist $i]
524 set idx $sgridx
525 if {$idx != 0} {
526 append sgrcode $sgrrst
527 }
528 append sgrcode $sgrcur
529 incr i
530 set sgridx [lindex $sgridxlist $i]
531 }
532 # highlight change
533 if {$hiidx ne {} && ($cursgridx eq {} || $hiidx <= $cursgridx)} {
534 set idx $hiidx
535 set hicur [expr {!$hicur}]
536 if {$hicur} {
537 if {$sgrcode ne {}} {
538 append sgrcode {;}
539 }
540 append sgrcode $::g_colors(hi)
541 # restore current sgr set to only clear highlight
542 } elseif {$sgrcode eq {}} {
543 append sgrcode $sgrrst $sgrcur
544 }
545 incr j
546 set hiidx [lindex $hiidxlist $j]
547 } elseif {$hicur} {
548 append sgrcode {;} $::g_colors(hi)
549 }
550 lappend fullsgridxlist $idx $sgrcode
551 }
552 # reset sgr at end of string
553 lappend fullsgridxlist [string length $str] 0
554
555 # apply defined sgr codes to the string
556 set stridx 0
557 foreach {sgridx sgrcode} $fullsgridxlist {
558 if {$sgridx != 0} {
559 append sgrstr [string range $str $stridx $sgridx-1]
560 }
561 append sgrstr "\033\[${sgrcode}m"
562 set stridx $sgridx
563 }
564 set str $sgrstr
565 }
566 }
567 return $str
568 }
569
570 # Sort tags to return those matching defined sgr keys in a list up to a given
571 # maxnb number and if tag not set to be displayed by its name. Other elements
572 # are returned in a separate list
573 proc getTagSgrForModname {keylist maxnb} {
574 set sgrkeylist {}
575 if {[getConf color]} {
576 set otherlist {}
577 foreach key $keylist {
578 if {[info exists ::g_colors($key)] && ![info exists\
579 ::g_tagColorName($key)] && [llength $sgrkeylist] < $maxnb} {
580 lappend sgrkeylist $key
581 } else {
582 lappend otherlist $key
583 }
584 }
585 } else {
586 set otherlist $keylist
587 }
588 return [list $sgrkeylist $otherlist]
589 }
590
591 # save message if report is not yet initialized
592 proc report {message {nonewline 0} {immed 0} {padnl 0}} {
593 lappend ::errreport_buffer [list report $message $nonewline $immed $padnl]
594 }
595
596 # regular procedure to use once error report is initialized
597 proc __report {message {nonewline 0} {immed 0} {padnl 0}} {
598 # hold or print output
599 if {!$immed && [depthState reportholdid] > 0} {
600 lappend ::g_holdReport([currentState reportholdid]) [list report\
601 $message $nonewline $immed $padnl]
602 } else {
603 # produce blank line prior message if asked to
604 if {[isStateDefined reportfd] && [isStateDefined report_sep_next]} {
605 unsetState report_sep_next
606 report [expr {[isStateEqual report_format json] ? {,} : {}}]
607 }
608 # prefix msg lines after first one with 2 spaces
609 if {$padnl} {
610 set first 1
611 foreach line [split $message \n] {
612 if {$first} {
613 set first 0
614 } else {
615 append padmsg "\n "
616 }
617 append padmsg $line
618 }
619 set message $padmsg
620 }
621
622 # protect from issue with fd, just ignore it
623 catch {
624 if {$nonewline} {
625 puts -nonewline [getState reportfd] $message
626 } else {
627 puts [getState reportfd] $message
628 }
629 }
630 }
631 }
632
633 # report error the correct way depending of its type
634 proc reportIssue {issuetype issuemsg {issuefile {}}} {
635 switch -- $issuetype {
636 invalid {
637 reportInternalBug $issuemsg $issuefile
638 }
639 default {
640 reportError $issuemsg
641 }
642 }
643 }
644
645 # report defined command (used in display evaluation mode)
646 proc reportCmd {cmd args} {
647 # use Tcl native string representation of list
648 if {$cmd eq {-nativeargrep}} {
649 set cmdargs [lassign $args cmd]
650 } else {
651 set cmdargs [listTo tcl $args 0]
652 }
653 set extratab [expr {[string length $cmd] < 8 ? "\t" : {}}]
654 report [sgr cm $cmd]$extratab\t$cmdargs
655
656 # empty string returns if command result is another command input
657 return {}
658 }
659
660 # report defined command (called as an execution trace)
661 proc reportCmdTrace {cmdstring args} {
662 reportCmd {*}$cmdstring
663 }
664
665 proc reportVersion {} {
666 ##nagelfar ignore Too long line
667 report {Modules Release @MODULES_RELEASE@@MODULES_BUILD@\
668 (@MODULES_BUILD_DATE@)}
669 }
670
671 proc reportName {} {
672 report Modules
673 }
674
675 # disable error reporting (non-critical report only) unless debug enabled.
676 # keep track of inhibition depth to cope with nested calls
677 proc inhibitErrorReport {} {
678 if {![isVerbosityLevel trace]} {
679 setState inhibit_errreport [expr {[getState inhibit_errreport] + 1}]
680 }
681 }
682
683 # withdraw an error report inhibition demand (depth stays null if demand
684 # was made under trace verbosity where inhibition is disabled)
685 proc uninhibitErrorReport {} {
686 set inhibit_depth [getState inhibit_errreport]
687 if {$inhibit_depth > 0} {
688 setState inhibit_errreport [expr {$inhibit_depth - 1}]
689 }
690 }
691
692 proc initProcReportTrace {type prc} {
693 ##nagelfar ignore #7 Non static subcommand
694 if {[isVerbosityLevel debug] && [getState timer]} {
695 # time execution of procedure instead of regular debug report
696 trace $type execution $prc enter reportTimerExecEnter
697 trace $type execution $prc leave reportTimerExecLeave
698 } elseif {[isVerbosityLevel debug2]} {
699 # trace each procedure call
700 trace $type execution $prc enter reportTraceExecEnter
701 }
702 }
703
704 # init error report and output buffered messages
705 proc initErrorReport {} {
706 # ensure init is done only once
707 if {![isStateDefined init_error_report]} {
708 setState init_error_report 1
709
710 # ask for color init now as debug mode has already fire lines to render
711 # and we want them to be reported first (not the color init lines)
712 if {[isVerbosityLevel debug]} {
713 getConf color
714 }
715
716 # trigger pager start if something needs to be printed, to guaranty
717 # reportDebug calls during pager start are processed in buffer mode
718 if {[isVerbosityLevel debug]} {
719 getState reportfd
720 }
721
722 # only report timing information in debug mode if timer mode is enabled
723 if {[isVerbosityLevel debug] && ![getState timer]} {
724 # replace report procedures used to buffer messages until error
725 # report being initialized by regular report procedures
726 # delete initial reportDebug proc after getState which needs it
727 rename ::reportDebug {}
728 rename ::__reportDebug ::reportDebug
729 } else {
730 rename ::reportDebug {}
731 # set a disabled version if debug is disabled
732 rename ::__reportDebugNop ::reportDebug
733 }
734 rename ::reportError {}
735 rename ::__reportError ::reportError
736 rename ::reportErrorAndExit {}
737 rename ::__reportErrorAndExit ::reportErrorAndExit
738 rename ::reportSeparateNextContent {}
739 rename ::__reportSeparateNextContent ::reportSeparateNextContent
740 rename ::report {}
741 rename ::__report ::report
742
743 # setup traces for either debug or timer reports
744 if {[isVerbosityLevel debug] && [getState timer] || [isVerbosityLevel\
745 debug2]} {
746 # list of core procedures to exclude from tracing
747 set excl_prc_list [list report reportDebug reportFlush reportTimer\
748 reportTraceExecEnter reportTimerExecEnter reportTimerExecLeave\
749 initProcReportTrace isVerbosityLevel reportSeparateNextContent\
750 getState setState unsetState lappendState lpopState currentState\
751 depthState isStateDefined isStateEqual sgr getConf setConf\
752 unsetConf lappendConf getCallingProcName isEnvVarDefined\
753 envVarEquals log getConfList]
754
755 foreach prc [info procs] {
756 if {$prc ni $excl_prc_list} {
757 initProcReportTrace add $prc
758 }
759 }
760 }
761
762 # now error report is init output every message saved in buffer; first
763 # message will trigger message paging configuration and startup unless
764 # already done if debug mode enabled
765 foreach errreport $::errreport_buffer {
766 {*}$errreport
767 }
768 }
769 }
770
771 # drop or report held messages
772 proc releaseHeldReport {args} {
773 foreach {holdid action} $args {
774 if {[info exists ::g_holdReport($holdid)]} {
775 if {$action eq {report}} {
776 foreach repcall $::g_holdReport($holdid) {
777 {*}$repcall
778 }
779 }
780 unset ::g_holdReport($holdid)
781 }
782 # also drop reported tag of conflict error
783 if {[info exists ::g_holdReportConflict($holdid)]} {
784 if {$action eq {drop}} {
785 foreach {evalid drop_mod_list} $::g_holdReportConflict($holdid) {
786 lassign [getDiffBetweenList $::report_conflict($evalid)\
787 $drop_mod_list] ::report_conflict($evalid)
788 }
789 }
790 unset ::g_holdReportConflict($holdid)
791 }
792 # also drop failed module evaluation to get their failure information
793 # if later retried
794 if {[info exists ::g_holdModuleFailedEval($holdid)]} {
795 if {$action eq {drop}} {
796 foreach {evalid failed_context failed_mod}\
797 $::g_holdModuleFailedEval($holdid) {
798 set failed_eval_list $::g_moduleFailedEval($evalid)
799 for {set i 0} {$i < [llength $failed_eval_list]} {incr i} {
800 if {[lindex $failed_eval_list $i] eq $failed_context &&\
801 [lindex $failed_eval_list $i+1] eq $failed_mod} {
802 set failed_eval_list [lreplace $failed_eval_list $i $i+1]
803 break
804 }
805 }
806 set ::g_moduleFailedEval($evalid) $failed_eval_list
807 }
808 }
809 unset ::g_holdModuleFailedEval($holdid)
810 }
811 }
812 }
813
814 # final message output and reportfd flush and close
815 proc reportFlush {} {
816 # report execution time if asked
817 if {[getState timer]} {
818 reportSeparateNextContent
819 reportTimer {Total execution took} {%.3f ms} $::timer_start [clock\
820 microseconds]
821 }
822
823 # finish output document if json format enabled
824 if {[isStateEqual report_format json]} {
825 # render error messages all together
826 if {[info exists ::g_report_erralist]} {
827 # ignite report first to get eventual error message from report
828 # initialization in order 'foreach' got all messages prior firing
829 report "\"errors\": \[" 1
830 foreach {sev msg} $::g_report_erralist {
831 # split message in lines
832 lappend dispmsglist "\n{ \"severity\": \"$sev\", \"message\": \[\
833 \"[join [split [charEscaped $msg \"] \n] {", "}]\" \] }"
834 }
835 report "[join $dispmsglist ,] \]"
836 }
837 # inhibit next content separator if output is ending
838 unsetState report_sep_next
839 report \}
840 }
841
842 # close pager if enabled
843 if {[isStateDefined reportfd] && ![isStateEqual reportfd stderr]} {
844 catch {flush [getState reportfd]}
845 catch {close [getState reportfd]}
846 }
847 }
848
849 proc logEvent {event args} {
850 if {$event in [getConfList logged_events]} {
851 set log_info_list [list user [getState username] {*}$args]
852 set log_formatted_list {}
853 foreach {key val} $log_info_list {
854 lappend log_formatted_list "$key=\"$val\""
855 }
856 set log_message [join $log_formatted_list]
857 log $log_message
858 }
859 }
860
861 proc log {log_message} {
862 lappend ::g_log_msg_list $log_message
863 }
864
865 # send messages to log
866 proc logFlush {} {
867 # logger pipe is started only if enabled and some msgs need to be logged
868 set logfd [getState logfd]
869
870 # logging only occurs from this procedure with is run during termination
871 if {[string length $logfd]} {
872 if {[catch {
873 foreach log_msg $::g_log_msg_list {
874 puts $logfd $log_msg
875 }
876 flush $logfd
877 close $logfd
878 } errMsg]} {
879 reportWarning {Issue occurred when logging information}
880 }
881 }
882 }
883
884 # check if element passed as argument (corresponding to a kind of information)
885 # should be part of output content
886 proc isEltInReport {elt {retifnotdef 1}} {
887 # get config name relative to current sub-command and output format
888 set conf [currentState commandname]
889 if {[getState report_format] ne {regular}} {
890 append conf _[getState report_format]
891 }
892 append conf _output
893 set arrname ::g_$conf
894 ##nagelfar vartype arrname varName
895
896 if {[info exists ::g_config_defs($conf)]} {
897 # build value cache if it does not exist yet
898 if {![array exists $arrname]} {
899 array set $arrname {}
900 foreach confelt [getConfList $conf] {
901 ##nagelfar ignore Suspicious variable name
902 set ${arrname}($confelt) 1
903 }
904 }
905
906 # check if elt is marked to be included in output
907 ##nagelfar ignore Suspicious variable name
908 return [info exists ${arrname}($elt)]
909 } else {
910 # return $retifnotdef (ok by default) in case no config option
911 # corresponds to the current module sub-command and output format
912 return $retifnotdef
913 }
914 }
915
916 proc registerModuleDesignation {evalid mod vrlist taglist} {
917 set ::g_moduleDesgination($evalid) [list $mod $vrlist $taglist]
918 }
919
920 proc getModuleFromEvalId {evalid} {
921 if {[info exists ::g_moduleDesgination($evalid)]} {
922 return [lindex $::g_moduleDesgination($evalid) 0]
923 }
924 }
925
926 proc getModuleDesignation {from {mod {}} {sgr 1}} {
927 # fetch module name version and variants from specified context
928 switch -- $from {
929 spec {
930 set moddesig [getModuleNameAndVersFromVersSpec $mod]
931 set vrlist [getVariantList $mod 7 0 1]
932 set taglist {}
933 }
934 loaded {
935 set moddesig $mod
936 set vrlist [getVariantList $mod 7]
937 set taglist {}
938 }
939 default {
940 # fetch information from passed evaluation id
941 if {[info exists ::g_moduleDesgination($from)]} {
942 lassign $::g_moduleDesgination($from) moddesig vrlist taglist
943 # if not found, use passed spec to compute designation
944 } else {
945 set moddesig [getModuleNameAndVersFromVersSpec $mod]
946 set vrlist [getVariantList $mod 7 0 1]
947 set taglist [getExportTagList $mod]
948 }
949 }
950 }
951
952 # build module designation
953 switch -- $sgr {
954 2 {
955 set vrsgr va
956 set himatchmap [prepareMapToHightlightSubstr $moddesig]
957
958 set showtags 1
959 # prepare list of tag abbreviations that can be substituted and list
960 # of tags whose name should be colored
961 getConf tag_abbrev
962 getConf tag_color_name
963 # abbreviate tags
964 set taglist [abbrevTagList $taglist]
965 }
966 1 {
967 set vrsgr {se va}
968 set himatchmap {}
969 set showtags 0
970 }
971 0 {
972 set vrsgr {}
973 set himatchmap {}
974 set showtags 0
975 }
976 }
977 lassign [formatListEltToDisplay $moddesig {} {} {} {} 0 0 $taglist\
978 $showtags $vrlist $vrsgr 1 $himatchmap] disp dispsgr displen
979
980 return $dispsgr
981 }
982
983 #
984 # Helper procedures to format various messages
985 #
986
987 proc getHintUnFirstMsg {modlist} {
988 return "HINT: Might try \"module unload [join $modlist]\" first."
989 }
990
991 proc getHintLoFirstMsg {modlist} {
992 if {[llength $modlist] > 1} {
993 set oneof {at least one of }
994 set mod modules
995 } else {
996 set oneof {}
997 set mod module
998 }
999 return "HINT: ${oneof}the following $mod must be loaded first: [join\
1000 $modlist]"
1001 }
1002
1003 proc getErrConflictMsg {conlist} {
1004 return "Module cannot be loaded due to a conflict.\n[getHintUnFirstMsg\
1005 $conlist]"
1006 }
1007
1008 proc getErrPrereqMsg {prelist {load 1} {is_path_specific 0}} {
1009 if {$load} {
1010 foreach pre $prelist {
1011 lappend predesiglist [getModuleDesignation spec $pre]
1012 }
1013 lassign [list {} missing [getHintLoFirstMsg $predesiglist]] un miss\
1014 hintmsg
1015 } else {
1016 ##nagelfar ignore Found constant
1017 lassign [list un a [getHintUnFirstMsg $prelist]] un miss hintmsg
1018 }
1019 set path_specific_msg [expr {$is_path_specific ? [getSpecificPathMsg] :\
1020 {}}]
1021 return "Module cannot be ${un}loaded due to $miss\
1022 prereq$path_specific_msg.\n$hintmsg"
1023 }
1024
1025 proc getErrReqLoMsg {prelist {is_path_specific 0}} {
1026 foreach pre $prelist {
1027 lappend predesiglist [getModuleDesignation spec $pre]
1028 }
1029 set path_specific_msg [expr {$is_path_specific ? [getSpecificPathMsg] :\
1030 {}}]
1031 return "Load of requirement [join $predesiglist { or }]$path_specific_msg\
1032 failed"
1033 }
1034
1035 proc getReqNotLoadedMsg {prelist {is_path_specific 0}} {
1036 foreach pre $prelist {
1037 lappend predesiglist [getModuleDesignation spec $pre]
1038 }
1039 set path_specific_msg [expr {$is_path_specific ? [getSpecificPathMsg] :\
1040 {}}]
1041 return "Requirement [join $predesiglist { or }]$path_specific_msg is not\
1042 loaded"
1043 }
1044
1045 proc getSpecificPathMsg {} {
1046 return { (specific path)}
1047 }
1048
1049 proc getKindModuleBeStateMsg {kind mod_list state} {
1050 set is [expr {[llength $mod_list] > 1 ? {are} : {is}}]
1051 foreach mod $mod_list {
1052 lappend mod_desig_list [getModuleDesignation loaded $mod]
1053 }
1054 return "$kind [join $mod_desig_list { and }] $is $state"
1055 }
1056
1057 proc getDepLoadedMsg {pre_mod_list} {
1058 return [getKindModuleBeStateMsg Dependent $pre_mod_list loaded]
1059 }
1060
1061 proc getDepLoadingMsg {pre_mod_list} {
1062 return [getKindModuleBeStateMsg Dependent $pre_mod_list loading]
1063 }
1064
1065 proc getErrConUnMsg {conlist} {
1066 set condesiglist {}
1067 foreach con $conlist {
1068 lappend condesiglist [getModuleDesignation spec $con]
1069 }
1070 return "Unload of conflicting [join $condesiglist { and }] failed"
1071 }
1072
1073 proc getConLoadedMsg {con_mod_list} {
1074 return [getKindModuleBeStateMsg Conflicting $con_mod_list loaded]
1075 }
1076
1077 proc getConLoadingMsg {con_mod_list} {
1078 return [getKindModuleBeStateMsg Conflicting $con_mod_list loading]
1079 }
1080
1081 proc getPresentConflictErrorMsg {curmodnamevr con_mod_list is_loading} {
1082 if {[isModuleEvaluated any $curmodnamevr {} {*}$con_mod_list] || [getState\
1083 force]} {
1084 return [expr {$is_loading ? [getConLoadingMsg $con_mod_list] :\
1085 [getConLoadedMsg $con_mod_list]}]
1086 } else {
1087 return [getErrConflictMsg $con_mod_list]
1088 }
1089 }
1090
1091 proc getForbiddenMsg {mod fpmod} {
1092 set msg "Access to module [getModuleDesignation spec $mod 2] is denied"
1093 set extramsg [getModuleTagProp $mod $fpmod forbidden message]
1094 if {$extramsg ne {}} {
1095 append msg \n$extramsg
1096 }
1097 return $msg
1098 }
1099
1100 proc getNearlyForbiddenMsg {mod fpmod} {
1101 set after [getModuleTagProp $mod $fpmod nearly-forbidden after]
1102 set msg "Access to module will be denied starting '$after'"
1103 set extramsg [getModuleTagProp $mod $fpmod nearly-forbidden message]
1104 if {$extramsg ne {}} {
1105 append msg \n$extramsg
1106 }
1107 return $msg
1108 }
1109
1110 proc getWarningMsg {mod fpmod} {
1111 return [getModuleTagProp $mod $fpmod warning message]
1112 }
1113
1114 proc getStickyUnloadMsg {{tag sticky}} {
1115 return "Unload of $tag module skipped"
1116 }
1117
1118 proc getStickyReqUnloadMsg {{tag sticky}} {
1119 return "Unload of $tag module requirement skipped"
1120 }
1121
1122 proc getStickyForcedUnloadMsg {} {
1123 return {Unload of sticky module forced}
1124 }
1125
1126 proc getModWithAltVrIsLoadedMsg {mod is_loading} {
1127 set vrdesiglist {}
1128 foreach vr [getVariantList $mod 1] {
1129 lappend vrdesiglist [sgr va $vr]
1130 }
1131 set state [expr {$is_loading ? {loading} : {loaded}}]
1132 return "Variant [sgr se "\{"][join $vrdesiglist [sgr se :]][sgr se "\}"]\
1133 is already $state"
1134 }
1135
1136 proc getModFromDiffPathIsLoadedMsg {} {
1137 return {Module already loaded from a different modulepath}
1138 }
1139
1140 proc getEmptyNameMsg {type} {
1141 return "Invalid empty $type name"
1142 }
1143
1144 #
1145 # Stack of message recording/eval unique identifiers
1146 #
1147
1148 proc pushMsgRecordId {recid {setmsgid 1}} {
1149 lappendState evalid $recid
1150 if {$setmsgid} {
1151 lappendState msgrecordid $recid
1152 }
1153 }
1154
1155 proc popMsgRecordId {{setmsgid 1}} {
1156 lpopState evalid
1157 if {$setmsgid} {
1158 lpopState msgrecordid
1159 }
1160 }
1161
1162 proc clearAllMsgRecordId {} {
1163 unsetState evalid
1164 unsetState msgrecordid
1165 }
1166
1167 #
1168 # Format output text
1169 #
1170
1171 # format an element with its syms for display in a list
1172 proc formatListEltToDisplay {elt eltsgr eltsuffix sym_list symsgr show_syms\
1173 sgrdef tag_list show_tags vr_list vrsgr show_vrs {himatchmap {}}\
1174 {himatcharrvrmap {}} {himatcharrvrvalmap {}}} {
1175 # fetch sgr codes from tags to apply directly on main element
1176 if {$show_tags && [llength $tag_list]} {
1177 # if more codes than character in elt, additional codes apply to the
1178 # side tag list
1179 lassign [getTagSgrForModname $tag_list [string length $elt]] tagsgrlist\
1180 tag_list
1181 } else {
1182 set tagsgrlist {}
1183 }
1184 # display default sym graphically over element name
1185 if {$show_syms} {
1186 if {[set defidx [lsearch -exact $sym_list default]] != -1 && $sgrdef} {
1187 set sym_list [lreplace $sym_list $defidx $defidx]
1188 lappend eltsgrlist de
1189 }
1190 }
1191
1192 set displen 0
1193 set disp $elt
1194 lappend eltsgrlist $eltsgr
1195 set dispsgr [sgr $eltsgrlist $elt $himatchmap $tagsgrlist]
1196 # enclose name between quotes if a space is found
1197 if {[string first { } $elt] != -1} {
1198 incr displen 2
1199 set dispsgr '$dispsgr'
1200 }
1201 # append suffix
1202 append disp $eltsuffix
1203 append dispsgr $eltsuffix
1204
1205 # format variant list if any
1206 if {$show_vrs && [llength $vr_list]} {
1207 array set himatchvrvalarr $himatcharrvrvalmap
1208 array set himatchvrarr $himatcharrvrmap
1209 set commasgr [sgr se ,]
1210 set vrssgr "[sgr se \{]"
1211 set vrs \{
1212 foreach vrspec $vr_list {
1213 lassign $vrspec vrname vrnameset vrvalues vrdflidx vrloadedidx\
1214 loadedsgrkey
1215 array unset vrvalsgridx
1216 # apply sgr to default and loaded variant value
1217 if {$vrdflidx != -1} {
1218 lappend vrvalsgridx($vrdflidx) de
1219 }
1220 if {$vrloadedidx != -1} {
1221 lappend vrvalsgridx($vrloadedidx) $loadedsgrkey
1222 }
1223 set vrsgrvalues $vrvalues
1224 foreach vrvalidx [array names vrvalsgridx] {
1225 lset vrsgrvalues $vrvalidx [sgr $vrvalsgridx($vrvalidx) [lindex\
1226 $vrvalues $vrvalidx]]
1227 }
1228 if {[info exists notfirstvr]} {
1229 set colonsgr [sgr se :]
1230 append vrssgr $colonsgr
1231 append vrs :
1232 } else {
1233 set notfirstvr 1
1234 }
1235 # highlight variant if corresponds to one set in query
1236 if {[info exists himatchvrarr($vrname)]} {
1237 set hivrmap $himatchvrarr($vrname)
1238 set hivrvalmap $himatchvrvalarr($vrname)
1239 } else {
1240 set hivrmap {}
1241 set hivrvalmap {}
1242 }
1243 if {[string length $vrnameset]} {
1244 append vrssgr [sgr $vrsgr $vrnameset $hivrmap]
1245 }
1246 append vrssgr [sgr $vrsgr [lindex $vrsgrvalues 0] $hivrvalmap]
1247 foreach vrvalue [lrange $vrsgrvalues 1 end] {
1248 append vrssgr $commasgr[sgr $vrsgr $vrvalue $hivrvalmap]
1249 }
1250 append vrs $vrnameset[join $vrvalues :]
1251 }
1252 append vrssgr [sgr se \}]
1253 append vrs \}
1254 append dispsgr $vrssgr
1255 append disp $vrs
1256 }
1257
1258 # format remaining sym list
1259 if {$show_syms && [llength $sym_list]} {
1260 # track if a symbol has been reported excluding sym for alias '@'
1261 if {![info exists ::g_used_sym_nocolor] && ([llength $sym_list] > 1 ||
1262 [lindex $sym_list 0] ne {@})} {
1263 set ::g_used_sym_nocolor 1
1264 }
1265 append disp "([join $sym_list :])"
1266 set symssgr [sgr se (]
1267 foreach sym $sym_list {
1268 if {[info exists notfirstsym]} {
1269 if {![info exists colonsgr]} {
1270 set colonsgr [sgr se :]
1271 }
1272 append symssgr $colonsgr
1273 } else {
1274 set notfirstsym 1
1275 }
1276 append symssgr [sgr $symsgr $sym]
1277 }
1278 append symssgr [sgr se )]
1279 append dispsgr $symssgr
1280 }
1281
1282 # format tag list if any remaining
1283 if {$show_tags && [llength $tag_list]} {
1284 append disp " <[join $tag_list :]>"
1285 set tagssgr " [sgr se <]"
1286 foreach tag $tag_list {
1287 # track tag name or abbreviation that have been used
1288 if {![info exists ::g_used_tags($tag)]} {
1289 set ::g_used_tags($tag) 1
1290 }
1291 if {[info exists notfirsttag]} {
1292 if {![info exists colonsgr]} {
1293 set colonsgr [sgr se :]
1294 }
1295 append tagssgr $colonsgr
1296 } else {
1297 set notfirsttag 1
1298 }
1299 # try to sgr in case a code apply to the tag
1300 append tagssgr [sgr $tag $tag]
1301 }
1302 append tagssgr [sgr se >]
1303 append dispsgr $tagssgr
1304 }
1305
1306 # compute length
1307 incr displen [string length $disp]
1308
1309 return [list $disp $dispsgr $displen]
1310 }
1311
1312 # format an element with its syms for a long/detailed display in a list
1313 proc formatListEltToLongDisplay {elt eltsgr eltsuffix sym_list symsgr mtime\
1314 sgrdef {himatchmap {}}} {
1315 # display default sym graphically over element name
1316 if {[set defidx [lsearch -exact $sym_list default]] != -1 && $sgrdef} {
1317 set sym_list [lreplace $sym_list $defidx $defidx]
1318 lappend eltsgrlist de
1319 }
1320 lappend eltsgrlist $eltsgr
1321
1322 set displen 0
1323 set disp $elt
1324 set dispsgr [sgr $eltsgrlist $elt $himatchmap]
1325 # enclose name between quotes if a space is found
1326 if {[string first { } $elt] != -1} {
1327 incr displen 2
1328 set dispsgr '$dispsgr'
1329 }
1330 # append suffix
1331 append disp $eltsuffix
1332 append dispsgr $eltsuffix
1333
1334 # compute length
1335 incr displen [string length $disp]
1336
1337 # format remaining sym list
1338 if {[llength $sym_list]} {
1339 set symslen [string length [join $sym_list :]]
1340 foreach sym $sym_list {
1341 if {![info exists colonsgr]} {
1342 set colonsgr [sgr se :]
1343 } else {
1344 append symssgr $colonsgr
1345 }
1346 append symssgr [sgr $symsgr $sym]
1347 }
1348 } else {
1349 set symssgr {}
1350 set symslen 0
1351 }
1352 set nbws1 [expr {40 - $displen}]
1353 set nbws2 [expr {$nbws1 < 0 ? 20 - $symslen + $nbws1 : 20 - $symslen}]
1354 return [list $disp $dispsgr[string repeat { } $nbws1]$symssgr[string\
1355 repeat { } $nbws2]$mtime $displen]
1356 }
1357
1358 proc formatArrayValToJson {vallist} {
1359 return [expr {[llength $vallist] ? "\[ \"[join $vallist {", "}]\" \]" :\
1360 {[]}}]
1361 }
1362
1363 proc formatObjectValToJson {objlist} {
1364 foreach {key val isbool} $objlist {
1365 if {[info exists disp]} {
1366 append disp {, }
1367 }
1368 append disp "\"$key\": "
1369 if {$isbool} {
1370 append disp [expr {$val ? {true} : {false}}]
1371 } else {
1372 append disp "\"$val\""
1373 }
1374 }
1375 ##nagelfar ignore Bad expression
1376 return [expr {[info exists disp] ? "{ $disp }" : "{}"}]
1377 }
1378
1379 # format an element with its syms for a json display in a list
1380 proc formatListEltToJsonDisplay {elt args} {
1381 set disp "\"$elt\": \{ \"name\": \"$elt\""
1382 foreach {key vtype val show} $args {
1383 if {!$show} {
1384 continue
1385 }
1386 append disp ", \"$key\": "
1387 switch -- $vtype {
1388 a {append disp [formatArrayValToJson $val]}
1389 o {append disp [formatObjectValToJson $val]}
1390 s {append disp "\"$val\""}
1391 }
1392 }
1393 append disp "\}"
1394
1395 return $disp
1396 }
1397
1398 # Prepare a map list to translate later on a substring in its highlighted
1399 # counterpart. Translate substring into all module it specifies in case of an
1400 # advanced version specification. Each string obtained is right trimmed from
1401 # wildcard. No highlight is set for strings still containing wildcard chars
1402 # after right trim operation. No highlist map is returned at all if highlight
1403 # rendering is disabled.
1404 proc prepareMapToHightlightSubstr {args} {
1405 set maplist {}
1406 if {[sgr hi {}] ne {}} {
1407 foreach substr $args {
1408 foreach m [getAllModulesFromVersSpec $substr] {
1409 set m [string trimright $m {*?}]
1410 if {$m ne {} && [string first * $m] == -1 && [string first ? $m]\
1411 == -1} {
1412 lappend maplist $m [sgr hi $m]
1413 }
1414 }
1415 }
1416 }
1417 return $maplist
1418 }
1419
1420 # Specific highlight translation map for variant name and value
1421 proc prepareMapToHightlightVariant {args} {
1422 if {[sgr hi {}] ne {}} {
1423 foreach modspec $args {
1424 foreach vrspec [getVariantListFromVersSpec $modspec] {
1425 set vrvalues [lassign $vrspec vrname vrnot vrisbool]
1426 if {![info exists vrname_map($vrname)]} {
1427 set maplist [list $vrname [sgr hi $vrname]]
1428 # also highlight shortcut if any
1429 if {[info exists ::g_variantShortcut($vrname)]} {
1430 lappend maplist $::g_variantShortcut($vrname) [sgr hi\
1431 $::g_variantShortcut($vrname)]
1432 }
1433 set vrname_map($vrname) $maplist
1434 }
1435 # adapt variant value to highlight if boolean
1436 set maplist {}
1437 foreach vrvalue $vrvalues {
1438 if {$vrisbool} {
1439 set vrshort [expr {$vrvalue ? {+} : {-}}]$vrname
1440 lappend maplist $vrshort [sgr hi $vrshort]
1441 set vrvalue [expr {$vrvalue ? {on} : {off}}]
1442 }
1443 lappend maplist $vrvalue [sgr hi $vrvalue]
1444 }
1445 lappend vrval_map($vrname) {*}$maplist
1446 }
1447 }
1448 }
1449 return [list [array get vrname_map] [array get vrval_map]]
1450 }
1451
1452 # Format list of modules obtained from a getModules call in upper context
1453 proc reportModules {search_queries header hsgrkey hstyle show_mtime show_idx\
1454 one_per_line theader_cols excluded_tag {mod_list_order {}}} {
1455 # link to the result module list obtained in caller context
1456 upvar mod_list mod_list
1457
1458 # output is JSON format
1459 set json [isStateEqual report_format json]
1460
1461 # is some module variant specified in search query
1462 set variant_spec_in_query 0
1463 foreach modspec $search_queries {
1464 if {[llength [getVariantListFromVersSpec $modspec]]} {
1465 set variant_spec_in_query 1
1466 break
1467 }
1468 }
1469
1470 # elements to include in output
1471 if {[set report_indesym [isEltInReport indesym 0]]} {
1472 set report_sym 0
1473 } else {
1474 set report_sym [isEltInReport sym]
1475 }
1476 set report_tag [isEltInReport tag]
1477 set report_alias [expr {[isEltInReport alias] || [isEltInReport\
1478 provided-alias]}]
1479 # enable variant report if variantifspec configured and some variant is
1480 # specified in query or variant configured for report or list sub-command
1481 # json output
1482 set report_variant [expr {($variant_spec_in_query && [isEltInReport\
1483 variantifspec 0]) || [isEltInReport variant [expr {[currentState\
1484 commandname] eq {list} && $json}]]}]
1485 set collect_variant_from [expr {[currentState commandname] in {avail\
1486 spider} ? {2} : {0}}]
1487
1488 # prepare list of tag abbreviations that can be substituted and list of
1489 # tags whose name should be colored
1490 getConf tag_abbrev
1491 getConf tag_color_name
1492
1493 # prepare results for display
1494 set alias_colored [isSgrkeyColored al]
1495 set default_colored [isSgrkeyColored de]
1496 set himatchmap [prepareMapToHightlightSubstr {*}$search_queries]
1497 lassign [prepareMapToHightlightVariant {*}$search_queries]\
1498 himatcharrvrmap himatcharrvrvalmap
1499 set clean_list {}
1500 set vr_list {}
1501 set via_list [expr {[isEltInReport via] ? [getViaListModuleForModulepath\
1502 $header] : {}}]
1503
1504 # treat elements in specified order if any
1505 ##nagelfar ignore #2 Badly formed if statement
1506 foreach elt [if {![llength $mod_list_order]} {array names mod_list}\
1507 {set mod_list_order}] {
1508 if {$report_variant} {
1509 set vr_list [getVariantList $elt [expr {$json ? 4 : 7}] 0\
1510 $collect_variant_from]
1511 }
1512 set sym_list [getVersAliasList $elt]
1513 # fetch tags but clear excluded tag
1514 set tag_list [replaceFromList [getTagList $elt [lindex $mod_list($elt)\
1515 2]] $excluded_tag]
1516 # abbreviate tags unless for json output
1517 if {!$json} {
1518 set tag_list [abbrevTagList $tag_list]
1519 }
1520 set dispsgr {}
1521 # ignore "version" entries as symbolic version are treated
1522 # along to their relative modulefile not independently
1523 switch -- [lindex $mod_list($elt) 0] {
1524 directory {
1525 if {$json} {
1526 ##nagelfar ignore +2 Found constant
1527 set dispsgr [formatListEltToJsonDisplay $elt type s directory\
1528 1 symbols a $sym_list 1 via a $via_list 1]
1529 } elseif {$show_mtime} {
1530 # append / char after name to clearly indicate this is a dir
1531 lassign [formatListEltToLongDisplay $elt di / $sym_list sy {}\
1532 $default_colored $himatchmap] disp dispsgr displen
1533 } else {
1534 lassign [formatListEltToDisplay $elt di / $sym_list sy\
1535 $report_sym $default_colored {} 0 {} {} 0 $himatchmap] disp\
1536 dispsgr displen
1537 }
1538 }
1539 modulefile - virtual {
1540 if {$json} {
1541 ##nagelfar ignore +4 Found constant
1542 set dispsgr [formatListEltToJsonDisplay $elt type s modulefile\
1543 1 variants o $vr_list $report_variant symbols a $sym_list 1\
1544 tags a $tag_list 1 pathname s [lindex $mod_list($elt) 2] 1\
1545 via a $via_list 1]
1546 } elseif {$show_mtime} {
1547 set clock_mtime [expr {[lindex $mod_list($elt) 1] ne {} ?\
1548 [clock format [lindex $mod_list($elt) 1] -format {%Y/%m/%d\
1549 %H:%M:%S}] : {}}]
1550 # add to display file modification time in addition
1551 # to potential syms
1552 lassign [formatListEltToLongDisplay $elt {} {} $sym_list sy\
1553 $clock_mtime $default_colored $himatchmap] disp dispsgr\
1554 displen
1555 } else {
1556 lassign [formatListEltToDisplay $elt {} {} $sym_list sy\
1557 $report_sym $default_colored $tag_list $report_tag $vr_list\
1558 va $report_variant $himatchmap $himatcharrvrmap\
1559 $himatcharrvrvalmap] disp dispsgr displen
1560 }
1561 }
1562 alias {
1563 if {$json} {
1564 ##nagelfar ignore +3 Found constant
1565 set dispsgr [formatListEltToJsonDisplay $elt type s alias 1\
1566 symbols a $sym_list 1 tags a $tag_list 1 target s [lindex\
1567 $mod_list($elt) 1] 1 via a $via_list 1]
1568 } elseif {$show_mtime} {
1569 lassign [formatListEltToLongDisplay $elt al " -> [lindex\
1570 $mod_list($elt) 1]" $sym_list sy {} $default_colored\
1571 $himatchmap] disp dispsgr displen
1572 } elseif {$report_alias} {
1573 # add a '@' sym to indicate elt is an alias if not colored
1574 if {!$alias_colored} {
1575 lappend sym_list @
1576 # track use of '@' sym to add it to the output key
1577 if {$report_sym && ![info exists ::g_used_alias_nocolor]} {
1578 set ::g_used_alias_nocolor 1
1579 }
1580 }
1581 lassign [formatListEltToDisplay $elt al {} $sym_list sy\
1582 $report_sym $default_colored $tag_list $report_tag {} {} 0\
1583 $himatchmap] disp dispsgr displen
1584 }
1585 }
1586 version {
1587 # report symbolic version independently from the module it is
1588 # attached to. only done on regular or terse output when 'indesym'
1589 # element is in relative output configuration option
1590 if {$report_indesym} {
1591 lassign [formatListEltToDisplay $elt sy {} {} {} 0 0 {} 0 {}\
1592 {} 0 $himatchmap] disp dispsgr displen
1593 }
1594 }
1595 }
1596 if {$dispsgr ne {}} {
1597 if {$json} {
1598 lappend clean_list $dispsgr
1599 } else {
1600 lappend clean_list $disp
1601 set sgrmap($disp) $dispsgr
1602 set lenmap($disp) $displen
1603 }
1604 }
1605 }
1606
1607 set len_list {}
1608 # dictionary-sort results unless if output order is specified
1609 if {![llength $mod_list_order]} {
1610 set clean_list [lsort -dictionary $clean_list]
1611 }
1612 if {$json} {
1613 ##nagelfar ignore Found constant
1614 upvar 0 clean_list display_list
1615 } else {
1616 set display_list {}
1617 foreach disp $clean_list {
1618 # compute display element length list on sorted result
1619 lappend display_list $sgrmap($disp)
1620 lappend len_list $lenmap($disp)
1621 }
1622 }
1623
1624 # output table header if needed and not yet done
1625 if {[llength $display_list] && $show_mtime && ![isStateDefined\
1626 theader_shown]} {
1627 setState theader_shown 1
1628 displayTableHeader {*}$theader_cols
1629 }
1630
1631 # output formatted elements
1632 displayElementList $header $hsgrkey $hstyle $one_per_line $show_idx 1\
1633 $display_list $len_list $via_list
1634 }
1635
1636 proc showModulePath {} {
1637 set modpathlist [getModulePathList]
1638 if {[llength $modpathlist]} {
1639 report {Search path for module files (in search order):}
1640 foreach path $modpathlist {
1641 report " [sgr mp $path]"
1642 }
1643 } else {
1644 reportWarning {No directories on module search path}
1645 }
1646 }
1647
1648 proc displayTableHeader {sgrkey args} {
1649 foreach {title col_len} $args {
1650 set col "- [sgr $sgrkey $title] "
1651 append col [string repeat - [expr {$col_len - [string length $title] -\
1652 3}]]
1653 lappend col_list $col
1654 }
1655
1656 report [join $col_list .]
1657 }
1658
1659 proc displaySeparatorLine {{title {}} {sgrkey {}} {extra {}}} {
1660 set tty_cols [getState term_columns]
1661 if {$title eq {}} {
1662 # adapt length if screen width is very small
1663 set max_rep 67
1664 set rep [expr {$tty_cols > $max_rep ? $max_rep : $tty_cols}]
1665 report [string repeat - $rep]
1666 } else {
1667 set len [string length $title$extra]
1668 set lrep [tcl::mathfunc::max [expr {($tty_cols - $len - 2)/2}] 1]
1669 set rrep [tcl::mathfunc::max [expr {$tty_cols - $len - 2 - $lrep}] 1]
1670 report "[string repeat - $lrep] [sgr $sgrkey $title]$extra [string\
1671 repeat - $rrep]"
1672 }
1673 }
1674
1675 # get a list of elements and print them in a column or in a
1676 # one-per-line fashion
1677 proc displayElementList {header sgrkey hstyle one_per_line display_idx\
1678 start_idx display_list {len_list {}} {via_list {}}} {
1679 set elt_cnt [llength $display_list]
1680 reportDebug "header=$header, sgrkey=$sgrkey, hstyle=$hstyle,\
1681 elt_cnt=$elt_cnt, one_per_line=$one_per_line,\
1682 display_idx=$display_idx, start_idx=$start_idx, via=$via_list"
1683
1684 # end proc if no element are to print
1685 if {$elt_cnt == 0} {
1686 return
1687 }
1688 # output is JSON format
1689 set json [isStateEqual report_format json]
1690
1691 # display header if any provided
1692 if {$header ne {noheader}} {
1693 set header [getModulepathLabel $header]
1694 if {$json} {
1695 report "\"$header\": \{"
1696 } elseif {$hstyle eq {sepline}} {
1697 set extra [expr {[string length $via_list] ? " (via [join $via_list\
1698 { > }])" : {}}]
1699 displaySeparatorLine $header $sgrkey $extra
1700 } else {
1701 report [sgr $sgrkey $header]:
1702 }
1703 }
1704
1705 # increase index length when 100+ modules to report
1706 if {$display_idx} {
1707 set idx_len [expr {$elt_cnt > 99 ? {3} : {2}}]
1708 }
1709
1710 if {$json} {
1711 set displist [join $display_list ,\n]
1712 # display one element per line
1713 } elseif {$one_per_line} {
1714 if {$display_idx} {
1715 set idx $start_idx
1716 foreach elt $display_list {
1717 append displist [format "%${idx_len}d) %s " $idx $elt] \n
1718 incr idx
1719 }
1720 } else {
1721 append displist [join $display_list \n] \n
1722 }
1723 # elsewhere display elements in columns
1724 } else {
1725 # save room for numbers and spacing: 2 or 3 digits + ) + space
1726 set elt_prefix_len [expr {$display_idx ? $idx_len + 2 : {0}}]
1727 # save room for two spaces after element
1728 set tty_cols [getState term_columns]
1729
1730 lassign [compute_output_grid $tty_cols $len_list $elt_prefix_len] rows\
1731 cols cols_width
1732 reportDebug list=$display_list
1733 reportDebug "rows/cols=$rows/$cols,\
1734 lastcol_item_cnt=[expr {int($elt_cnt % $rows)}]"
1735
1736 for {set row 0} {$row < $rows} {incr row} {
1737 for {set col 0} {$col < $cols} {incr col} {
1738 set index [expr {$col * $rows + $row}]
1739 if {$index < $elt_cnt} {
1740 if {$display_idx} {
1741 append displist [format "%${idx_len}d) " [expr {$index +\
1742 $start_idx}]]
1743 }
1744 # cannot use 'format' as strings may contain SGR codes
1745 append displist [lindex $display_list $index][string repeat\
1746 { } [expr {[lindex $cols_width $col] - [lindex $len_list\
1747 $index] - $elt_prefix_len}]]
1748 }
1749 }
1750 append displist \n
1751 }
1752 }
1753 if {$json && $header ne {noheader}} {
1754 append displist "\n\}"
1755 }
1756 report $displist 1
1757 reportSeparateNextContent
1758 }
1759
1760 # returns rows, cols and each col width of the output grid with most cols
1761 proc compute_output_grid {out_width len_list prefix_len} {
1762 set col_sepa_len 2
1763 set elt_count [llength $len_list]
1764 if {!$elt_count} {
1765 return {0 0 {0}}
1766 }
1767
1768 # start with max possible columns guessed from shortest element in list
1769 set min_len [tcl::mathfunc::min {*}$len_list]
1770 set col_min [expr {$prefix_len + $min_len + $col_sepa_len}]
1771 # exact same output with 1 elt to print whether width is tiny or large
1772 set max_cols [tcl::mathfunc::min $elt_count\
1773 [expr {int(floor(double($out_width) / $col_min))}]]
1774
1775 for {set cols $max_cols} {$cols > 1} {incr cols -1} {
1776 set rows [expr {int(ceil(double($elt_count) / $cols))}]
1777 set cols_width {}
1778
1779 # compute width of each column (max length among elements in that col)
1780 for {set c 0} {$c < $cols} {incr c} {
1781 set idx_first [expr {$c * $rows}]
1782 set idx_last [expr {$idx_first + $rows - 1}]
1783 # stop when no more element for available columns
1784 if {$idx_first >= $elt_count} {
1785 break
1786 }
1787 set col_max [tcl::mathfunc::max {*}[lrange $len_list $idx_first\
1788 $idx_last]]
1789 set col_width [expr {$prefix_len + $col_max}]
1790 # column separator suffix is not added on last column
1791 if {($c + 1) < $cols && ($idx_last + 1) < $elt_count} {
1792 incr col_width $col_sepa_len
1793 }
1794 lappend cols_width $col_width
1795
1796 # immediately try fewer columns if we already exceed output grid
1797 if {[tcl::mathop::+ {*}$cols_width] > $out_width} {
1798 break
1799 }
1800 }
1801
1802 # ff it fits, this is the maximum cols possible
1803 if {[tcl::mathop::+ {*}$cols_width] <= $out_width} {
1804 return [list $rows $cols $cols_width]
1805 }
1806 }
1807
1808 # fits in 1 column
1809 return [list $elt_count 1 {0}]
1810 }
1811
1812 # Report an output key to help understand what the SGR used on this output
1813 # correspond to
1814 proc displayKey {} {
1815 # specific key entry for symbolic version if reported independently
1816 set typesym [list {symbolic-version}]
1817 if {![isEltInReport indesym 0]} {
1818 lappend typesym [sgr se (]<SGR>[sgr se )] 18
1819 }
1820
1821 array set skipsgr [list hi 1 db 1 tr 1 se 1 er 1 wa 1 me 1 in 1 cm 1 va 1]
1822 array set typesgr [list mp modulepath di [list directory <SGR>/ 10] al\
1823 module-alias sy $typesym de [list {default-version}]]
1824
1825 set display_list {}
1826 set len_list {}
1827 foreach key [array names ::g_used_colors] {
1828 # sgr key matches a basic modulefile type
1829 if {[info exists typesgr($key)]} {
1830 # the way to describe key is already defined
1831 if {[llength $typesgr($key)] > 1} {
1832 lassign $typesgr($key) desc desctmp len
1833 set desc [string map [list <SGR> [sgr $key $desc]] $desctmp]
1834 } else {
1835 set desc [lindex $typesgr($key) 0]
1836 }
1837 if {$key eq {sy} && [info exists ::g_used_sym_nocolor]} {
1838 unset ::g_used_sym_nocolor
1839 }
1840 # key is a tag abbreviation
1841 } elseif {[info exists ::g_abbrevTag($key)]} {
1842 set desc $::g_abbrevTag($key)
1843 # if not part of the ignored list, this key corresponds to a tag name
1844 } elseif {![info exists skipsgr($key)]} {
1845 set desc $key
1846 }
1847 if {[info exists desc]} {
1848 # define key description
1849 if {![info exists len]} {
1850 set len [string length $desc]
1851 set desc [sgr $key $desc]
1852 }
1853 lappend display_list $desc
1854 lappend len_list $len
1855 unset desc
1856 unset len
1857 }
1858 }
1859
1860 # include var=val key if any other variant form is present in report
1861 if {![info exists ::g_used_va(val)] && [array exists ::g_used_va]} {
1862 set ::g_used_va(val) 1
1863 }
1864 # add key for variant reports
1865 if {[info exists ::g_used_va(on)]} {
1866 lappend display_list "[sgr se \{][sgr va +variant][sgr se\
1867 \}]=[sgr se \{][sgr va variant=on][sgr se \}]"
1868 lappend len_list 23
1869 }
1870 if {[info exists ::g_used_va(off)]} {
1871 lappend display_list "[sgr se \{][sgr va -variant][sgr se\
1872 \}]=[sgr se \{][sgr va variant=off][sgr se \}]"
1873 lappend len_list 24
1874 }
1875 foreach sc [array names ::g_used_va] {
1876 if {$sc ni {on off val}} {
1877 lappend display_list "[sgr se \{][sgr va ${sc}value][sgr se\
1878 \}]=[sgr se \{][sgr va $::g_used_va($sc)=value][sgr se \}]"
1879 lappend len_list [expr {17 + [string length $::g_used_va($sc)]}]
1880 }
1881 }
1882 # finish with variant=value entry as it is referred by other variant keys
1883 if {[info exists ::g_used_va(val)]} {
1884 lappend display_list "[sgr se \{][sgr va variant=value][sgr se \}]"
1885 lappend len_list 15
1886 }
1887
1888 # add key for alias if '@' put in parentheses
1889 if {[info exists ::g_used_alias_nocolor]} {
1890 lappend display_list "[sgr se (]@[sgr se )]=module-alias"
1891 lappend len_list 9
1892 }
1893 # add key for symbolic version if any put in parentheses but no color
1894 if {[info exists ::g_used_sym_nocolor]} {
1895 lappend display_list "[sgr se (]symbolic-version[sgr se )]"
1896 lappend len_list 18
1897 }
1898
1899 # add key for module tag if any put in angle brackets
1900 if {[array exists ::g_used_tags]} {
1901 lappend display_list "[sgr se <]module-tag[sgr se >]"
1902 lappend len_list 12
1903 }
1904 # report translation of each uncolored tag abbreviation that have been used
1905 foreach tag [array names ::g_used_tags] {
1906 if {![info exists ::g_used_colors($tag)] && [info exists\
1907 ::g_abbrevTag($tag)]} {
1908 lappend display_list [sgr se <]$tag[sgr se >]=$::g_abbrevTag($tag)
1909 lappend len_list [expr {[string length $tag] + [string length\
1910 $::g_abbrevTag($tag)] + 3}]
1911 }
1912 }
1913
1914 if {[llength $display_list]} {
1915 # display header
1916 report Key:
1917 # display key content
1918 displayElementList noheader {} {} 0 0 0 $display_list $len_list
1919 }
1920 }
1921
1922 # Return conf value and from where an eventual def value has been overridden
1923 proc displayConfig {val env_var {asked 0} {trans {}} {locked 0}} {
1924 array set transarr $trans
1925
1926 # get overridden value and know what has overridden it
1927 if {$asked} {
1928 set defby " (cmd-line)"
1929 } elseif {$env_var ne {} && !$locked && [isEnvVarDefined $env_var]} {
1930 set defby " (env-var)"
1931 } elseif {$locked} {
1932 set defby " (locked)"
1933 } else {
1934 set defby {}
1935 }
1936
1937 # translate fetched value if translation table exists
1938 if {[info exists transarr($val)]} {
1939 set val $transarr($val)
1940 }
1941
1942 return $val$defby
1943 }
1944
1945 # report linter output as error/warning messages
1946 proc displayLinterOutput {linter output} {
1947 switch -- $linter {
1948 nagelfar {
1949 # parsing linter output
1950 set report_list {}
1951 foreach line [split $output \n] {
1952 set firstword [string range $line 0 [string first { } $line]-1]
1953 switch -- $firstword {
1954 Checking - Parsing {}
1955 Line {
1956 # add message of previous line if any
1957 if {[info exists msg]} {
1958 lappend report_list $msg
1959 }
1960
1961 # extract information from message line
1962 set colidx [string first : $line]
1963 set linenum [string trimleft [string range $line 5\
1964 $colidx-1]]
1965 set severity [string index $line $colidx+2]
1966 switch -- $severity {
1967 W {
1968 set severity WARNING
1969 set sgrkey wa
1970 set raisecnt 0
1971 }
1972 E {
1973 set severity ERROR
1974 set sgrkey er
1975 set raisecnt 1
1976 }
1977 default {
1978 set severity NOTICE
1979 set sgrkey in
1980 set raisecnt 0
1981 }
1982 }
1983 set msg [string range $line $colidx+4 end]
1984
1985 # start recorded message properties
1986 lappend report_list $linenum $severity $sgrkey $raisecnt
1987 }
1988 default {
1989 # this line is continuing message started previously
1990 append msg \n[string trimleft $line]
1991 }
1992 }
1993 }
1994 # add message of last line if any
1995 if {[info exists msg]} {
1996 lappend report_list $msg
1997 unset msg
1998 }
1999
2000 # report messages
2001 foreach {linenum severity sgrkey raisecnt mesg} $report_list {
2002 reportError $mesg "[format %-7s $severity] line $linenum"\
2003 $sgrkey $raisecnt
2004 }
2005 }
2006 default {
2007 reportError $output
2008 }
2009 }
2010 }
2011
2012 proc reportMlUsage {} {
2013 reportVersion
2014 report {Usage: ml [options] [command] [args ...]
2015 ml [options] [[-]modulefile ...]
2016
2017 Examples:
2018 ml equivalent to: module list
2019 ml foo bar equivalent to: module load foo bar
2020 ml -foo -bar baz equivalent to: module unload foo bar; module load baz
2021 ml avail -t equivalent to: module avail -t
2022
2023 See 'module --help' to get available commands and options.}
2024 }
2025
2026 proc reportUsage {} {
2027 reportVersion
2028 ##nagelfar ignore #141 Too long line
2029 report {Usage: module [options] [command] [args ...]
2030
2031 Loading / Unloading commands:
2032 add | load [-f] [-i] [--auto|--no-auto] [--tag=LIST] modulefile [...]
2033 Load modulefile(s)
2034 try-add | try-load [-f] [-i] [--auto|--no-auto] [--tag=LIST] modfile [...]
2035 Load modfile(s), no complain if not found
2036 add-any | load-any [-f] [-i] [--auto|--no-auto] [--tag=LIST] modfile [...]
2037 Load first available modulefile in list
2038 rm | remove | delete | unload [-f] [-i] [--auto|--no-auto] modulefile [...]
2039 Remove modulefile(s)
2040 purge [-f] Unload all loaded modulefiles
2041 reload | update [-f] Unload then load all loaded modulefiles
2042 switch | swap [-f] [-i] [--auto|--no-auto] [--tag=LIST] [mod1] mod2
2043 Unload mod1 and load mod2
2044 refresh Refresh loaded module volatile components
2045 reset [-f] Restore initial environment
2046
2047 Listing / Searching commands:
2048 list [-a] [-t|-l|-j] [-S|-C] [-o LIST] [mod ...]
2049 List all or matching loaded modules
2050 avail [-a] [-t|-l|-j] [-S|-C] [-d|-L] [-o LIST]
2051 [-i] [--indepth|--no-indepth] [mod ...]
2052 List all or matching available modules
2053 aliases [-a] List all module aliases
2054 whatis [-a] [-i] [-j] [modulefile ...]
2055 Print whatis information of modulefile(s)
2056 apropos | keyword | search [-a] [-j] str
2057 Search all name and whatis containing str
2058 spider [-a] [-t|-l|-j] [-S|-C] [-d|-L] [-o LIST]
2059 [-i] [--indepth|--no-indepth] [mod ...]
2060 Scan all modulepaths and list all or
2061 matching available modules
2062 is-loaded [-i] [modulefile ...] Test if any of the modulefile(s) are loaded
2063 is-avail [-i] modulefile [...] Is any of the modulefile(s) available
2064 info-loaded [-i] modulefile Get full name of matching loaded module(s)
2065
2066 Collection of modules handling commands:
2067 save [collection|file] Save current module list to collection
2068 restore [-f] [collection|file] Restore module list from collection or file
2069 saverm | disable [collection] Remove saved collection
2070 saveshow | describe [coll|file] Display information about collection
2071 savelist [-a] [-t|-l|-j] [-S|-C] [collection ...]
2072 List all or matching saved collections
2073 is-saved [collection ...] Test if any of the collection(s) exists
2074 stash [-f] Save current environment and reset
2075 stashpop [-f] [stash] Restore then remove stash collection
2076 stashrm [stash] Remove stash collection
2077 stashshow [stash] Display information about stash collection
2078 stashclear Remove all stash collections
2079 stashlist [-t|-l|-j] List all stash collections
2080
2081 Environment direct handling commands:
2082 prepend-path [-d c] [--duplicates] var val [...]
2083 Prepend value to environment variable
2084 append-path [-d c] [--duplicates] var val [...]
2085 Append value to environment variable
2086 remove-path [-d c] [--index] var val [...]
2087 Remove value from environment variable
2088
2089 Module cache handling commands:
2090 cachebuild [modulepath ...] Create cache file for modulepath(s)
2091 cacheclear Delete cache file in enabled modulepath(s)
2092
2093 Other commands:
2094 help [-i] [modulefile ...] Print this or modulefile(s) help info
2095 display | show [-i] modulefile [...]
2096 Display information about modulefile(s)
2097 test [-i] [modulefile ...] Test modulefile(s)
2098 use [-a|-p] dir [...] Add dir(s) to MODULEPATH variable
2099 unuse dir [...] Remove dir(s) from MODULEPATH variable
2100 is-used [dir ...] Is any of the dir(s) enabled in MODULEPATH
2101 path [-i] modulefile Print modulefile path
2102 paths [-i] modulefile Print path of matching available modules
2103 clear [-f] Reset Modules-specific runtime information
2104 source [--auto|--no-auto] [-f] scriptfile [...]
2105 Execute scriptfile(s)
2106 config [--dump-state|name [val]|--reset name]
2107 Display or set Modules configuration
2108 state [name] Display Modules state
2109 sh-to-mod shell shellscript [arg ...]
2110 Make modulefile from script env changes
2111 mod-to-sh [-f] [-i] [--auto|--no-auto] shell modulefile [...]
2112 Make shell code from modulefile env changes
2113 edit modulefile Open modulefile in editor
2114 lint [-a] [-i] [modulefile ...]
2115 Check syntax of modulefile
2116
2117 Switches:
2118 -t | --terse Display output in terse format
2119 -l | --long Display output in long format
2120 -j | --json Display output in JSON format
2121 -o LIST | --output=LIST
2122 Define elements to output on 'avail', 'spider' or 'list'
2123 sub-cmds in addition to module names (LIST is made of items
2124 like 'sym', 'tag', 'variant' or 'key' separated by ':')
2125 -a | --all Include hidden modules in search
2126 -d | --default Only show default versions available
2127 -L | --latest Only show latest versions available
2128 -S | --starts-with
2129 Search modules whose name begins with query string
2130 -C | --contains Search modules whose name contains query string
2131 -i | --icase Case insensitive match
2132 -a | --append Append directory to MODULEPATH (on 'use' sub-command)
2133 -p | --prepend Prepend directory to MODULEPATH
2134 --auto Enable automated module handling mode
2135 --no-auto Disable automated module handling mode
2136 -f | --force By-pass dependency consistency, abort on error or
2137 confirmation dialog
2138 --tag=LIST Apply tag to loading module on 'load', 'try-load', 'load-any'
2139 or 'switch' sub-commands (LIST is made of tag names
2140 separated by ':')
2141 -d C | --delim C
2142 Set delimiter character instead of ':' (on 'prepend-path',
2143 'append-path' or 'remove-path' sub-commands)
2144 --duplicates Allow duplicate entries (on 'prepend-path' or 'append-path'
2145 sub-commands)
2146 --index Given value is an index in the variable's list, instead of
2147 a value to look up (on 'remove-path' sub-command)
2148
2149 Options:
2150 -h | --help This usage info
2151 -V | --version Module version
2152 --dumpname Module implementation name
2153 -D | --debug Enable debug messages
2154 -T | --trace Enable trace messages
2155 -v | --verbose Enable verbose messages
2156 -s | --silent Turn off error, warning and informational messages
2157 --timer Report execution times
2158 -p | --paginate Pipe mesg output into a pager if stream attached to terminal
2159 -P | --no-pager Do not pipe message output into a pager
2160 --redirect Send output to stdout (only for sh, bash, ksh, zsh and fish)
2161 --no-redirect Send output to stderr
2162 --color[=WHEN] Colorize the output; WHEN can be 'always' (default if
2163 omitted), 'auto' or 'never'
2164 -w COLS | --width=COLS
2165 Set output width to COLS columns.
2166 --ignore-cache Ignore module cache
2167 --ignore-user-rc
2168 Skip evaluation of user-specific module rc file
2169 --no-modulepath-ignore
2170 Do not apply modulepath-ignore pattern definitions}
2171 }
2172
2173 # create appropriate message and kind of report when a requirement is not
2174 # satisfied
2175 proc reportMissingPrereqError {curmodnamevr modulepath_list args} {
2176 set is_path_specific [llength $modulepath_list]
2177 if {[isModuleEvaluated reqlo $curmodnamevr $modulepath_list {*}$args]} {
2178 set msg [getErrReqLoMsg $args $is_path_specific]
2179 } else {
2180 set retiseval [isModuleEvaluated any $curmodnamevr $modulepath_list\
2181 {*}$args]
2182 # more appropriate msg if an evaluation was attempted or is by-passed
2183 set msg [expr {$retiseval || [getState force] ? [getReqNotLoadedMsg\
2184 $args $is_path_specific] : [getErrPrereqMsg $args 1\
2185 $is_path_specific]}]
2186 }
2187
2188 knerrorOrWarningIfForced $msg MODULES_ERR_GLOBAL
2189 }
2190
2191 proc setConflictErrorAsReported {args} {
2192 lappendNoDup ::report_conflict([currentState evalid]) {*}$args
2193 # save content added to remove it later if evaluation is withdrawn
2194 if {[depthState reportholdid]} {
2195 lappend ::g_holdReportConflict([currentState reportholdid]) \
2196 [currentState evalid] $args
2197 }
2198 }
2199
2200 proc isConflictErrorAlreadyReported {msgrecid mod_con_list} {
2201 if {[info exists ::report_conflict($msgrecid)]} {
2202 return [isIntBetweenList $mod_con_list $::report_conflict($msgrecid)]
2203 } else {
2204 return 0
2205 }
2206 }
2207
2208 # Report final error caught on main catch block
2209 proc reportFinalError {error_msg} {
2210 # render error if not done yet
2211 if {$::errorCode ne {MODULES_ERR_RENDERED}} {
2212 incrErrorCount
2213 renderFalse
2214 }
2215
2216 if {$::errorCode ni [list MODULES_ERR_RENDERED MODULES_ERR_KNOWN]} {
2217 # add web link to report issue unless if an external error is detected
2218 set external_error_list [list\
2219 {Can't find a usable init.tcl in the following directories}\
2220 {interpreter uses an incompatible stubs mechanism}\
2221 {dlopen(}\
2222 {couldn't fork child process: resource temporarily unavailable}\
2223 {invalid command name "tcl::mathfunc::max"}]
2224 set add_report_link 1
2225 foreach external_error $external_error_list {
2226 if {[string equal -length [string length $external_error]\
2227 $external_error $error_msg]} {
2228 set add_report_link 0
2229 break
2230 }
2231 }
2232
2233 # report stack trace in addition to the error msg if error is unknown
2234 set error_msg $::errorInfo
2235
2236 if {$add_report_link} {
2237 append error_msg \n[sgr hi {Please report this issue at\
2238 https://github.com/envmodules/modules/issues}]
2239 }
2240 }
2241
2242 reportError $error_msg
2243 }
2244
2245 # ;;; Local Variables:
2246 # ;;; Mode: tcl-mode
2247 # ;;; tcl-indent-level: 3
2248 # ;;; tcl-continued-indent-level: 3
2249 # ;;; indent-tabs-mode: nil
2250 # ;;; End:
2251 # vim:set tabstop=3 shiftwidth=3 expandtab autoindent: