@@ -33,8 +33,10 @@ local MSG_ID = {
3333 CONSOLE = 3 , -- cloned console output
3434}
3535
36- -- avoid printReplacement to be reentrant
36+ -- stop printReplacement from being reentrant
3737-- otherwise errors might cascade into lots of recursive prints
38+ -- hammerspoon is single threaded, thus this does not need a semaphore
39+ -- otherwise we'll have to deal with a potential race condition
3840module .insidePrintInstances = {}
3941
4042module .print_enter = function (instance )
@@ -46,38 +48,38 @@ module.print_exit = function(instance)
4648 -- make sure instance exists
4749 if module .insidePrintInstances [instance ] then
4850 module .insidePrintInstances [instance ] = module .insidePrintInstances [instance ] - 1
51+ -- make sure to delete the entry from the table to avoid
52+ -- growing forever
4953 if module .insidePrintInstances [instance ] == 0 then
5054 module .insidePrintInstances [instance ] = nil
5155 end
5256 end
5357end
5458
5559module .print_inside = function (instance )
60+ -- return true if we are already inside printReplacement
5661 val = module .insidePrintInstances [instance ]
5762 return val and val > 0
5863end
5964
6065local originalPrint = print
6166local printReplacement = function (...)
6267 originalPrint (... )
63- for i ,v in pairs (module .__registeredCLIInstances ) do
64- originalPrint (string.format (" to print instance [%s]" , i ))
68+ for id ,v in pairs (module .__registeredCLIInstances ) do
6569 if v ._cli .console and v .print and not v ._cli .quietMode then
66- -- v.print(...)
67- -- make it more obvious what is console output versus the command line's
68-
69- if module .print_inside (i ) then
70- originalPrint (string.format (" Instance of [%s] already recursing [%d] times, do not do " ,
71- i , module .insidePrintInstances [i ]))
70+ if module .print_inside (id ) then
71+ log .w (string.format (" Instance of [%s] already recursing, refusing request." , id ))
7272 else
73- module .print_enter (i )
73+ module .print_enter (id )
74+ -- v.print(...)
75+ -- make it more obvious what is console output versus the command line's
7476 local things = table.pack (... )
7577 local stdout = (things .n > 0 ) and tostring (things [1 ]) or " "
7678 for i = 2 , things .n do
7779 stdout = stdout .. " \t " .. tostring (things [i ])
7880 end
7981 v ._cli .remote :sendMessage (stdout .. " \n " , MSG_ID .CONSOLE )
80- module .print_exit (i )
82+ module .print_exit (id )
8183 end
8284 end
8385 end
0 commit comments