Branchwell

Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / PublicationLease.swift

Raw 758 B on 8f75dd7d901e2186ca9d9e1cf2f061105c02ae42
1import Darwin
2import Foundation
3
4struct PublicationLeaseBusy: LocalizedError {
5 var errorDescription: String? { "Wait for the current publishing attempt to finish." }
6}
7
8final class PublicationLease {
9 private let descriptor: Int32
10
11 init(directory: URL) throws {
12 let file = directory.appending(path: ".publication.lock")
13 let descriptor = open(file.path, O_RDWR | O_CREAT | O_NOFOLLOW | O_CLOEXEC, 0o600)
14 guard descriptor >= 0 else { throw WorkspaceError("Couldn’t lock the publishing workspace.") }
15 guard flock(descriptor, LOCK_EX | LOCK_NB) == 0 else {
16 close(descriptor)
17 throw PublicationLeaseBusy()
18 }
19 self.descriptor = descriptor
20 }
21
22 deinit { close(descriptor) }
23}