1
1
mirror of https://github.com/qvacua/vimr.git synced 2024-12-11 07:22:23 +03:00
vimr/VimR/FileUtils.swift

68 lines
1.9 KiB
Swift
Raw Normal View History

/**
* Tae Won Ha - http://taewon.de - @hataewon
* See LICENSE
*/
import Foundation
class FileUtils {
2016-09-25 18:50:33 +03:00
fileprivate static let keysToGet = [
URLResourceKey.isDirectoryKey,
URLResourceKey.isHiddenKey,
URLResourceKey.isAliasFileKey,
URLResourceKey.isSymbolicLinkKey
]
2016-09-25 18:50:33 +03:00
fileprivate static let scanOptions: FileManager.DirectoryEnumerationOptions = [
FileManager.DirectoryEnumerationOptions.skipsSubdirectoryDescendants,
FileManager.DirectoryEnumerationOptions.skipsPackageDescendants
]
2016-09-25 18:50:33 +03:00
fileprivate static let fileManager = FileManager.default
2016-10-02 13:28:47 +03:00
static let userHomeUrl = URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)
2016-09-25 18:50:33 +03:00
static func directDescendants(_ url: URL) -> [URL] {
guard let childUrls = try? self.fileManager.contentsOfDirectory(
at: url, includingPropertiesForKeys: self.keysToGet, options: self.scanOptions
) else {
// FIXME error handling
return []
}
return childUrls
}
2016-09-25 18:50:33 +03:00
static func fileExistsAtUrl(_ url: URL) -> Bool {
guard url.isFileURL else {
return false
}
2016-09-25 18:50:33 +03:00
let path = url.path
return self.fileManager.fileExists(atPath: path)
}
2016-09-25 18:50:33 +03:00
static func commonParent(ofUrls urls: [URL]) -> URL {
guard urls.count > 0 else {
2016-09-25 18:50:33 +03:00
return URL(fileURLWithPath: "/", isDirectory: true)
}
2016-09-25 18:50:33 +03:00
let pathComps = urls.map { $0.pathComponents }
2016-10-07 19:06:58 +03:00
let min = pathComps.map { $0.count }.min()!
let pathCompsOnlyMin = pathComps.map { $0[0..<min] }
2016-10-07 01:24:15 +03:00
let commonIdx = (0..<min).reversed().reduce(min - 1) { (result, idx) in
if Set(pathCompsOnlyMin.map { $0[idx] }).count > 1 {
return idx - 1
} else {
return result
}
}
2016-10-07 01:24:15 +03:00
let result = pathCompsOnlyMin[0]
let possibleParent = NSURL.fileURL(withPathComponents: Array(result[0...commonIdx]))!
return possibleParent.dir ? possibleParent : possibleParent.deletingLastPathComponent()
}
}