Allow using an external task for running commands in mac-crafter run command
authorClaudio Cambra <claudio.cambra@nextcloud.com>
Thu, 21 Nov 2024 10:27:52 +0000 (18:27 +0800)
committerClaudio Cambra <claudio.cambra@nextcloud.com>
Thu, 21 Nov 2024 10:46:59 +0000 (18:46 +0800)
Signed-off-by: Claudio Cambra <claudio.cambra@nextcloud.com>
admin/osx/mac-crafter/Sources/Utils/Shell.swift

index 1d7a35522c4118b5e9a219e56aea2e488608aa4c..8c1570c5e8f516821cf06e3ed94c2acace17dc10 100644 (file)
 
 import Foundation
 
-var task: Process?
+weak var globalTaskRef: Process?
 
 @discardableResult
 func run(
     _ launchPath: String,
     _ args: [String],
     env: [String: String]? = nil,
-    quiet: Bool = false
+    quiet: Bool = false,
+    task: Process = Process()
 ) -> Int32 {
-    defer { task = nil }
-    task = Process()
-
+    globalTaskRef = task
     signal(SIGINT) { _ in
-        task?.terminate()  // Send terminate signal to the task
-        exit(0)            // Exit the script after cleanup
+        globalTaskRef?.terminate()  // Send terminate signal to the task
+        exit(0)           // Exit the script after cleanup
     }
 
-    task?.launchPath = launchPath
-    task?.arguments = args
+    task.launchPath = launchPath
+    task.arguments = args
 
     if let env,
-       let combinedEnv = task?.environment?.merging(env, uniquingKeysWith: { (_, new) in new })
+       let combinedEnv = task.environment?.merging(env, uniquingKeysWith: { (_, new) in new })
     {
-        task?.environment = combinedEnv
+        task.environment = combinedEnv
     }
 
     if quiet {
-        task?.standardOutput = nil
-        task?.standardError = nil
+        task.standardOutput = nil
+        task.standardError = nil
     }
 
-    task?.launch()
-    task?.waitUntilExit()
-    return task?.terminationStatus ?? 1
+    task.launch()
+    task.waitUntilExit()
+    return task.terminationStatus
 }
 
 func run(