Debian Codegraph @

tcl/util.tcl

raw
1 ##########################################################################
2
3 # UTIL.TCL, utility procedures
4 # Copyright (C) 2002-2004 Mark Lakata
5 # Copyright (C) 2004-2017 Kent Mein
6 # Copyright (C) 2016-2026 Xavier Delaruelle
7 #
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 2 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20
21 ##########################################################################
22
23 proc charEscaped {str {charlist " \\\\\t{}\\\[\\\]|<>!;#^\$&*?\"'`()"}} {
24 return [regsub -all "\(\[$charlist\]\)" $str {\\\1}]
25 }
26
27 proc charUnescaped {str {charlist " \\\\\t{}\\\[\\\]|<>!;#^\$&*?\"'`()"}} {
28 return [regsub -all "\\\\\(\[$charlist\]\)" $str {\1}]
29 }
30
31 proc escapeGlobChars {str} {
32 return [charEscaped $str {*?[]\\}]
33 }
34
35 proc strTo {lang str {esc 1}} {
36 switch -- $lang {
37 tcl { set enco \{; set encc \}}
38 shell { set enco '; set encc '}
39 }
40 # escape all special characters
41 if {$esc} {
42 set str [charEscaped $str]
43 }
44 # enclose if empty or if contain a space character unless already escaped
45 if {$str eq {} || (!$esc && [regexp {\s} $str])} {
46 set str "$enco$str$encc"
47 }
48 return $str
49 }
50
51 proc listTo {lang lst {esc 1}} {
52 set lout [list]
53 # transform each list element
54 foreach str $lst {
55 lappend lout [strTo $lang $str $esc]
56 }
57 return [join $lout { }]
58 }
59
60 proc runEnvCommand {env_list cmd args} {
61 # set specific env
62 set saved_env_list {}
63 foreach {var val} $env_list {
64 lappend saved_env_list $var [get-env $var <unset>]
65 set ::env($var) $val
66 }
67
68 set res [runCommand $cmd {*}$args]
69
70 # restore env
71 foreach {var val} $saved_env_list {
72 if {$val eq {<unset>}} {
73 unset ::env($var)
74 } else {
75 set ::env($var) $val
76 }
77 }
78
79 return $res
80 }
81
82 # find command path and remember it
83 proc getCommandPath {cmd} {
84 return [lindex [auto_execok $cmd] 0]
85 }
86
87 # find then run command or raise error if command not found
88 proc runCommand {cmd args} {
89 set cmdpath [getCommandPath $cmd]
90 if {$cmdpath eq {}} {
91 knerror "Command '$cmd' cannot be found" MODULES_ERR_GLOBAL
92 } else {
93 return [exec $cmdpath {*}$args]
94 }
95 }
96
97 proc getAbsolutePath {path {from_cwd 0}} {
98 # currently executing a modulefile or rc, so get the directory of this file
99 # unless resolution from current working directory is requested
100 if {!$from_cwd && [currentState modulefile] ne {}} {
101 set curdir [file dirname [currentState modulefile]]
102 # elsewhere get module command current working directory
103 } else {
104 # register pwd at first call
105 if {![isStateDefined cwd]} {
106 # raise a global known error if cwd cannot be retrieved (especially
107 # when this directory has been removed)
108 if {[catch {setState cwd [pwd]} errorMsg]} {
109 knerror $errorMsg
110 }
111 }
112 set curdir [getState cwd]
113 }
114
115 # empty result if empty path
116 if {$path eq {}} {
117 set abspath {}
118 # consider path absolute if it starts with a variable ref
119 } elseif {[string index $path 0] eq {$}} {
120 set abspath $path
121 } else {
122 set abslist {}
123 # get a first version of the absolute path by joining the current
124 # working directory to the given path. if given path is already absolute
125 # 'file join' will not break it as $curdir will be ignored as soon a
126 # beginning '/' character is found on $path. this first pass also clean
127 # extra '/' character. then each element of the path is analyzed to
128 # clear "." and ".." components.
129 foreach elt [file split [file join $curdir $path]] {
130 if {$elt eq {..}} {
131 # skip ".." element if it comes after root element, remove last
132 # element elsewhere
133 if {[llength $abslist] > 1} {
134 set abslist [lreplace $abslist end end]
135 }
136 # skip any "." element
137 } elseif {$elt ne {.}} {
138 lappend abslist $elt
139 }
140 }
141 set abspath [file join {*}$abslist]
142 }
143
144 # return cleaned absolute path
145 return $abspath
146 }
147
148 # if no exact match found but icase mode is enabled then search if an icase
149 # match exists among all array key elements, select dictionary highest version
150 # if multiple icase matches are returned
151 proc getArrayKey {arrname name icase} {
152 if {$icase} {
153 upvar $arrname arr
154 if {![info exists arr($name)]} {
155 foreach elt [lsort -dictionary -decreasing [array names arr]] {
156 if {[string equal -nocase $name $elt]} {
157 reportDebug "key '$elt' in array '$arrname' matches '$name'"
158 set name $elt
159 break
160 }
161 }
162 }
163 }
164 return $name
165 }
166
167 # split string while ignore any separator character that is escaped
168 proc psplit {str sep} {
169 # use standard split if no sep character found
170 if {[string first \\$sep $str] == -1} {
171 set res [split $str $sep]
172 } else {
173 set previdx -1
174 set idx [string first $sep $str]
175 while {$idx != -1} {
176 # look ahead if found separator is escaped
177 if {[string index $str $idx-1] ne "\\"} {
178 # unescape any separator character when adding to list
179 lappend res [charUnescaped [string range $str $previdx+1 $idx-1]\
180 $sep]
181 set previdx $idx
182 }
183 set idx [string first $sep $str $idx+1]
184 }
185
186 lappend res [charUnescaped [string range $str $previdx+1 end] $sep]
187 }
188
189 return $res
190 }
191
192 # join list while escape any character equal to separator
193 proc pjoin {lst sep} {
194 # use standard join if no sep character found
195 if {[string first $sep $lst] == -1} {
196 set res [join $lst $sep]
197 } else {
198 set res {}
199 foreach elt $lst {
200 # preserve empty entries
201 if {[info exists not_first]} {
202 append res $sep
203 } else {
204 set not_first 1
205 }
206 # escape any separator character when adding to string
207 append res [charEscaped $elt $sep]
208 }
209 }
210
211 return $res
212 }
213
214 # Is provided string a version number: consider first element of string if
215 # '.' character used in it. [0-9af] on this first part is considered valid
216 # anything else could be used in latter elements
217 proc isVersion {str} {
218 return [string is xdigit -strict [lindex [split $str .] 0]]
219 }
220
221 # Return number of occurrences of passed character in passed string
222 proc countChar {str char} {
223 return [expr {[string length $str] - [string length [string map [list\
224 $char {}] $str]]}]
225 }
226
227 proc lappendNoDup {lstname args} {
228 set ret 0
229 upvar $lstname lst
230 foreach elt $args {
231 if {![info exists lst] || $elt ni $lst} {
232 lappend lst $elt
233 set ret 1
234 }
235 }
236 return $ret
237 }
238
239 proc replaceFromList {list1 item args} {
240 set xi 0
241 while {[set xi [lsearch -exact -start $xi $list1 $item]] != -1} {
242 set list1 [lreplace $list1 $xi $xi {*}$args]
243 }
244 return $list1
245 }
246
247 proc lrem {lst_name item} {
248 upvar $lst_name lst
249 set lst [lsearch -inline -all -not -exact $lst $item]
250 }
251
252 # make lprepend rely on ledit if this command exists (Tcl 9+)
253 if {[string length [info commands ledit]]} {
254 proc lprepend {lst_name args} {
255 upvar $lst_name lst
256 if {[info exists lst]} {
257 ##nagelfar ignore
258 ledit lst -1 -1 {*}$args
259 } else {
260 set lst $args
261 }
262 }
263 } else {
264 proc lprepend {lst_name args} {
265 upvar $lst_name lst
266 if {[info exists lst]} {
267 set lst [list {*}$args {*}$lst]
268 } else {
269 set lst $args
270 }
271 }
272 }
273
274 # provide a lpop proc if this command does not exist (Tcl <9)
275 # this proc only supports removing first or last item from list
276 if {![string length [info commands lpop]]} {
277 ##nagelfar ignore Procedure
278 proc lpop {lst_name {idx end}} {
279 upvar $lst_name lst
280 ##nagelfar ignore Badly formed if statement
281 lassign [if {$idx eq {end}} {list 0 end-1} {list 1 end}] first last
282 set lst [lrange $lst $first $last]
283 }
284 }
285
286 # test if 2 lists have at least one element in common
287 proc isIntBetweenList {list1 list2} {
288 foreach elt $list1 {
289 if {$elt in $list2} {
290 return 1
291 }
292 }
293 return 0
294 }
295
296 # test if 2 lists have at least one element in diff
297 proc isDiffBetweenList {list1 list2} {
298 foreach elt $list1 {
299 if {$elt ni $list2} {
300 return 1
301 }
302 }
303 return 0
304 }
305
306 # returns elements from list1 not part of list2 and elements from list2 not
307 # part of list1
308 proc getDiffBetweenList {list1 list2} {
309 set res1 [list]
310 set res2 [list]
311
312 foreach elt $list1 {
313 if {$elt ni $list2} {
314 lappend res1 $elt
315 }
316 }
317 foreach elt $list2 {
318 if {$elt ni $list1} {
319 lappend res2 $elt
320 }
321 }
322
323 return [list $res1 $res2]
324 }
325
326 # returns if at least one element in list is present several times
327 proc isDupInList {arg_list} {
328 ##nagelfar ignore #2 Unknown variable
329 lappendNoDup uniq_list {*}$arg_list
330 return [expr {[llength $arg_list] != [llength $uniq_list]}]
331 }
332
333 # return intersection of all lists: elements present in every list
334 proc getIntersectBetweenList {args} {
335 foreach lst $args {
336 if {![info exists res]} {
337 set cur_res $lst
338 } else {
339 set cur_res [list]
340 foreach elt $res {
341 if {$elt in $lst} {
342 lappend cur_res $elt
343 }
344 }
345 }
346 set res $cur_res
347 # stop when intersection result becomes empty
348 if {![llength $res]} {
349 break
350 }
351 }
352 return $res
353 }
354
355 # return elements from arr1 not in arr2, elements from arr1 in arr2 but with a
356 # different value and elements from arr2 not in arr1.
357 # if notset_equals_empty is enabled, not-set element in array is equivalent to
358 # element set to an empty value.
359 # if unordered_lists_compared is enabled, value of array element is considered
360 # a list and difference between list entries is made (order insensitive)
361 proc getDiffBetweenArray {arrname1 arrname2 {notset_equals_empty 0}\
362 {unordered_lists_compared 0}} {
363 upvar $arrname1 arr1
364 upvar $arrname2 arr2
365 set notin2 [list]
366 set diff [list]
367 set notin1 [list]
368
369 foreach name [array names arr1] {
370 # element in arr1 not in arr2
371 if {![info exists arr2($name)]} {
372 if {!$notset_equals_empty} {
373 lappend notin2 $name
374 # if we consider a not-set entry equal to an empty value, there is a
375 # difference only if entry in the other array is not empty
376 } elseif {$arr1($name) ne {}} {
377 lappend diff $name
378 }
379 # element present in both arrays but with a different value
380 } elseif {!$unordered_lists_compared} {
381 # but with a different value
382 if {$arr1($name) ne $arr2($name)} {
383 lappend diff $name
384 }
385 } else {
386 # with a different value, not considering order
387 lassign [getDiffBetweenList $arr1($name) $arr2($name)] notin2 notin1
388 if {[llength $notin2] || [llength $notin1]} {
389 lappend diff $name
390 }
391 }
392 }
393
394 foreach name [array names arr2] {
395 # element in arr2 not in arr1
396 if {![info exists arr1($name)]} {
397 if {!$notset_equals_empty} {
398 lappend notin1 $name
399 } elseif {$arr2($name) ne {}} {
400 lappend diff $name
401 }
402 }
403 }
404
405 return [list $notin2 $diff $notin1]
406 }
407
408 proc getCallingProcName {} {
409 if {[info level] > 2} {
410 return [lindex [info level -2] 0]
411 }
412 }
413
414 proc replaceFirstInStr {str old new} {
415 set start_idx [string first $old $str]
416 if {$start_idx == -1} {
417 return $str
418 }
419 set end_idx [expr {$start_idx + [string length $old] - 1}]
420 return [string replace $str $start_idx $end_idx $new]
421 }
422
423 # ;;; Local Variables:
424 # ;;; Mode: tcl-mode
425 # ;;; tcl-indent-level: 3
426 # ;;; tcl-continued-indent-level: 3
427 # ;;; indent-tabs-mode: nil
428 # ;;; End:
429 # vim:set tabstop=3 shiftwidth=3 expandtab autoindent: