xtool.git
Publicgit clone https://git.maproj.org/xtool.gitxtool.git / Sources / XUtils / System+Utils.swift
System+Utils.swift53 lines · 1.1 KiBRaw
| 1 | import Foundation |
| 2 | |
| 3 | #if canImport(System) |
| 4 | import System |
| 5 | |
| 6 | public typealias FilePath = System.FilePath |
| 7 | public typealias FileDescriptor = System.FileDescriptor |
| 8 | public typealias Errno = System.Errno |
| 9 | #else |
| 10 | import SystemPackage |
| 11 | |
| 12 | public typealias FilePath = SystemPackage.FilePath |
| 13 | public typealias FileDescriptor = SystemPackage.FileDescriptor |
| 14 | public typealias Errno = SystemPackage.Errno |
| 15 | |
| 16 | extension URL { |
| 17 | public init?(filePath: FilePath) { |
| 18 | self.init(filePath: filePath.string) |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | extension FilePath { |
| 23 | public init?(_ url: URL) { |
| 24 | guard url.isFileURL else { return nil } |
| 25 | self.init(url.path) |
| 26 | } |
| 27 | } |
| 28 | #endif |
| 29 | |
| 30 | extension FileDescriptor { |
| 31 | enum LockMode { |
| 32 | case shared |
| 33 | case exclusive |
| 34 | |
| 35 | fileprivate var raw: CInt { |
| 36 | switch self { |
| 37 | case .shared: LOCK_SH |
| 38 | case .exclusive: LOCK_EX |
| 39 | } |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | func tryLock(mode: LockMode) throws -> Bool { |
| 44 | if flock(rawValue, mode.raw | LOCK_NB) == 0 { |
| 45 | return true |
| 46 | } |
| 47 | let err = errno |
| 48 | if err == EWOULDBLOCK { |
| 49 | return false |
| 50 | } |
| 51 | throw Errno(rawValue: err) |
| 52 | } |
| 53 | } |