@@ -18,30 +18,27 @@ public actor FileLock {
18
18
self . filePath = path
19
19
}
20
20
21
- public func tryLock( ) async -> Bool {
21
+ public func tryLock( ) async throws -> Bool {
22
22
do {
23
23
guard !self . isLocked else { return true }
24
-
25
- guard !( try await FileSystem . exists ( atPath: self . filePath) ) else {
26
- return false
27
- }
28
- // Create the lock file with exclusive permissions
29
- try await FileSystem . create ( . mode( 0o600 ) , file: self . filePath, contents: nil )
24
+ let fileURL = URL ( fileURLWithPath: self . filePath. string)
25
+ let contents = Data ( ) // Empty data to create a lock file
26
+ try contents. write ( to: fileURL, options: . withoutOverwriting)
30
27
self . isLocked = true
31
28
return true
32
- } catch {
29
+ } catch CocoaError . fileWriteFileExists {
33
30
return false
34
31
}
35
32
}
36
33
37
34
public func waitForLock(
38
35
timeout: TimeInterval = FileLock . defaultTimeout,
39
36
pollingInterval: TimeInterval = FileLock . defaultPollingInterval
40
- ) async -> Bool {
37
+ ) async throws -> Bool {
41
38
let start = Date ( )
42
39
43
40
while Date ( ) . timeIntervalSince ( start) < timeout {
44
- if await self . tryLock ( ) {
41
+ if try await self . tryLock ( ) {
45
42
return true
46
43
}
47
44
try? await Task. sleep ( for: . seconds( pollingInterval) )
@@ -65,7 +62,7 @@ public func withLock<T>(
65
62
action: @escaping ( ) async throws -> T
66
63
) async throws -> T {
67
64
let lock = FileLock ( at: lockFile)
68
- guard await lock. waitForLock ( timeout: timeout, pollingInterval: pollingInterval) else {
65
+ guard try await lock. waitForLock ( timeout: timeout, pollingInterval: pollingInterval) else {
69
66
throw SwiftlyError ( message: " Failed to acquire file lock at \( lock. filePath) " )
70
67
}
71
68
0 commit comments