Hog v10.58.0
tools.tcl
Go to the documentation of this file.
1 
2 namespace eval Tools {
3 
4  # Register bare tool command
6  description "Every registered tool. Usage: <tool>"
7  aliases tools
8  }
9 
10  # Manifest fields - identity/metadata only.
11  variable _fields {
12  { name "" required}
13  { ref_name "" optional}
14  { vendor "" optional}
15  { description "" optional}
16  { version "" optional}
17  { features {} optional}
18  { custom 0 optional}
19  { _source_path "" optional}
20  { _git {} optional}
21  }
22 
23  proc _validate_manifest {tool_name raw_dict} {
24  variable _fields
25  set norm [dict create]
26  dict for {k v} $raw_dict { dict set norm [string tolower $k] $v }
27  set raw_dict $norm
28  set result [dict create]
29  foreach field $_fields {
30  lassign $field fname fdefault frequired
31  if {[dict exists $raw_dict $fname]} {
32  dict set result $fname [dict get $raw_dict $fname]
33  } elseif {$frequired eq "required"} {
34  error "Tool '$tool_name': missing required field '$fname'"
35  } else {
36  dict set result $fname $fdefault
37  }
38  }
39  return $result
40  }
41 
42  # The booting parent stamps HOG_ACTIVE_TOOL before exec'ing an IDE child, so a
43  # fresh process just reads its identity instead of trying to figure it out.
44  # In-process tools never reach here - their Launch calls ActiveTool::Set direct.
45  proc detectActiveTool {} {
46  if {![info exists ::env(HOG_ACTIVE_TOOL)] || $::env(HOG_ACTIVE_TOOL) eq ""} { return "" }
47  return [ResolveAlias $::env(HOG_ACTIVE_TOOL)]
48  }
49 
50  proc PrintTools {} {
51  puts "=================================================="
52  puts " Loaded Tools"
53  puts "=================================================="
54  set tools [namespace children ::Tools]
55  if {[llength $tools] == 0} {
56  puts " (none)"
57  } else {
58  foreach ns $tools {
59  ${ns}::_printTool
60  }
61  }
62  puts "=================================================="
63  }
64 
65 
66  # Throws on failure (errorcode {HOG_TOOL_FAILED <exit>}) so a failed IDE child
67  # can't surface as a success. The top-level entry maps that code to its own
68  # exit status - see launch.tcl.
69  proc Launch {tool} {
70  set tool_ns [ResolveAlias $tool]
71  if {$tool_ns eq "" || [info commands ${tool_ns}::Launch] eq ""} {
72  return -code error -errorcode {HOG_TOOL_FAILED 1} \
73  "Tool '$tool' not found or has no Launch proc"
74  }
75  # Stamp identity for any IDE child this Launch execs; restore so a nested
76  # boot can't leave the parent mislabeled.
77  set _had [info exists ::env(HOG_ACTIVE_TOOL)]
78  set _prev [expr {$_had ? $::env(HOG_ACTIVE_TOOL) : ""}]
79  set ::env(HOG_ACTIVE_TOOL) [string tolower [namespace tail $tool_ns]]
80  set _code [catch {${tool_ns}::Launch} result _opts]
81  if {$_had} { set ::env(HOG_ACTIVE_TOOL) $_prev } else { unset ::env(HOG_ACTIVE_TOOL) }
82  if {$_code} {
83  # A non-zero IDE child makes exec throw with -errorcode
84  # {CHILDSTATUS <pid> <exit>}; carry that exit code up rather than
85  # flattening every failure to 1.
86  set _child 1
87  if {[dict exists $_opts -errorcode]} {
88  set _ec [dict get $_opts -errorcode]
89  if {[lindex $_ec 0] eq "CHILDSTATUS" && [llength $_ec] >= 3} {
90  set _child [lindex $_ec 2]
91  }
92  }
93  return -code error -errorcode [list HOG_TOOL_FAILED $_child] \
94  "Tool '$tool' failed (exit $_child): $result"
95  }
96  return $result
97  }
98 
99  proc ResolveAlias {alias} {
100  if {$alias eq ""} { return "" }
101  if {[string first "::" $alias] >= 0} {
102  return [expr {[namespace exists $alias] ? $alias : ""}]
103  }
104  set needle [string tolower $alias]
105  foreach ns [namespace children ::Tools] {
106  if {[string tolower [namespace tail $ns]] eq $needle} { return $ns }
107  if {[catch {set m [${ns}::GetManifest]} err]} { continue }
108  if {[dict exists $m ref_name]} {
109  foreach iname [dict get $m ref_name] {
110  if {[string tolower $iname] eq $needle} { return $ns }
111  }
112  }
113  }
114  return ""
115  }
116 
117  # Register tools from a directory
118  # looks for ./<tool>/<tool>.tcl or ./<tool>/main.tcl
119  # Pass -custom to mark every tool sourced from this dir as user-defined.
120  # Each file self-registers via RegisterTool
121  proc RegisterFromDir {dir args} {
122  Msg Debug "Loading tools from $dir"
123  if {![file isdirectory $dir]} { return }
124  set is_custom [expr {"-custom" in $args}]
125  foreach sub [lsort [glob -nocomplain -type d -directory $dir *]] {
126  set tool_name [file tail $sub]
127  set entry [file join $sub "$tool_name.tcl"]
128  if {![file exists $entry]} {
129  set entry [file join $sub "main.tcl"]
130  }
131  if {![file exists $entry]} {
132  Msg Warning "Tool directory '$tool_name' has no '$tool_name.tcl' or 'main.tcl', skipping"
133  continue
134  }
135  Hog::SourceFile $entry $is_custom "tool '$tool_name'"
136  }
137  }
138 
139  # Git commit/tag info for whatever entry file a tool was sourced from.
140  proc _gitInfoFor {entry} {
141  set git_info { commit "unknown" date "unknown" ver "unknown" }
142  if {$entry eq ""} { return $git_info }
143  set cwd [pwd]
144  cd [file dirname $entry]
145  set git_ret [GitRet [list log -n 1 --decorate "--format=commit {%h} tag {%d} date {%ad}" --date=short] .]
146  cd $cwd
147 
148  if {[lindex $git_ret 0] == 0 && [llength [lindex $git_ret 1]] > 0} {
149  set git_info [lindex $git_ret 1]
150  set _hog_tag ""
151  set _ver_tag ""
152  foreach t [split [dict get $git_info tag] ","] {
153  set t [string trim $t " \t()"]
154  if {$_hog_tag eq "" && [regexp {^tag:\s+(Hog\d{4}\.\d+(?:\.\d+)*)$} $t -> _found]} {
155  set _hog_tag $_found
156  } elseif {$_ver_tag eq "" && [regexp {^tag:\s+(v\d+(?:\.\d+)+)$} $t -> _found]} {
157  set _ver_tag $_found
158  }
159  }
160  if {$_hog_tag ne ""} { dict set git_info ver $_hog_tag } \
161  elseif {$_ver_tag ne ""} { dict set git_info ver $_ver_tag } \
162  else { dict set git_info ver "unknown" }
163  }
164  return $git_info
165  }
166 
167  # Registers the tool namespace calling this
168  # creates a command group for the tool,
169  # injects RegisterCommand/RegisterFlow/RegisterStage
170  proc RegisterTool {ns manifest_dict} {
171  set tool_name [namespace tail $ns]
172  if {[catch {_validate_manifest $tool_name $manifest_dict} validated]} {
173  Msg Warning "Skipping tool '$tool_name': $validated"
174  return
175  }
176  set is_custom [set ::Hog::_loading_custom]
177  dict set validated custom $is_custom
178  dict set validated _source_path [set ::Hog::_loading_source]
179  dict set validated _git [_gitInfoFor [set ::Hog::_loading_source]]
180 
181  namespace eval $ns [list variable Manifest $validated]
183 
184  set tool_key [string toupper $tool_name]
185  set tool_canon "TOOL.$tool_key"
186  set ref_aliases [expr {[dict exists $validated ref_name] ? [dict get $validated ref_name] : {}}]
187 
188  Commands::RegisterCommand $tool_canon [dict create \
189  description [dict get $validated description] \
190  aliases $ref_aliases \
191  ] {*}[expr {$is_custom ? "-custom" : ""}] -source [set ::Hog::_loading_source]
192 
193  Commands::AddAlias $tool_key $tool_canon
194  foreach a $ref_aliases { Commands::AddAlias $a $tool_canon }
195  }
196 
197  # Register Stage to tool's command tree, registered under TOOL.<TOOL>.STAGE
198  #
199  # RegisterStage Implement {produces {...} requires {...}}
200  # RegisterStage Implement {produces {...} requires {...}} { <body> }
201  #
202  proc RegisterStage {tool_ns name spec args} {
203  if {[llength $args] > 1} {
204  Msg Warning "RegisterStage '$name': expected 'name spec ?body?'"
205  return
206  }
207  set tool_short [string tolower [namespace tail $tool_ns]]
208  if {[llength $args] == 1} {
209  proc ${tool_ns}::${name} {} [lindex $args 0]
210  }
211 
212  set raw [dict create \
213  script "${tool_ns}::${name}" \
214  ide $tool_short \
215  requires_proj true \
216  ]
217 
218  foreach k {description help aliases options produces requires} {
219  if {[dict exists $spec $k]} { dict set raw $k [dict get $spec $k] }
220  }
221 
222  set tool_key [string toupper [namespace tail $tool_ns]]
223  set stage_group "TOOL.$tool_key.STAGE"
224 
225  if {[Commands::GetCommand $stage_group] eq {}} {
226  Commands::RegisterCommand $stage_group [dict create description \
227  "Individual stages of [namespace tail $tool_ns]'s flows.\
228  Usage: $tool_short stage <stage> <project>"]
229  }
230  Commands::RegisterCommand "TOOL.$tool_key.STAGE.$name" $raw
231  }
232 
233  proc Init {} {
234  set active [detectActiveTool]
235  if {$active ne ""} {
236  ::ActiveTool::Set $active
237  }
238  }
239 
240  proc GetToolForProject {project top_path} {
241  set conf [file join $top_path $project hog.conf]
242  if {![file exists $conf]} {
243  Msg Error "hog.conf not found for project '$project' at $conf"
244  return ""
245  }
246  set ide_name_and_ver [string tolower [GetIDEFromConf $conf]]
247  set ide_name [lindex [regexp -all -inline {\S+} $ide_name_and_ver] 0]
248  foreach ns [namespace children ::Tools] {
249  if {[catch {set m [${ns}::GetManifest]} err]} { continue }
250  if {![dict exists $m ref_name]} { continue }
251  foreach iname [dict get $m ref_name] {
252  if {[string tolower $iname] eq $ide_name} {
253  return $ns
254  }
255  }
256  }
257  Msg Warning "No loaded tool matches IDE '$ide_name' (from $conf)"
258  return ""
259  }
260 
261  # we can inject procs into each tool's namespace to provide some common functionality
262  # let's use use calls like Tools::Vivado::GetManifest and not have to define these for each tool
263  proc InjectCommonProcs {tool_ns} {
264  namespace eval $tool_ns {
265 
266  if {[info commands Launch] eq ""} {
267  proc Launch {} {
268  ActiveTool::Set [namespace current]
269  return "no_ide"
270  }
271  }
272 
273  if {[info commands Initialize] eq ""} {
274  proc Initialize {} {}
275  }
276 
277  # Injected into tool's namespace to simplify registration process
278  # key can be dotted -> ping.pong registers the pong command under ping
279  proc RegisterCommand {key raw_dict} {
280  set ns [namespace current]
281  if {![dict exists $raw_dict ide]} { dict set raw_dict ide [string tolower [namespace tail $ns]] }
282  Commands::RegisterCommand "TOOL.[string toupper [namespace tail $ns]].$key" $raw_dict
283  }
284 
285  proc RegisterFlow {key raw_dict} {
286  Flow::RegisterFlow [namespace current] $key $raw_dict
287  }
288 
289  # RegisterStage <name> {spec} declares against an existing proc;
290  # RegisterStage <name> {spec} {body} also defines it.
291  proc RegisterStage {name spec args} {
292  Tools::RegisterStage [namespace current] $name $spec {*}$args
293  }
294 
295  proc GetManifest {} {
296  variable Manifest
297  return $Manifest
298  }
299 
300  proc Has {method} {
301  return [expr {[info commands [namespace current]::${method}] ne ""}]
302  }
303 
304  proc _printTool {} {
305  #TODO: Clean this up probably
306  variable Manifest
307  set injected {Has GetManifest _printTool}
308  set tool_name [namespace tail [namespace current]]
309 
310  set methods {}
311  foreach cmd [lsort [info commands [namespace current]::*]] {
312  set m [namespace tail $cmd]
313  if {$m ni $injected && [string index $m 0] ne "_"} {
314  lappend methods $m
315  }
316  }
317 
318  puts "\[$tool_name\]"
319  puts " Manifest: $Manifest"
320  puts " Methods: [join $methods {, }]"
321  }
322  }
323  }
324 }
325 
326 
327 
328 # Which tool's process we are in - "tclsh" at the top level, or a tool namespace
329 # once an IDE child has booted (or an in-process tool has flipped itself active).
330 # Identity only; stage resolution goes through the command tree
331 namespace eval ActiveTool {
332  variable tool "tclsh"
333 
334  proc CurrentTool {} {
335  variable tool
336  return $tool
337  }
338 
339  proc Set {tool_ns} {
340  variable tool
341  if {$tool_ns ne ""} { set tool $tool_ns }
342  }
343 }