@@ -207,8 +207,8 @@ func runProgramAction(pme *packagemanager.Explorer,
207207 outStream , errStream io.Writer ,
208208 dryRun bool , userFields map [string ]string ) (* rpc.Port , error ) {
209209
210+ // Ensure watcher events consumption in case of exit on error
210211 defer func () {
211- // On exit, discard all events until the watcher is closed
212212 go f .DiscardCh (watch )
213213 }()
214214
@@ -218,20 +218,6 @@ func runProgramAction(pme *packagemanager.Explorer,
218218 }
219219 logrus .WithField ("port" , port ).Tracef ("Upload port" )
220220
221- // Default newPort
222- uploadCompleted := func () * rpc.Port { return nil }
223- if watch != nil {
224- // Run port detector
225- uploadCompletedCtx , cancel := context .WithCancel (context .Background ())
226- newUploadPort := f .NewFuture [* rpc.Port ]()
227- go detectUploadPort (port , watch , uploadCompletedCtx , newUploadPort )
228- uploadCompleted = func () * rpc.Port {
229- cancel ()
230- return newUploadPort .Await ()
231- }
232- defer uploadCompleted () // defer in case of exit on error (ensures goroutine completion)
233- }
234-
235221 if burnBootloader && programmerID == "" {
236222 return nil , & arduino.MissingProgrammerError {}
237223 }
@@ -404,6 +390,24 @@ func runProgramAction(pme *packagemanager.Explorer,
404390 uploadProperties .Set ("build.project_name" , sketchName )
405391 }
406392
393+ // By default do not return any new port...
394+ uploadCompleted := func () * rpc.Port { return nil }
395+ // ...but if there is an expected port change then run the detector...
396+ if uploadProperties .GetBoolean ("upload.wait_for_upload_port" ) && watch != nil {
397+ uploadCompletedCtx , cancel := context .WithCancel (context .Background ())
398+ newUploadPort := f .NewFuture [* rpc.Port ]()
399+ go detectUploadPort (port , watch , uploadCompletedCtx , newUploadPort )
400+ uploadCompleted = func () * rpc.Port {
401+ cancel ()
402+ return newUploadPort .Await ()
403+ }
404+
405+ // Ensures goroutines completion in case of exit on error
406+ defer uploadCompleted ()
407+ } else {
408+ go f .DiscardCh (watch )
409+ }
410+
407411 // Force port wait to make easier to unbrick boards like the Arduino Leonardo, or similar with native USB,
408412 // when a sketch causes a crash and the native USB serial port is lost.
409413 // See https://github.com/arduino/arduino-cli/issues/1943 for the details.
0 commit comments