Debian Codegraph @

tcl/init.tcl.in

raw
1 ##########################################################################
2
3 # INIT.TCL, configuration and state handing 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 # Runtime state properties (default value, proc to call to initialize state
24 # value?)
25 ##nagelfar ignore +38 Found constant
26 array set g_state_defs [list\
27 autoinit {0}\
28 cache_mcookie_version {5.3}\
29 clock_seconds {<undef> initStateClockSeconds}\
30 domainname {<undef> initStateDomainname}\
31 error_count {0}\
32 extra_siteconfig_loaded {0}\
33 false_rendered {0}\
34 force {0}\
35 hiding_threshold {0 initStateHidingThreshold}\
36 inhibit_errreport {0}\
37 inhibit_interp {0}\
38 init_error_report {0}\
39 is_stderr_tty {<undef> initStateIsStderrTty}\
40 is_win {<undef> initStateIsWin}\
41 kernelversion {<undef> {runCommand uname -v}}\
42 linked_envvars {<undef> initStateLinkedEnvvars}\
43 logfd {{} initStateLogfd}\
44 logging {<undef> initStateLogging}\
45 lsb_codename {<undef> {runCommand lsb_release -s -c}}\
46 lsb_id {<undef> {runCommand lsb_release -s -i}}\
47 lsb_release {<undef> {runCommand lsb_release -s -r}}\
48 machine [list $::tcl_platform(machine)]\
49 modules_release {@MODULES_RELEASE@}\
50 nodename {<undef> {runCommand uname -n}}\
51 os [list $::tcl_platform(os)]\
52 osversion [list $::tcl_platform(osVersion)]\
53 paginate {<undef> initStatePaginate}\
54 path_separator {<undef> initStatePathSeparator}\
55 report_format {regular}\
56 reportfd {stderr initStateReportfd}\
57 return_false {0}\
58 siteconfig_loaded {0}\
59 shelltype {<undef> initStateShellType}\
60 sub1_separator {&}\
61 sub2_separator {|}\
62 tcl_ext_lib_loaded {0}\
63 tcl_version [list [info patchlevel]]\
64 term_columns {<undef> initStateTermColumns}\
65 timer {0}\
66 usergroups {<undef> initStateUsergroups}\
67 username {<undef> initStateUsername}\
68 ]
69
70 # Configuration option properties (superseding environment variable, default
71 # value, is configuration lockable to default value, value kind, valid value
72 # list?, internal value representation?, proc to call to initialize option
73 # value, valid value list kind
74 ##nagelfar ignore #103 Too long line
75 array set g_config_defs [list\
76 contact {MODULECONTACT root@localhost 0 s}\
77 abort_on_error {MODULES_ABORT_ON_ERROR {@abortonerror@} 0 l {load ml\
78 mod-to-sh purge reload switch switch_unload try-load unload} {} {}\
79 eltlist}\
80 auto_handling {MODULES_AUTO_HANDLING @autohandling@ 0 b {0 1}}\
81 avail_indepth {MODULES_AVAIL_INDEPTH @availindepth@ 0 b {0 1}}\
82 avail_output {MODULES_AVAIL_OUTPUT {@availoutput@} 0 l {modulepath alias\
83 provided-alias dirwsym indesym sym tag key hidden variant variantifspec\
84 via} {} {} eltlist}\
85 avail_terse_output {MODULES_AVAIL_TERSE_OUTPUT {@availterseoutput@} 0 l\
86 {modulepath alias provided-alias dirwsym indesym sym tag key hidden\
87 variant variantifspec} {} {} eltlist}\
88 cache_buffer_bytes {MODULES_CACHE_BUFFER_BYTES 32768 0 i {4096 1000000} {}\
89 {} intbe}\
90 cache_expiry_secs {MODULES_CACHE_EXPIRY_SECS 0 0 i {0 31536000} {} {}\
91 intbe}\
92 collection_pin_version {MODULES_COLLECTION_PIN_VERSION 0 0 b {0 1}}\
93 collection_pin_tag {MODULES_COLLECTION_PIN_TAG 0 0 b {0 1}}\
94 collection_target {MODULES_COLLECTION_TARGET <undef> 0 s}\
95 color {MODULES_COLOR @color@ 0 s {never auto always} {0 1 2}\
96 initConfColor}\
97 colors {MODULES_COLORS {} 0 l {} {} initConfColors}\
98 conflict_unload {MODULES_CONFLICT_UNLOAD @conflictunload@ 0 b {0 1}}\
99 csh_limit {{} 4000 0 i}\
100 domainname {MODULES_DOMAINNAME {@domainnamecmd@} 0 s}\
101 extra_siteconfig {MODULES_SITECONFIG <undef> 1 s {}}\
102 editor {MODULES_EDITOR {@editor@} 0 s {} {} initConfEditor}\
103 hide_auto_loaded {MODULES_HIDE_AUTO_LOADED 0 0 b {0 1}}\
104 home {MODULESHOME {@moduleshome@} 0 s}\
105 icase {MODULES_ICASE @icase@ 0 s {never search always}}\
106 ignore_cache {MODULES_IGNORE_CACHE 0 0 b {0 1}}\
107 ignore_cache_subcmds {MODULES_IGNORE_CACHE_SUBCMDS {} 0 l}\
108 ignore_user_rc {MODULES_IGNORE_USER_RC 0 0 b {0 1}}\
109 ignored_dirs {{} {CVS RCS SCCS .svn .git .SYNC .sos} 0 o}\
110 implicit_requirement {MODULES_IMPLICIT_REQUIREMENT @implicitrequirement@ 0\
111 b {0 1}}\
112 info_extension {MODULES_INFO_EXTENSION 0 0 b {0 1}}\
113 init_envvars {MODULES_INIT_ENVVARS {@initenvvars@} 0 l {} {}\
114 initConfInitEnvvars}\
115 linked_envvars {MODULES_LINKED_ENVVARS {} 0 l {} {}\
116 initConfLinkedEnvvars}\
117 list_output {MODULES_LIST_OUTPUT {@listoutput@} 0 l {header idx variant\
118 alias indesym sym tag hidden key} {} {} eltlist}\
119 list_terse_output {MODULES_LIST_TERSE_OUTPUT {@listterseoutput@} 0 l\
120 {header idx variant alias indesym sym tag hidden key} {} {} eltlist}\
121 locked_configs {{} {@lockedconfigs@} 0 o}\
122 logged_events {MODULES_LOGGED_EVENTS {@loggedevents@} 1 l {auto_eval\
123 requested_eval requested_cmd} {} {} eltlist}\
124 logger {MODULES_LOGGER {@loggercmd@} 1 s}\
125 mcookie_check {MODULES_MCOOKIE_CHECK always 0 s {eval always}}\
126 mcookie_version_check {MODULES_MCOOKIE_VERSION_CHECK\
127 @mcookieversioncheck@ 0 b {0 1}}\
128 ml {MODULES_ML @ml@ 0 b {0 1}}\
129 modulepath_ignore {MODULES_MODULEPATH_IGNORE 1 0 b {0 1}}\
130 nearly_forbidden_days {MODULES_NEARLY_FORBIDDEN_DAYS @nearlyforbiddendays@\
131 0 i {0 365} {} {} intbe}\
132 non_exportable_tags {MODULES_NON_EXPORTABLE_TAGS {} 0 l}\
133 pager {MODULES_PAGER {@pagercmd@} 0 s}\
134 paginate {MODULES_PAGINATE @paginate@ 0 b {0 1}}\
135 path_entry_reorder {MODULES_PATH_ENTRY_REORDER @pathentryreorder@ 0 b {0 1}}\
136 protected_envvars {MODULES_PROTECTED_ENVVARS <undef> 0 l}\
137 rcfile {MODULERCFILE <undef> 0 l}\
138 redirect_output {MODULES_REDIRECT_OUTPUT 1 0 b {0 1}}\
139 require_via {MODULES_REQUIRE_VIA @requirevia@ 0 b {0 1}}\
140 reset_target_state {MODULES_RESET_TARGET_STATE __init__ 0 s}\
141 quarantine_support {MODULES_QUARANTINE_SUPPORT @quarantinesupport@ 0 b {0\
142 1}}\
143 run_quarantine {MODULES_RUN_QUARANTINE <undef> 0 o}\
144 shells_with_ksh_fpath {MODULES_SHELLS_WITH_KSH_FPATH {} 0 l {sh bash csh\
145 tcsh fish} {} {} eltlist}\
146 silent_shell_debug {MODULES_SILENT_SHELL_DEBUG @silentshdbgsupport@ 0 b {0\
147 1}}\
148 siteconfig {{} {@etcdir@/siteconfig.tcl} 0 s}\
149 spider_indepth {MODULES_SPIDER_INDEPTH @spiderindepth@ 0 b {0 1}}\
150 spider_output {MODULES_SPIDER_OUTPUT {@spideroutput@} 0 l {modulepath\
151 alias provided-alias dirwsym indesym sym tag key hidden variant\
152 variantifspec via} {} {} eltlist}\
153 spider_terse_output {MODULES_SPIDER_TERSE_OUTPUT {@spiderterseoutput@} 0 l\
154 {modulepath alias provided-alias dirwsym indesym sym tag key hidden\
155 variant variantifspec} {} {} eltlist}\
156 source_cache {MODULES_SOURCE_CACHE @sourcecache@ 0 b {0 1}}\
157 sticky_purge {MODULES_STICKY_PURGE {@stickypurge@} 0 s {error warning\
158 silent}}\
159 tag_abbrev {MODULES_TAG_ABBREV {@tagabbrev@} 0 l {} {} initConfTagAbbrev}\
160 tag_color_name {MODULES_TAG_COLOR_NAME {@tagcolorname@} 0 l {} {}\
161 initConfTagColorName}\
162 tcl_ext_lib {{} {} 0 s {} {} initConfTclExtLib}\
163 tcl_linter {MODULES_TCL_LINTER {@tcllintercmd@} 0 s}\
164 term_background {MODULES_TERM_BACKGROUND @termbg@ 0 s {dark light}}\
165 term_width {MODULES_TERM_WIDTH 0 0 i {0 1000} {} {} intbe}\
166 unique_name_loaded {MODULES_UNIQUE_NAME_LOADED @uniquenameloaded@ 0 b {0\
167 1}}\
168 unload_match_order {MODULES_UNLOAD_MATCH_ORDER @unloadmatchorder@ 0 s\
169 {returnlast returnfirst}}\
170 implicit_default {MODULES_IMPLICIT_DEFAULT @implicitdefault@ 1 b {0 1}}\
171 extended_default {MODULES_EXTENDED_DEFAULT @extendeddefault@ 0 b {0 1}}\
172 advanced_version_spec {MODULES_ADVANCED_VERSION_SPEC @advversspec@ 0 b {0\
173 1}}\
174 search_match {MODULES_SEARCH_MATCH @searchmatch@ 0 s {starts_with\
175 contains}}\
176 set_shell_startup {MODULES_SET_SHELL_STARTUP @setshellstartup@ 0 b {0 1}}\
177 variant_shortcut {MODULES_VARIANT_SHORTCUT {@variantshortcut@} 0 l {} {}\
178 initConfVariantShortcut}\
179 verbosity {MODULES_VERBOSITY @verbosity@ 0 s {silent concise normal\
180 verbose verbose2 trace debug debug2}}\
181 wa_277 {MODULES_WA_277 @wa277@ 0 b {0 1}}\
182 ]
183
184 # List of events on which a site-specific procedure can be registered through
185 # the add-hook command
186 set g_hookEvents {before-modulefile-eval after-modulefile-eval\
187 before-modulerc-eval after-modulerc-eval}
188
189 # Get state value
190 proc getState {state {valifundef {}} {catchinitproc 0}} {
191 if {![info exists ::g_states($state)]} {
192 # fetch state properties (including its default value) if defined
193 if {[info exists ::g_state_defs($state)]} {
194 lassign $::g_state_defs($state) value initproclist
195 } else {
196 set value <undef>
197 set initproclist {}
198 }
199
200 # call specific proc to initialize state if any
201 if {$initproclist ne {}} {
202 # catch init procedure error and report it as warning, so default
203 # value will get set for state
204 if {$catchinitproc} {
205 if {[catch {set value [{*}$initproclist]} errMsg]} {
206 reportWarning $errMsg
207 }
208 } else {
209 set value [{*}$initproclist]
210 }
211 # overridden value coming the command-line
212 ##nagelfar ignore Suspicious variable
213 } elseif {[info exists ::asked_$state]} {
214 set value [set ::asked_$state]
215 }
216
217 # return passed value if undefined and no value record
218 if {$value eq {<undef>}} {
219 set value $valifundef
220 } else {
221 setState $state $value
222 }
223 return $value
224 } else {
225 return $::g_states($state)
226 }
227 }
228
229 # Clear state
230 proc unsetState {state} {
231 if {[isStateDefined $state]} {
232 unset ::g_states($state)
233 reportDebug "$state unset"
234 }
235 }
236
237 # Set state value
238 proc setState {state value} {
239 set ::g_states($state) $value
240 reportDebug "$state set to '$value'"
241 }
242
243 # Append each passed value to the existing state value list
244 proc lappendState {state args} {
245 if {$state eq {-nodup}} {
246 set state [lindex $args 0]
247 # retrieve current val through getState to initialize it if still undef
248 set value [getState $state]
249 ##nagelfar ignore Found constant
250 lappendNoDup value {*}[lrange $args 1 end]
251 setState $state $value
252 } else {
253 lappend ::g_states($state) {*}$args
254 reportDebug "$state appended with '$args'"
255 }
256 }
257
258 # Remove last element from state value list
259 proc lpopState {state} {
260 lpop ::g_states($state)
261 reportDebug "$state removed last item"
262 }
263
264 # Return first element from state value list
265 proc topState {state} {
266 return [lindex [getState $state] 0]
267 }
268
269 # Return last element from state value list
270 proc currentState {state} {
271 return [lindex [getState $state] end]
272 }
273
274 # Get number of element from state value list
275 proc depthState {state} {
276 return [llength [getState $state]]
277 }
278
279 # Check if state has been defined
280 proc isStateDefined {state} {
281 return [info exists ::g_states($state)]
282 }
283
284 # Check if state equals passed value
285 proc isStateEqual {state value} {
286 return [expr {[getState $state] eq $value}]
287 }
288
289 proc isConfigLocked {option} {
290 return [expr {[lsearch -exact [getConf locked_configs] $option] != -1}]
291 }
292
293 # Get configuration option value
294 proc getConf {option {valifundef {}}} {
295 if {![info exists ::g_configs($option)]} {
296 # fetch option properties (including its default value)
297 lassign $::g_config_defs($option) envvar value islockable valuekind\
298 validvallist intvallist initproc validvallistkind
299
300 # ensure option is not locked before superseding its default value
301 if {!$islockable || ![isConfigLocked $option]} {
302 # call specific proc to initialize config option if any
303 if {$initproc ne {}} {
304 set value [$initproc $envvar $value $validvallist $intvallist]
305 } else {
306 # overridden value coming from environment
307 if {$envvar ne {} && [isEnvVarDefined $envvar]} {
308 switch -- $validvallistkind {
309 eltlist {
310 # ignore non-valid values
311 if {![isDiffBetweenList [split $::env($envvar) :]\
312 $validvallist]} {
313 set value $::env($envvar)
314 }
315 }
316 intbe {
317 # ignore non-valid values
318 if {[string is integer -strict $::env($envvar)] &&\
319 $::env($envvar) >= [lindex $validvallist 0] &&\
320 $::env($envvar) <= [lindex $validvallist 1]} {
321 set value $::env($envvar)
322 }
323 }
324 {} {
325 # ignore non-valid values
326 ##nagelfar ignore +3 Non static subcommand
327 if {[switch -- [llength $validvallist] {
328 0 {expr {1 == 1}}
329 1 {string is $validvallist -strict $::env($envvar)}
330 default {expr {$::env($envvar) in $validvallist}}
331 }]} {
332 set value $::env($envvar)
333 }
334 }
335 }
336 }
337
338 # overridden value coming the command-line (already validated)
339 ##nagelfar ignore Suspicious variable
340 if {[info exists ::asked_$option]} {
341 set askedval [set ::asked_$option]
342 # append or subtract value to existing configuration value if
343 # new value starts with '+' or '-' (for colon-separated list
344 # option only)
345 if {$valuekind eq {l} && [string index $askedval 0] in {+ -}} {
346 set curvaluelist [split $value :]
347 switch -- [string index $askedval 0] {
348 + {
349 ##nagelfar ignore Found constant
350 lappendNoDup curvaluelist {*}[split [string range\
351 $askedval 1 end] :]
352 }
353 - {
354 lassign [getDiffBetweenList $curvaluelist [split\
355 [string range $askedval 1 end] :]] curvaluelist
356 }
357 }
358 set value [join $curvaluelist :]
359 } else {
360 set value $askedval
361 }
362 }
363
364 # convert value to its internal representation
365 if {[llength $intvallist]} {
366 set value [lindex $intvallist [lsearch -exact $validvallist\
367 $value]]
368 }
369 }
370 }
371
372 # return passed value if undefined and no value record
373 if {$value eq {<undef>}} {
374 set value $valifundef
375 } else {
376 setConf $option $value
377 }
378 return $value
379 } else {
380 return $::g_configs($option)
381 }
382 }
383
384 # Check if configuration option has been defined
385 proc isConfDefined {option} {
386 return [info exists ::g_configs($option)]
387 }
388
389 # Set configuration option value
390 proc setConf {option value} {
391 set ::g_configs($option) $value
392 reportDebug "$option set to '$value'"
393 }
394
395 # Unset configuration option value if it is set
396 proc unsetConf {option} {
397 if {[info exists ::g_configs($option)]} {
398 unset ::g_configs($option)
399 reportDebug "$option unset"
400 }
401 }
402
403 # Append each passed value to the existing config option value list
404 proc lappendConf {option args} {
405 # retrieve current value through getConf to initialize it if still undef
406 set value [getConf $option]
407 ##nagelfar ignore Found constant
408 lappendNoDup value {*}$args
409 setConf $option $value
410 }
411
412 # Get configuration option value split as a list
413 proc getConfList {option {valifundef {}}} {
414 return [split [getConf $option $valifundef] :]
415 }
416
417 # Source site config which can be used to define global procedures or
418 # settings. We first look for the global siteconfig, then if an extra
419 # siteconfig is defined and allowed, source that file if it exists
420 proc sourceSiteConfig {} {
421 lappend siteconfiglist [getConf siteconfig]
422 for {set i 0} {$i < [llength $siteconfiglist]} {incr i} {
423 set siteconfig [lindex $siteconfiglist $i]
424 if {[file readable $siteconfig]} {
425 reportDebug "Source site configuration ($siteconfig)"
426 if {[catch {uplevel 1 source "{$siteconfig}"} errMsg]} {
427 set errMsg "Site configuration source failed\n"
428 # issue line number is lost due to uplevel use
429 append errMsg [formatErrStackTrace $::errorInfo $siteconfig {}]
430 reportErrorAndExit $errMsg
431 }
432 ##nagelfar ignore Found constant
433 if {$siteconfig eq [getConf siteconfig]} {
434 setState siteconfig_loaded 1
435 } else {
436 setState extra_siteconfig_loaded 1
437 }
438 }
439 # check on extra_siteconfig after initial siteconfig loaded in case
440 # it inhibits this extra load
441 ##nagelfar ignore Found constant
442 if {$siteconfig eq [getConf siteconfig] && [getConf\
443 extra_siteconfig] ne {}} {
444 lappend siteconfiglist [getConf extra_siteconfig]
445 }
446 }
447 }
448
449 # Used to tell if a machine is running Windows or not
450 proc initStateIsWin {} {
451 return [expr {$::tcl_platform(platform) eq {windows}}]
452 }
453
454 # Get default path separator
455 proc initStatePathSeparator {} {
456 return [expr {[getState is_win] ? {;} : {:}}]
457 }
458
459 # Detect if terminal is attached to stderr message channel
460 proc initStateIsStderrTty {} {
461 return [expr {![catch {fconfigure stderr -mode}]}]
462 }
463
464 # Determine if pagination need to be started
465 proc initStatePaginate {} {
466 if {![getConf paginate]} {
467 return 0
468 }
469
470 set pager [getConf pager]
471 # empty or 'cat' pager command means no-pager
472 set nopager_cmd_list [list {} cat]
473 if {[file tail [lindex $pager 0]] in $nopager_cmd_list} {
474 return 0
475 }
476
477 set pager_shell_list [list sh csh fish cmd pwsh]
478 if {[getState shelltype] ni $pager_shell_list} {
479 return 0
480 }
481
482 # some module sub-commands turn off pager
483 set nopager_subcmd_list [list clear edit]
484 if {[getState subcmd] in $nopager_subcmd_list || ([getState subcmd] eq\
485 {ml} && [lindex [getState subcmd_args] 0] in $nopager_subcmd_list)} {
486 return 0
487 }
488
489 # error stream must be attached to a terminal
490 if {![getState is_stderr_tty]} {
491 return 0
492 }
493
494 return 1
495 }
496
497 # start pager pipe process with defined configuration
498 proc initStateReportfd {} {
499 # get default value
500 lassign $::g_state_defs(reportfd) reportfd
501
502 # start pager at first call and only if enabled
503 if {[getState paginate]} {
504 if {[catch {
505 set reportfd [open "|[getConf pager] >@stderr 2>@stderr" w]
506 fconfigure $reportfd -buffering line -blocking 1 -buffersize 65536
507 } errMsg]} {
508 # silently set reportfd to its fallback value to process warn msg
509 set ::g_states(reportfd) $reportfd
510 reportWarning $errMsg
511 }
512 }
513
514 # startup content in case of structured output format (puts here rather
515 # calling report proc to avoid infinite reportfd init loop
516 if {[isStateEqual report_format json]} {
517 puts -nonewline $reportfd \{
518 }
519
520 return $reportfd
521 }
522
523 proc initStateLinkedEnvvars {} {
524 getConf linked_envvars
525 return [array get ::g_linkedEnvvars]
526 }
527
528 proc initStateDomainname {} {
529 return [runCommand {*}[getConf domainname]]
530 }
531
532 # Determine if logging need to be started
533 proc initStateLogging {} {
534 set logger_not_empty [string length [lindex [getConf logger] 0]]
535 set something_to_log [info exists ::g_log_msg_list]
536 return [expr {$logger_not_empty && $something_to_log}]
537 }
538
539 # start logger pipe process with defined configuration
540 proc initStateLogfd {} {
541 # sets default fallback value
542 lassign $::g_state_defs(logfd) logfd
543
544 # start logger at first call and only if enabled
545 if {[getState logging]} {
546 if {[catch {
547 # drop output of logger command to avoid it pollutes main channels
548 set logfd [open "|[getConf logger] >/dev/null 2>/dev/null" w]
549 fconfigure $logfd -buffering none -blocking 1
550 } errMsg]} {
551 reportWarning $errMsg
552 }
553 }
554
555 return $logfd
556 }
557
558 # Provide columns number for output formatting
559 proc initStateTermColumns {} {
560 set cols [getConf term_width]
561 if {$cols == 0} {
562 # determine col number from tty capabilities
563 # tty info query depends on running OS
564 switch -- $::tcl_platform(os) {
565 SunOS {
566 catch {regexp {columns = (\d+);} [exec stty] match cols} errMsg
567 }
568 {Windows NT} {
569 catch {regexp {Columns:\s+(\d+)} [exec mode] match cols} errMsg
570 }
571 default {
572 catch {set cols [lindex [exec stty size] 1]} errMsg
573 }
574 }
575 # default size if tty cols cannot be found
576 set cols [expr {![info exists cols] || $cols eq {0} ? 80 : $cols}]
577 }
578 return $cols
579 }
580
581 # Deduce shelltype value from shell state value
582 proc initStateShellType {} {
583 switch -- [getState shell] {
584 sh - bash - ksh - zsh {
585 return sh
586 }
587 csh - tcsh {
588 return csh
589 }
590 default {
591 return [getState shell]
592 }
593 }
594 }
595
596 proc initStateHidingThreshold {} {
597 # sets default fallback value
598 lassign $::g_state_defs(hiding_threshold) hiding_threshold
599
600 if {[isEltInReport hidden 0]} {
601 set hiding_threshold 2
602 } elseif {[info exists ::asked_hiding_threshold]} {
603 set hiding_threshold $::asked_hiding_threshold
604 }
605
606 return $hiding_threshold
607 }
608
609 # Get all groups of user running modulecmd.tcl process
610 proc __initStateUsergroups {} {
611 set user_group_list {}
612 # parse regular "id" output to get all group, also those whose name cannot
613 # be resolved or contain a space character
614 set id_out [runEnvCommand {LANG C} id]
615 set id_out_grp_start [expr {[string first {groups=} $id_out] + 7}]
616 set id_out_next_start [string first = $id_out $id_out_grp_start]
617 ##nagelfar ignore #2 Badly formed if statement
618 set id_out_grp_end [if {$id_out_next_start > -1} {expr {[string last { }\
619 $id_out $id_out_next_start] - 1}} {return -level 0 end}]
620 set id_grp_out [string range $id_out $id_out_grp_start $id_out_grp_end]
621
622 foreach grp_info [split $id_grp_out ,] {
623 if {[set idx [string first ( $grp_info]] != -1} {
624 set grp [string range $grp_info $idx+1 end-1]
625 } else {
626 # use group gid number as name if it cannot be resolved
627 set grp $grp_info
628 }
629 lappend user_group_list $grp
630 }
631 return $user_group_list
632 }
633
634 # Get name of user running modulecmd.tcl process
635 proc __initStateUsername {} {
636 return [runCommand id -u -n]
637 }
638
639 # Get Epoch time (number of seconds elapsed since Unix epoch)
640 proc __initStateClockSeconds {} {
641 return [clock seconds]
642 }
643
644 proc parseEqualListConfValue {option envvar value {level Warning}} {
645 # overridden value coming from environment
646 if {[isEnvVarDefined $envvar]} {
647 if {[catch {
648 # try to set the variable init value mapping table
649 array set test_arr [split $::env($envvar) {:=}]
650 set value $::env($envvar)
651 set setfromenv 1
652 } errMsg ]} {
653 report$level "Ignore invalid value set in $envvar ($::env($envvar))"
654 }
655 }
656
657 # test default value
658 if {![info exists setfromenv]} {
659 if {[catch {
660 array set test_arr [split $value {:=}]
661 } errMsg ]} {
662 report$level "Ignore invalid default value for '$option' config\
663 ($value)"
664 # define an empty list if no valid value set
665 set value {}
666 }
667 }
668
669 return $value
670 }
671
672 # Initialize Select Graphic Rendition table
673 proc initConfColors {envvar value validvallist intvallist} {
674 # default color theme depends on terminal background color kind
675 if {[getConf term_background] eq {light}} {
676 ##nagelfar ignore Too long line
677 set value {@lightbgcolors@}
678 set option light-background-colors
679 } else {
680 ##nagelfar ignore Too long line
681 set value {@darkbgcolors@}
682 set option dark-background-colors
683 }
684 set value [parseEqualListConfValue $option $envvar $value Debug]
685
686 # check each color defined and unset invalid codes
687 set colors_list {}
688 foreach {elt col} [split $value {:=}] {
689 if {![regexp {^[\d;]+$} $col]} {
690 reportDebug "Ignore invalid color code for '$elt' ($col)"
691 } else {
692 lappend colors_list $elt=$col
693 }
694 }
695 set value [join $colors_list :]
696
697 # set SGR table as an array to easily access rendition for each key
698 array unset ::g_colors
699 array set ::g_colors [split $value {:=}]
700
701 return $value
702 }
703
704 # Initialize color configuration value
705 proc initConfColor {envvar value validvallist intvallist} {
706 # overridden value coming from environment via standard variable
707 # https://no-color.org/ and https://bixense.com/clicolors/
708 if {[isEnvVarDefined NO_COLOR]} {
709 set value never
710 } elseif {[isEnvVarDefined CLICOLOR]} {
711 if {[envVarEquals CLICOLOR 0]} {
712 set value never
713 } else {
714 set value auto
715 }
716 } elseif {[isEnvVarDefined CLICOLOR_FORCE] && $::env(CLICOLOR_FORCE) ne\
717 {0}} {
718 set value always
719 }
720
721 # overridden value coming from environment via Modules-specific variable
722 if {$envvar ne {} && [isEnvVarDefined $envvar]} {
723 # ignore non-valid values
724 if {![llength $validvallist] || $::env($envvar) in $validvallist} {
725 set value $::env($envvar)
726 }
727 }
728
729 # overridden value coming the command-line
730 if {[info exists ::asked_color]} {
731 set value [set ::asked_color]
732 }
733
734 # convert value to its internal representation
735 set value [lindex $intvallist [lsearch -exact $validvallist $value]]
736
737 # disable color mode if no terminal attached except if 'always' asked
738 if {$value != 0 && (![getState is_stderr_tty] || $value == 2)} {
739 incr value -1
740 }
741
742 # initialize color theme if color mode enabled
743 getConf colors
744
745 return $value
746 }
747
748 # Initialize tcl_ext_lib configuration value
749 proc initConfTclExtLib {envvar value validvallist intvallist} {
750 set libfile libtclenvmodules@SHLIB_SUFFIX@
751
752 # determine lib directory
753 ##nagelfar ignore #19 Strange command
754 ##nagelfar ignore +13 Too long line
755 @notmultilibsupport@set libdir {@libdir@}
756 @multilibsupport@switch -- [getState machine] {
757 @multilibsupport@ x86_64 - aarch64 - ppc64le - s390x {
758 @multilibsupport@ set libdirmain {@libdir64@}
759 @multilibsupport@ set libdiralt {@libdir32@}
760 @multilibsupport@ }
761 @multilibsupport@ default {
762 @multilibsupport@ set libdirmain {@libdir32@}
763 @multilibsupport@ set libdiralt {@libdir64@}
764 @multilibsupport@ }
765 @multilibsupport@}
766 @multilibsupport@# use alternative arch lib if available and not main one
767 @multilibsupport@if {![file exists [file join $libdirmain $libfile]] && [file exists [file\
768 @multilibsupport@ join $libdiralt $libfile]]} {
769 @multilibsupport@ set libdir $libdiralt
770 @multilibsupport@} else {
771 @multilibsupport@ set libdir $libdirmain
772 @multilibsupport@}
773 ##nagelfar variable libdir
774
775 return [file join $libdir $libfile]
776 }
777
778 # Initialize module tag abbreviation table
779 proc initConfTagAbbrev {envvar value validvallist intvallist} {
780 set value [parseEqualListConfValue tag_abbrev $envvar $value]
781 array set ::g_tagAbbrev [split $value {:=}]
782
783 # build abbrev:tagname array
784 foreach {tag abbrev} [array get ::g_tagAbbrev] {
785 # skip tags not relevant for current command, that share their
786 # abbreviation with another tag
787 switch -- $tag {
788 hidden-loaded {
789 set setabbrevtag [expr {[currentState commandname] eq {list}}]
790 }
791 hidden {
792 set setabbrevtag [expr {[currentState commandname] in {avail\
793 spider}}]
794 }
795 default {
796 set setabbrevtag 1
797 }
798 }
799 if {$setabbrevtag} {
800 set ::g_abbrevTag($abbrev) $tag
801 }
802 }
803
804 return $value
805 }
806
807 # Initialize module tag color name table
808 proc initConfTagColorName {envvar value validvallist intvallist} {
809 # overridden value coming from environment
810 if {[isEnvVarDefined $envvar]} {
811 set value $::env($envvar)
812 }
813
814 # set table for efficient search
815 foreach tag [split $value :] {
816 set ::g_tagColorName($tag) 1
817 }
818
819 return $value
820 }
821
822 # Initialize env variable initial value array
823 proc initConfInitEnvvars {envvar value validvallist intvallist} {
824 set value [parseEqualListConfValue init_envvars $envvar $value]
825 array set ::g_initEnvvars [split $value {:=}]
826
827 return $value
828 }
829
830 # Initialize env variable link array
831 proc initConfLinkedEnvvars {envvar value validvallist intvallist} {
832 # overridden value coming from environment
833 if {[isEnvVarDefined $envvar]} {
834 set value $::env($envvar)
835 }
836
837 # set array to get full value for one env var if set through multiple args
838 foreach link_arg [split $value :] {
839 set linked_envvar_list [lassign [split $link_arg &] src_envvar]
840 if {![string length $src_envvar] || ![llength $linked_envvar_list] ||\
841 {} in $linked_envvar_list || $src_envvar in $linked_envvar_list} {
842 reportWarning "Ignore invalid link defined in $envvar ($link_arg)"
843 } else {
844 lappendNoDup ::g_linkedEnvvars($src_envvar) {*}$linked_envvar_list
845 }
846 }
847
848 return $value
849 }
850
851 # Initialize interactive editor command
852 proc initConfEditor {envvar value validvallist intvallist} {
853 # overridden value coming from environment via Modules-specific variable
854 if {$envvar ne {} && [isEnvVarDefined $envvar]} {
855 set value $::env($envvar)
856 # overridden value coming from environment via standard variable
857 } elseif {[isEnvVarDefined VISUAL]} {
858 set value $::env(VISUAL)
859 } elseif {[isEnvVarDefined EDITOR]} {
860 set value $::env(EDITOR)
861 }
862 return $value
863 }
864
865 # Initialize variant shortcut table
866 proc initConfVariantShortcut {envvar value validvallist intvallist} {
867 set value [parseEqualListConfValue variant_shortcut $envvar $value]
868
869 # ignore shortcut if not equal to one character or if set on alphanum char
870 # or on char with special meaning
871 foreach {vr sc} [split $value {:=}] {
872 if {[string length $sc] == 1 && ![string match {[a-zA-Z0-9+~/@=-,:]}\
873 $sc]} {
874 # remove duplicate shortcut or variant definition
875 if {[info exists ::g_variantShortcut($vr)]} {
876 unset ::g_shortcutVariant($::g_variantShortcut($vr))
877 }
878 if {[info exists ::g_shortcutVariant($sc)]} {
879 unset ::g_variantShortcut($::g_shortcutVariant($sc))
880 }
881 set ::g_variantShortcut($vr) $sc
882 set ::g_shortcutVariant($sc) $vr
883 }
884 }
885
886 # update value after above filtering step
887 set value {}
888 foreach vr [array names ::g_variantShortcut] {
889 if {[string length $value]} {
890 append value :
891 }
892 append value $vr=$::g_variantShortcut($vr)
893 }
894
895 return $value
896 }
897
898 # Is currently set verbosity level is equal or higher than level passed as arg
899 proc isVerbosityLevel {name} {
900 return [expr {[lsearch -exact [lindex $::g_config_defs(verbosity) 4]\
901 [getConf verbosity]] >= [lsearch -exact [lindex\
902 $::g_config_defs(verbosity) 4] $name]}]
903 }
904
905 # Is match performed in a case sensitive or insensitive manner
906 proc isIcase {} {
907 # depending on current sub-command, list values that equal to a case
908 # insensitive match enablement
909 lappend enabledValList always
910 if {[currentState commandname] in [list avail list whatis search paths\
911 savelist spider]} {
912 lappend enabledValList search
913 }
914 return [expr {[getConf icase] in $enabledValList}]
915 }
916
917 # Know if we are currently at the top evaluation level: (1) at the modulecmd
918 # level (module command written by user in terminal or script) or (2) during
919 # the evaluation of rc or modulefile by a source or autoinit sub-command
920 # triggered from modulecmd level or (3) during the evaluation of global rc
921 # file. (2) and (3) are considered "extended" top evaluation contexts.
922 proc isTopEvaluation {} {
923 return [expr {([depthState modulename] == 0 && [currentState eval_context]\
924 in {{} load unload swload swunload}) || ([depthState modulename] == 1\
925 && ([aboveCommandName] in {source autoinit} || [isStateDefined\
926 rc_running]))}]
927 }
928
929 proc commandAbortOnError {{command {}}} {
930 if {![string length $command]} {
931 set command [currentState commandname]
932 }
933 set abort_command_list [getConfList abort_on_error]
934 return [expr {[isTopEvaluation] && ![getState force] && $command in\
935 $abort_command_list}]
936 }
937
938 # Register a site-specific procedure to be called when given hook event
939 # occurs. Several procedures may be registered on the same event, they are
940 # then called in their registration order
941 proc add-hook {event proc_name} {
942 if {$event ni $::g_hookEvents} {
943 knerror "Unknown hook event '$event'"
944 }
945 lappend ::g_hooks($event) $proc_name
946 }
947
948 # Call every procedure registered on given hook event with provided
949 # arguments. An error raised by a hook procedure is reported but does not
950 # interrupt the other procedures registered on this event nor the
951 # modulefile or modulerc evaluation being wrapped
952 proc runHooks {event args} {
953 if {[info exists ::g_hooks($event)]} {
954 foreach hookproc $::g_hooks($event) {
955 if {[catch {$hookproc {*}$args} errMsg]} {
956 reportError "Hook procedure '$hookproc' registered on\
957 '$event' event failed\n[formatErrStackTrace $::errorInfo\
958 $hookproc {}]"
959 }
960 }
961 }
962 }
963
964 # ;;; Local Variables:
965 # ;;; Mode: tcl-mode
966 # ;;; tcl-indent-level: 3
967 # ;;; tcl-continued-indent-level: 3
968 # ;;; indent-tabs-mode: nil
969 # ;;; End:
970 # vim:set tabstop=3 shiftwidth=3 expandtab autoindent: