Last active
June 9, 2018 10:11
-
-
Save warrenburton/8444b4956656fe2a00d4b9ac55a13080 to your computer and use it in GitHub Desktop.
Simple recursive file search utility.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
/// An object to perform a case sensitive recursive directory search for a **file** | |
/// Will not enter packages/bundles | |
class FileFinder: NSObject { | |
private let filename: String | |
private let rootDirectory: String | |
var maxDepth: Int = 5 | |
/// - parameter filename: File to find | |
/// - parameter rootDirectory: Directory to search in | |
/// - parameter maxDepth: Maximum depth to search ( unimplemented ) | |
init(filename:String, rootDirectory:String, maxDepth: Int = 5) { | |
self.filename = filename | |
self.rootDirectory = rootDirectory | |
super.init() | |
} | |
/// Perform search | |
/// - returns: String file path or nil if not found | |
func find() -> String? { | |
depth = 0 | |
return walkDirectory(parentDirectory: rootDirectory) | |
} | |
var depth = 0 | |
private func walkDirectory(parentDirectory: String) -> String? { | |
depth += 1 | |
let manager = FileManager.default | |
do { | |
let contents = try manager.contentsOfDirectory(atPath: parentDirectory) | |
for file in contents { | |
let path = parentDirectory.ns().appendingPathComponent(file) | |
if file == filename { | |
return path | |
} | |
if shouldDescend(path), let result = walkDirectory(parentDirectory: path) { | |
return result | |
} | |
} | |
} | |
catch { | |
print("gah! find error - \(error)") | |
} | |
depth -= 1 | |
depth = max(depth,0) | |
return nil | |
} | |
private func shouldDescend(_ path: String) -> Bool { | |
do { | |
let url = URL(fileURLWithPath: path) | |
let resourceValues = try url.resourceValues(forKeys: [.isPackageKey,.isDirectoryKey,.isSymbolicLinkKey]) | |
let isDirectory = resourceValues.isDirectory ?? false | |
let isPackage = resourceValues.isPackage ?? false | |
let isSymLink = resourceValues.isSymbolicLink ?? false | |
return isDirectory && !isPackage && !isSymLink | |
} catch { | |
print("strange? resource key fetch error - \(error)") | |
} | |
return false | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment