Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / PublicationLease.swift
| 1 | import Darwin |
| 2 | import Foundation |
| 3 | |
| 4 | struct PublicationLeaseBusy: LocalizedError { |
| 5 | var errorDescription: String? { "Wait for the current publishing attempt to finish." } |
| 6 | } |
| 7 | |
| 8 | final 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 | } |