Modern Apps git

← xtool.git

Improve cancellation handling

Commit
f16c2c869dad7aa6d04dbf2355494597f0d4b0f2
Author
Kabir Oberai <[email protected]>
When
2024-12-12 17:49 UTC (1 year ago)
Parents
0ac28bc

Diff

Sources/SupersignCLISupport/SupersignCommand.swift
diff --git a/Sources/SupersignCLISupport/SupersignCommand.swift b/Sources/SupersignCLISupport/SupersignCommand.swiftindex eb4d7d0..e37fdd8 100644--- a/Sources/SupersignCLISupport/SupersignCommand.swift+++ b/Sources/SupersignCLISupport/SupersignCommand.swift@@ -21,16 +21,7 @@ public enum SupersignCLI {      public static func run(configuration: Configuration, arguments: [String]? = nil) async throws {         _config = configuration-        do {-            var command = try SupersignCommand.parseAsRoot(arguments)-            if var asyncCommand = command as? AsyncParsableCommand {-                try await asyncCommand.run()-            } else {-                try command.run()-            }-        } catch {-            SupersignCommand.exit(withError: error)-        }+        await SupersignCommand.cancellableMain(arguments)     } } @@ -51,3 +42,34 @@ struct SupersignCommand: AsyncParsableCommand {         ]     ) }++extension ParsableCommand {+    fileprivate static func cancellableMain(_ arguments: [String]? = nil) async {+        let (canStart, cont) = AsyncStream.makeStream(of: Never.self)+        let task = Task {+            for await _ in canStart {}+            guard !Task.isCancelled else { return }+            do {+                var command = try self.parseAsRoot()+                if var asyncCommand = command as? AsyncParsableCommand {+                    try await asyncCommand.run()+                } else {+                    try command.run()+                }+            } catch is CancellationError {+                self.exit()+            } catch {+                self.exit(withError: error)+            }+        }++        signal(SIGINT, SIG_IGN)+        let source = DispatchSource.makeSignalSource(signal: SIGINT)+        source.setEventHandler { task.cancel() }+        source.resume()++        cont.finish()++        await task.value+    }+}