Hog v10.58.0
Logger.tcl
Go to the documentation of this file.
1 # Copyright 2018-2026 The University of Birmingham
2 # Copyright 2018-2026 Max-Planck-Institute for Physics
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 
16 # @file Logger.tcl
17 # Logger functions for the Hog project
18 
19 
20 set DEBUG_MODE 0
21 
22 proc setDebugMode {mode} {
23  global DEBUG_MODE
24  set DEBUG_MODE $mode
25 }
26 
27 proc getDebugMode {} {
28  global DEBUG_MODE
29  return $DEBUG_MODE
30 }
31 
32 proc printDebugMode {} {
33  global DEBUG_MODE
34  if {$DEBUG_MODE} {
35  Msg Info "DEBUG_MODE is set to $DEBUG_MODE"
36  } else {
37  Msg Info "DEBUG_MODE is not set or is 0"
38  }
39 }
40 
41 ## @brief Safely get a value from a dictionary
42 #
43 # @param[in] d The dictionary to search
44 # @param[in] args The keys to look for
45 proc dictSafeGet {d args} {
46  if {[dict exists $d {*}$args]} {
47  return [dict get $d {*}$args]
48  } else {
49  return ""
50  }
51 }
52 
53 #### DESKTOP NOTIFICATIONS
54 
55 # Absolute path of the Hog images folder, resolved once when this file is
56 # sourced. The procedures below may be called from any working directory, so
57 # the path cannot be recomputed from [info script] at call time.
58 set HogImagesPath [file normalize [file join [file dirname [info script]] .. .. images]]
59 
60 # Reentrancy guard. Msg notifies on errors, so Notify must never be able to
61 # call back into Msg in a way that would trigger a second notification.
62 set NotifyInProgress 0
63 
64 ## @brief Check if desktop notifications have been enabled by the user
65 #
66 # Notifications are opt-in and controlled by the HOG_NOTIFY environment
67 # variable, which may be set to 1, true, yes, on or enabled.
68 #
69 # @returns 1 if notifications are enabled, 0 otherwise
70 #
71 proc NotifyEnabled {} {
72  if {![info exists ::env(HOG_NOTIFY)]} {
73  return 0
74  }
75  set value [string tolower [string trim $::env(HOG_NOTIFY)]]
76  return [expr {[lsearch -exact {1 true yes on enabled} $value] >= 0}]
77 }
78 
79 ## @brief Map a Hog severity level onto a notification urgency
80 #
81 # @param[in] level The name of the severity level, as passed to Msg
82 #
83 # @returns one of "low", "normal" or "critical"
84 #
85 proc NotifyUrgency {level} {
86  set level [string tolower $level]
87  # Nothing is wrong: status, info and debug
88  if {$level == "status" || $level == "extra_info" || $level == "info" || $level == "debug"} {
89  return "low"
90  } elseif {$level == "error"} {
91  # An error is the only level that stops the build, and most desktops never
92  # auto dismiss a "critical" notification, so it is the only one that gets it
93  return "critical"
94  }
95  # Warnings and critical warnings, and anything unrecognised: worth a look,
96  # but the build is still alive
97  return "normal"
98 }
99 
100 ## @brief Send a desktop notification on Linux through the notify-send helper
101 #
102 # Notifications are opt-in: nothing is sent unless the HOG_NOTIFY environment
103 # variable is enabled, see NotifyEnabled.
104 #
105 # the helper is run detached and silenced: a notification that cannot be delivered,
106 # for example over ssh or with no notification daemon running, is dropped
107 # without interrupting the build.
108 #
109 # @param[in] level The severity level, in any of the forms accepted by Msg
110 # @param[in] message The body of the notification
111 # @param[in] title The title of the notification (default "Hog <level>")
112 #
113 proc Notify {level message {title ""}} {
114  global NotifyInProgress
115 
116  if {![NotifyEnabled] || $NotifyInProgress} {
117  return
118  }
119 
120  if {$title == ""} {
121  set title "Hog [string toupper $level]"
122  }
123 
124  set NotifyInProgress 1
125  set status [catch {
126  if {[auto_execok notify-send] == ""} {
127  Msg Debug "notify-send was not found, skipping notification"
128  } else {
129  set cmd [list notify-send --app-name=Hog --urgency=[NotifyUrgency $level]]
130  set icon [file join $::HogImagesPath hog.png]
131  if {[file exists $icon]} {
132  lappend cmd --icon=$icon
133  }
134  # "--" protects titles and messages that begin with a dash
135  lappend cmd -- $title $message
136  # Vivado and Quartus ship their own glib and put it on LD_LIBRARY_PATH,
137  # Drop it inside an IDE, the same workaround GetCurl uses for curl.
138  if {[info procs IsTclsh] != "" && ![IsTclsh]} {
139  set cmd [linsert $cmd 0 env -u LD_LIBRARY_PATH]
140  }
141  exec {*}$cmd < /dev/null > /dev/null 2> /dev/null &
142  }
143  } err]
144  set NotifyInProgress 0
145 
146  # Reporting the failure must not become a failure of its own
147  if {$status} {
148  catch {Msg Debug "Could not send notification: $err"}
149  }
150 }
151 
152 ## @brief The Hog Printout Msg function
153 #
154 # @param[in] level The severity level (status, info, warning, critical, error, debug)
155 # @param[in] msg The message to print
156 # @param[in] title The title string to be included in the header of the message [Hog:$title] (default "")
157 proc Msg {level fmsg {title ""}} {
158  # foreach msg [split $fmsg "\n"] {
159  set msg $fmsg
160  set level [string tolower $level]
161  if {$title == ""} {set title [lindex [info level [expr {[info level] - 1}]] 0]}
162  if {$level == 0 || $level == "status" || $level == "extra_info"} {
163  set vlevel {STATUS}
164  set qlevel info
165  } elseif {$level == 1 || $level == "info"} {
166  set vlevel {INFO}
167  set qlevel info
168  } elseif {$level == 2 || $level == "warning"} {
169  set vlevel {WARNING}
170  set qlevel warning
171  } elseif {$level == 3 || [string first "critical" $level] != -1} {
172  set vlevel {CRITICAL WARNING}
173  set qlevel critical_warning
174  } elseif {$level == 4 || $level == "error"} {
175  set vlevel {ERROR}
176  set qlevel error
177  } elseif {$level == 5 || $level == "debug"} {
178  if {([info exists ::DEBUG_MODE] && $::DEBUG_MODE == 1) || (
179  [info exists ::env(HOG_DEBUG_MODE)] && $::env(HOG_DEBUG_MODE) == 1
180  )} {
181  set vlevel {STATUS}
182  set qlevel extra_info
183  set msg "DEBUG: \[Hog:$title\] $msg"
184  } else {
185  return
186  }
187  } else {
188  puts "Hog Error: level $level not defined"
189  exit -1
190  }
191  # Every branch below exits on an error, so notify the desktop while we still can
192  if {$qlevel == "error"} {
193  Notify $level $msg "Hog $vlevel"
194  }
195  if {[IsXilinx]} {
196  # Vivado
197  if {[string match "-*" $msg]} {
198  set msg " $msg"
199  }
200  set status [catch {send_msg_id Hog:$title-0 $vlevel "$msg"}]
201  if {$status != 0} {
202  exit $status
203  }
204  } elseif {[IsQuartus]} {
205  # Quartus
206  post_message -type $qlevel "Hog:$title $msg"
207  if {$qlevel == "error"} {
208  exit 1
209  }
210  } else {
211  # Tcl Shell / Libero
212  if {[info exists ::HOG_API_MODE] && $::HOG_API_MODE} {
213  if {$qlevel == "error"} {
214  puts "\{\"error\": \"$msg\"\}"
215  exit 1
216  }
217  return
218  }
219  if {$vlevel != "STATUS"} {
220  puts "$vlevel: \[Hog:$title\] $msg"
221  } else {
222  # temporary solution to avoid removing of leading
223  set HogEnvDict [Hog::LoggerLib::GetTOMLDict]
224  puts "$msg"
225  }
226  if {$qlevel == "error"} {
227  exit 1
228  }
229  }
230  # }
231 }
232 
233 ## @brief Prints a message with selected severity and optionally write into a log file
234 #
235 # @param[in] msg The message to print
236 # @param[in] severity The severity of the message
237 # @param[in] outFile The path of the output logfile
238 #
239 proc MsgAndLog {msg {severity "CriticalWarning"} {outFile ""}} {
240  Msg $severity $msg
241  if {$outFile != ""} {
242  set directory [file dir $outFile]
243  if {![file exists $directory]} {
244  Msg Info "Creating $directory..."
245  file mkdir $directory
246  }
247 
248  set oF [open "$outFile" a+]
249  puts $oF $msg
250  close $oF
251  }
252 }
253 
254 
255 # @brief Print the Hog Logo
256 #
257 # @param[in] repo_path The main path of the git repository (default .)
258 proc Logo {{repo_path .}} {
259  # Msg Warning "HOG_LOGO_PRINTED : $HOG_LOGO_PRINTED"
260  if {![info exists ::env(HOG_LOGO_PRINTED)] || $::env(HOG_LOGO_PRINTED) eq "0"} {
261  if {
262  [info exists ::env(HOG_COLOR)] && ([string match "ENABLED" $::env(HOG_COLOR)] || [string is integer -strict $::env(HOG_COLOR)] && $::env(HOG_COLOR) > 0)
263  } {
264  set logo_file "$repo_path/Hog/images/hog_logo_color.txt"
265  } else {
266  set logo_file "$repo_path/Hog/images/hog_logo.txt"
267  }
268 
269  cd $repo_path/Hog
270  set ver [Git {describe --always}]
271  set old_path [pwd]
272  # set ver [Git {describe --always}]
273 
274  if {[file exists $logo_file]} {
275  set f [open $logo_file "r"]
276  set data [read $f]
277  close $f
278  set lines [split $data "\n"]
279  foreach l $lines {
280  if {[regexp {(Version:)[ ]+} $l -> prefix]} {
281  set string_len [string length $l]
282 
283  set version_string "* Version: $ver"
284  set version_len [string length $version_string]
285  append version_string [string repeat " " [expr {$string_len - $version_len - 1}]] "*"
286  set l $version_string
287  }
288  Msg Status $l
289  }
290  } {
291  Msg CriticalWarning "Logo file: $logo_file not found"
292  }
293 
294  Msg Status ""
295  Msg Status " ★ Like Hog? Star us on GitLab: https://gitlab.com/hog-cern/Hog | GitHub: https://github.com/hog-cern/Hog"
296  Msg Status ""
297 
298  # Msg Status "Version: $ver"
299  cd $old_path
300  }
301 }
302 
303 # Define the procedure to print the content of a file
304 #
305 # @param[in] filename The name of the file to read and print
306 #
307 # @brief This procedure opens the file, reads its content, and prints it to the console.
308 proc PrintFileContent {filename} {
309  # Open the file for reading
310  set file [open $filename r]
311 
312  # Read the content of the file
313  set content [read $file]
314 
315  # Close the file
316  close $file
317 
318  # Print the content of the file
319  puts $content
320 }
321 
322 
323 
324 ## Print a tree-like structure of Hog list file content
325 #
326 # @param[in] data the list of lines read from a list file
327 # @param[in] repo_path the path of the repository
328 # @param[in] indentation a string containing a number of spaces to indent the tree
329 proc PrintFileTree {{data} {repo_path} {indentation ""}} {
330  # Msg Debug "PrintFileTree called with data: $data, repo_path: $repo_path, indentation: $indentation"
331  set print_list {}
332  set last_printed ""
333  foreach line $data {
334  if {![regexp {^[\t\s]*$} $line] & ![regexp {^[\t\s]*\#} $line]} {
335  lappend print_list "$line"
336  }
337  }
338  set i 0
339 
340  foreach p $print_list {
341  incr i
342  if {$i == [llength $print_list]} {
343  set pad "└──"
344  } else {
345  set pad "├──"
346  }
347  set file_name [lindex [split $p] 0]
348  if {[file exists [file normalize [lindex [glob -nocomplain $repo_path/$file_name] 0]]]} {
349  set exists ""
350  } else {
351  set exists " !!!!! NOT FOUND !!!!!"
352  }
353 
354  Msg Status "$indentation$pad$p$exists"
355  set last_printed $file_name
356  }
357 
358  return $last_printed
359 }
360 
361 
362 
363 
364 namespace eval Hog::LoggerLib {
365 
366  variable toml_dict {}
367  variable fullPath
368 
369  ## @brief gets the full path to the file in the user home folder
370  #
371  # @param[in] filename The name of the file to get the path for
372  #
373  # @returns The full path to the file in the user's home directory, or 0 if file doesn't exist
374  #
375  proc GetUserFilePath {filename} {
376  set homeDir [file normalize ~]
377  set fullPath [file join $homeDir $filename]
378  if {[file exists $fullPath]} {
379  return $fullPath
380  } else {
381  return 0
382  }
383  }
384 
385 
386  ## @brief Parse a TOML format file and return the data as a dictionary
387  #
388  # @param[in] toml_file The path to the TOML file to parse
389  #
390  # @returns A nested dictionary containing the TOML data, or -1 in case of failure
391  #
392  proc ParseTOML {toml_file} {
393  variable toml_dict
394 
395  # set toml_dict [dict create \
396  # terminal [dict create logger 0 colored 0] \
397  # verbose [dict create level 4 pidshow 0 linecounter 0 msgtypeCounter 0] \
398  # ]
399  if {![file exists $toml_file]} {
400  Msg Warning "TOML file $toml_file does not exist"
401  return -1
402  }
403  if {[catch {open $toml_file r} file_handle]} {
404  Msg Error "Cannot open TOML file $toml_file: $file_handle"
405  return -1
406  }
407  # set toml_dict [dict create]
408  set current_section ""
409  set line_number 0
410  set in_multiline_string 0
411  set multiline_buffer ""
412  set multiline_key ""
413  while {[gets $file_handle line] >= 0} {
414  incr line_number
415  # Handle multiline strings
416  if {$in_multiline_string} {
417  if {[string match "*\"\"\"*" $line]} {
418  # End of multiline string
419  set end_pos [string first "\"\"\"" $line]
420  append multiline_buffer [string range $line 0 [expr $end_pos - 1]]
421  if {$current_section eq ""} {
422  dict set toml_dict $multiline_key $multiline_buffer
423  } else {
424  dict set toml_dict $current_section $multiline_key $multiline_buffer
425  }
426  set in_multiline_string 0
427  set multiline_buffer ""
428  set multiline_key ""
429  } else {
430  append multiline_buffer $line "\n"
431  }
432  continue
433  }
434  # Remove comments (but preserve # inside strings)
435  set clean_line ""
436  set in_quotes 0
437  set quote_char ""
438  for {set i 0} {$i < [string length $line]} {incr i} {
439  set char [string index $line $i]
440  if {!$in_quotes && ($char eq "\"" || $char eq "'")} {
441  set in_quotes 1
442  set quote_char $char
443  append clean_line $char
444  } elseif {$in_quotes && $char eq $quote_char} {
445  set in_quotes 0
446  set quote_char ""
447  append clean_line $char
448  } elseif {!$in_quotes && $char eq "#"} {
449  break
450  } else {
451  append clean_line $char
452  }
453  }
454  set line [string trim $clean_line]
455  # Skip empty lines
456  if {$line eq ""} {
457  continue
458  }
459  # Handle section headers [section] or [section.subsection]
460  if {[regexp {^\[([^\]]+)\]$} $line match section_name]} {
461  set current_section $section_name
462  # Initialize section if it doesn't exist
463  if {![dict exists $toml_dict $current_section]} {
464  dict set toml_dict $current_section [dict create]
465  }
466  continue
467  }
468  # Handle key-value pairs
469  if {[regexp {^([^=]+)=(.*)$} $line match raw_key raw_value]} {
470  set key [string trim $raw_key]
471  set value [string trim $raw_value]
472  # Handle multiline strings
473  if {[string match "*\"\"\"*" $value] && ![string match "*\"\"\"*\"\"\"*" $value]} {
474  set start_pos [string first "\"\"\"" $value]
475  set multiline_key $key
476  set multiline_buffer [string range $value [expr $start_pos + 3] end]
477  append multiline_buffer "\n"
478  set in_multiline_string 1
479  continue
480  }
481  # Parse the value
482  set parsed_value [ParseTOMLValue $value]
483  # Handle arrays and nested keys
484  if {[string match "*.*" $key]} {
485  set key_parts [split $key "."]
486  set dict_ref toml_dict
487  if {$current_section ne ""} {
488  lappend dict_ref $current_section
489  }
490  for {set i 0} {$i < [expr [llength $key_parts] - 1]} {incr i} {
491  set part [lindex $key_parts $i]
492  lappend dict_ref $part
493  if {![dict exists {*}$dict_ref]} {
494  dict set {*}$dict_ref [dict create]
495  }
496  }
497  set final_key [lindex $key_parts end]
498  lappend dict_ref $final_key
499  dict set {*}$dict_ref $parsed_value
500  } else {
501  # Simple key
502  if {$current_section eq ""} {
503  dict set toml_dict $key $parsed_value
504  } else {
505  dict set toml_dict $current_section $key $parsed_value
506  }
507  }
508  }
509  }
510  close $file_handle
511  return $toml_dict
512  }
513 
514  ## @brief Parse a TOML value and convert it to appropriate TCL type
515  #
516  # @param[in] value The raw value string from TOML
517  #
518  # @returns The parsed value in appropriate TCL format
519  #
520  proc ParseTOMLValue {value} {
521  set value [string trim $value]
522  # Handle boolean values
523  if {$value eq "true"} {
524  return 1
525  } elseif {$value eq "false"} {
526  return 0
527  }
528  # Handle strings (quoted)
529  if {[regexp {^"(.*)"$} $value match string_content]} {
530  # Handle escape sequences
531  set string_content [string map {\\" \" \\\\ \\ \\n \n \\t \t \\r \r} $string_content]
532  return $string_content
533  } elseif {[regexp {^'(.*)'$} $value match string_content]} {
534  # Single quoted strings (literal)
535  return $string_content
536  }
537  # Handle arrays
538  if {[string match {\[*\]} $value]} {
539  set array_content [string range $value 1 end-1]
540  set array_content [string trim $array_content]
541  if {$array_content eq ""} {
542  return [list]
543  }
544  set elements [list]
545  set current_element ""
546  set bracket_depth 0
547  set in_quotes 0
548  set quote_char ""
549  for {set i 0} {$i < [string length $array_content]} {incr i} {
550  set char [string index $array_content $i]
551  if {!$in_quotes && ($char eq "\"" || $char eq "'")} {
552  set in_quotes 1
553  set quote_char $char
554  append current_element $char
555  } elseif {$in_quotes && $char eq $quote_char} {
556  set in_quotes 0
557  set quote_char ""
558  append current_element $char
559  } elseif {!$in_quotes && $char eq "\["} {
560  incr bracket_depth
561  append current_element $char
562  } elseif {!$in_quotes && $char eq "\]"} {
563  incr bracket_depth -1
564  append current_element $char
565  } elseif {!$in_quotes && $char eq "," && $bracket_depth == 0} {
566  lappend elements [ParseTOMLValue [string trim $current_element]]
567  set current_element ""
568  } else {
569  append current_element $char
570  }
571  }
572  if {$current_element ne ""} {
573  lappend elements [ParseTOMLValue [string trim $current_element]]
574  }
575  return $elements
576  }
577  # Handle numbers (integers and floats)
578  if {[string is integer $value]} {
579  return [expr {int($value)}]
580  } elseif {[string is double $value]} {
581  return [expr {double($value)}]
582  }
583  # Handle dates/times as strings for now
584  if {[regexp {^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}} $value]} {
585  return $value
586  }
587  # Return as string if nothing else matches
588  return $value
589  }
590 
591  ## @brief Get a value from a TOML dictionary using dot notation
592  #
593  # @param[in] toml_dict The dictionary returned by ParseTOML
594  # @param[in] key_path The key path in dot notation (e.g., "section.subsection.key")
595  #
596  # @returns The value if found, or empty string if not found
597  #
598  proc GetTOMLValue {toml_dict key_path} {
599  set key_parts [split $key_path "."]
600  set current_dict $toml_dict
601  foreach part $key_parts {
602  if {[dict exists $current_dict $part]} {
603  set current_dict [dict get $current_dict $part]
604  } else {
605  return ""
606  }
607  }
608  return $current_dict
609  }
610 
611  ## @brief Print a TOML dictionary in a readable format
612  #
613  # @param[in] toml_dict The dictionary to print
614  # @param[in] indent Internal parameter for indentation (default: 0)
615  #
616  proc PrintTOMLDict {toml_dict {indent 0}} {
617  set indent_str [string repeat " " $indent]
618  dict for {key value} $toml_dict {
619  if {[string is list $value] && [llength $value] > 1 && [string is list [lindex $value 0]]} {
620  # This is likely a nested dictionary
621  Msg Debug "${indent_str}${key}:"
622  if {[catch {dict for {subkey subvalue} $value {}} result]} {
623  # Not a dictionary, print as value
624  Msg Debug "${indent_str} $value"
625  } else {
626  PrintTOMLDict $value [expr {$indent + 1}]
627  }
628  } elseif {[string is list $value] && [llength $value] > 0} {
629  # This is an array
630  Msg Debug "${indent_str}${key}: \[list of [llength $value] items\]"
631  foreach item $value {
632  Msg Debug "${indent_str} - $item"
633  }
634  } else {
635  Msg Debug "${indent_str}${key}: $value"
636  }
637  }
638  }
639 
640  ## @brief Access the dictionary of the parsed TOML file
641  #
642  # @returns The dictionary containing the parsed TOML data
643  proc GetTOMLDict {} {
644  variable toml_dict
645  if {[info exists toml_dict]} {
646  return $toml_dict
647  }
648  }
649 
650 
651 
652 }
653 
654