@@ -29,18 +29,28 @@ import TSCLibc
29
29
/// If `body` has a return value, that value is also used as the
30
30
/// return value for the `withTemporaryDirectory` function.
31
31
/// The cleanup block should be called when the temporary directory is no longer needed.
32
- ///
32
+ /// - Returns: `Task<Result, Error>` which can be used
33
33
/// - Throws: `MakeDirectoryError` and rethrows all errors from `body`.
34
34
@available ( macOS 12 , iOS 15 , tvOS 15 , watchOS 8 , * )
35
35
public func withTemporaryDirectory< Result> (
36
36
dir: AbsolutePath ? = nil ,
37
37
prefix: String = " TemporaryDirectory " ,
38
- _ body: ( AbsolutePath , @escaping ( AbsolutePath ) -> Void ) async throws -> Result
39
- ) async throws -> Result {
38
+ _ body: @escaping ( AbsolutePath , @escaping ( AbsolutePath ) -> Void ) async throws -> Result
39
+ ) throws -> Task < Result , Error > {
40
40
let temporaryDirectory = try createTemporaryDirectory ( dir: dir, prefix: prefix)
41
- return try await body ( temporaryDirectory) { path in
42
- _ = try ? FileManager . default. removeItem ( atPath: path. pathString)
41
+
42
+ let task : Task < Result , Error > = Task {
43
+ try await withTaskCancellationHandler {
44
+ try await body ( temporaryDirectory) { path in
45
+ _ = try ? FileManager . default. removeItem ( atPath: path. pathString)
46
+ }
47
+ } onCancel: {
48
+ _ = try ? FileManager . default. removeItem ( atPath: temporaryDirectory. pathString)
49
+ }
50
+
43
51
}
52
+
53
+ return task
44
54
}
45
55
46
56
/// Creates a temporary directory and evaluates a closure with the directory path as an argument.
@@ -63,10 +73,10 @@ public func withTemporaryDirectory<Result>(
63
73
public func withTemporaryDirectory< Result> (
64
74
dir: AbsolutePath ? = nil ,
65
75
prefix: String = " TemporaryDirectory " ,
66
- removeTreeOnDeinit: Bool = false ,
67
- _ body: ( AbsolutePath ) async throws -> Result
68
- ) async throws -> Result {
69
- try await withTemporaryDirectory ( dir: dir, prefix: prefix) { path, cleanup in
76
+ removeTreeOnDeinit: Bool = false ,
77
+ _ body: @escaping ( AbsolutePath ) async throws -> Result
78
+ ) throws -> Task < Result , Error > {
79
+ try withTemporaryDirectory ( dir: dir, prefix: prefix) { path, cleanup in
70
80
defer { if removeTreeOnDeinit { cleanup ( path) } }
71
81
return try await body ( path)
72
82
}
0 commit comments