restores Helder in all its glory
This commit is contained in:
@@ -0,0 +1,200 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
|
||||
public struct FileService: FileServicing {
|
||||
public let root: URL
|
||||
private let search: SearchServicing
|
||||
|
||||
public init(root: URL, search: SearchServicing) {
|
||||
self.root = root
|
||||
self.search = search
|
||||
}
|
||||
|
||||
/// Ripgrep's file list plus the empty folders it cannot see; without ripgrep, a walk.
|
||||
public func tree() async -> FileNode {
|
||||
if await search.isAvailable() {
|
||||
async let paths = search.listFiles(under: nil)
|
||||
async let empty = emptyDirectories()
|
||||
let (files, folders) = await (paths, empty)
|
||||
if !files.isEmpty || !folders.isEmpty {
|
||||
return FileTree.build(rootName: rootName, paths: files, emptyDirs: folders)
|
||||
}
|
||||
}
|
||||
return FileNode(name: rootName, kind: .directory, path: "", children: walk(""))
|
||||
}
|
||||
|
||||
public func children(of directory: String) async -> [FileNode] {
|
||||
guard absoluteURL(for: directory) != nil else { return [] }
|
||||
guard await search.isAvailable() else { return walk(directory) }
|
||||
async let paths = search.listFiles(under: directory)
|
||||
async let empty = emptyDirectories(under: directory)
|
||||
let tree = FileTree.build(rootName: rootName, paths: await paths, emptyDirs: await empty)
|
||||
return FileTree.find(directory, in: tree)?.children ?? []
|
||||
}
|
||||
|
||||
/// Folders under `scope` (or the root) whose whole subtree holds no file, relative to the root.
|
||||
public func emptyDirectories(under scope: String? = nil) async -> [String] {
|
||||
let start = scope ?? ""
|
||||
guard let url = absoluteURL(for: start) else { return [] }
|
||||
var out: [String] = []
|
||||
|
||||
/// Whether the subtree holds a file; empty folders are recorded on the way back up.
|
||||
func hasFile(_ url: URL, rel: String, depth: Int) -> Bool {
|
||||
var found = false
|
||||
for entry in DirectoryListing.entries(of: url) where !IgnoreRules.isWalkIgnored(entry.name) {
|
||||
switch entry.kind {
|
||||
case .file:
|
||||
found = true
|
||||
case .directory:
|
||||
let childRel = PathUtils.join(rel, entry.name)
|
||||
if depth < FileLimits.maxWalkDepth && hasFile(entry.url, rel: childRel, depth: depth + 1) {
|
||||
found = true
|
||||
} else {
|
||||
out.append(childRel)
|
||||
}
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
_ = hasFile(url, rel: start, depth: 0)
|
||||
return out
|
||||
}
|
||||
|
||||
public func read(_ path: String) async throws -> String {
|
||||
switch try await readText(path) {
|
||||
case let .text(text): text
|
||||
case .binary: ""
|
||||
}
|
||||
}
|
||||
|
||||
public func readText(_ path: String) async throws -> FileContents {
|
||||
guard let url = absoluteURL(for: path) else { throw FileServiceError.outsideProject }
|
||||
let data = try Data(contentsOf: url)
|
||||
return FileLimits.looksBinary(data) ? .binary : .text(String(decoding: data, as: UTF8.self))
|
||||
}
|
||||
|
||||
public func readImage(_ path: String) async -> Data? {
|
||||
guard FileLimits.imageMimeTypes[FileType.ext(path)] != nil, let url = absoluteURL(for: path),
|
||||
let size = (try? url.resourceValues(forKeys: [.fileSizeKey]))?.fileSize,
|
||||
size <= FileLimits.maxImageBytes else { return nil }
|
||||
return try? Data(contentsOf: url)
|
||||
}
|
||||
|
||||
public func write(_ path: String, contents: String) async throws {
|
||||
guard let url = absoluteURL(for: path) else { throw FileServiceError.outsideProject }
|
||||
let data = Data(contents.utf8)
|
||||
guard exists(url) else {
|
||||
guard let fresh = containedURL(for: path) else { throw FileServiceError.outsideProject }
|
||||
try data.write(to: fresh, options: .withoutOverwriting)
|
||||
return
|
||||
}
|
||||
try Self.replace(url.resolvingSymlinksInPath(), with: data)
|
||||
}
|
||||
|
||||
public func createFile(_ path: String) async throws {
|
||||
let url = try newEntryURL(path)
|
||||
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
do {
|
||||
try Data().write(to: url, options: .withoutOverwriting)
|
||||
} catch CocoaError.fileWriteFileExists {
|
||||
throw FileServiceError.alreadyExists(path)
|
||||
}
|
||||
}
|
||||
|
||||
public func createDirectory(_ path: String) async throws {
|
||||
let url = try newEntryURL(path)
|
||||
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
|
||||
}
|
||||
|
||||
/// A case-only rename (foo.md → Foo.md) is allowed only when both names reach the same file,
|
||||
/// as on a case-insensitive disk; on a case-sensitive one `Foo.md` may be another file.
|
||||
public func rename(_ path: String, to name: String) async throws -> String {
|
||||
guard let clean = PathUtils.validatedName(name) else { throw FileServiceError.invalidName(name) }
|
||||
let next = PathUtils.join(PathUtils.dirname(path), clean)
|
||||
guard !path.isEmpty, let from = containedURL(for: path), let to = containedURL(for: next) else {
|
||||
throw FileServiceError.outsideProject
|
||||
}
|
||||
if from.path == to.path { return path }
|
||||
if Self.isSameFile(from, to) {
|
||||
// rename(2): FileManager.moveItem refuses a case-only rename as "already exists".
|
||||
guard Darwin.rename(from.path, to.path) == 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) }
|
||||
return next
|
||||
}
|
||||
if exists(to) { throw FileServiceError.alreadyExists(next) }
|
||||
guard renamex_np(from.path, to.path, UInt32(RENAME_EXCL)) == 0 else {
|
||||
if errno == EEXIST { throw FileServiceError.alreadyExists(next) }
|
||||
throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
public func delete(_ path: String) async throws {
|
||||
guard let url = containedURL(for: path), url.standardizedFileURL != root.standardizedFileURL else {
|
||||
throw FileServiceError.outsideProject
|
||||
}
|
||||
guard (try? FileManager.default.attributesOfItem(atPath: url.path)) != nil else { return }
|
||||
try FileManager.default.removeItem(at: url)
|
||||
}
|
||||
|
||||
/// Writes a sibling temp file with the old file's permissions, then renames it over the old one.
|
||||
private static func replace(_ target: URL, with data: Data) throws {
|
||||
let mode = (try? FileManager.default.attributesOfItem(atPath: target.path)[.posixPermissions] as? NSNumber)?.uint16Value ?? 0o644
|
||||
let temp = target.deletingLastPathComponent().appendingPathComponent(".\(target.lastPathComponent).helder-\(UUID().uuidString)")
|
||||
let fd = open(temp.path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, mode_t(mode))
|
||||
guard fd >= 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) }
|
||||
do {
|
||||
let handle = FileHandle(fileDescriptor: fd, closeOnDealloc: true)
|
||||
try handle.write(contentsOf: data)
|
||||
try handle.synchronize()
|
||||
guard fchmod(fd, mode_t(mode)) == 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) }
|
||||
try handle.close()
|
||||
guard Darwin.rename(temp.path, target.path) == 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) }
|
||||
} catch {
|
||||
unlink(temp.path)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/// True when both URLs name one existing file, as a case-only rename does on a case-insensitive disk.
|
||||
private static func isSameFile(_ a: URL, _ b: URL) -> Bool {
|
||||
guard a.path.lowercased() == b.path.lowercased() else { return false }
|
||||
var first = stat(), second = stat()
|
||||
guard lstat(a.path, &first) == 0, lstat(b.path, &second) == 0 else { return false }
|
||||
return first.st_dev == second.st_dev && first.st_ino == second.st_ino
|
||||
}
|
||||
|
||||
private var rootName: String {
|
||||
root.lastPathComponent.isEmpty ? root.path : root.lastPathComponent
|
||||
}
|
||||
|
||||
private func exists(_ url: URL) -> Bool {
|
||||
(try? url.checkResourceIsReachable()) == true || FileManager.default.fileExists(atPath: url.path)
|
||||
}
|
||||
|
||||
/// The URL for a file or folder about to be created; refuses the root, escapes and taken names.
|
||||
private func newEntryURL(_ path: String) throws -> URL {
|
||||
guard !path.isEmpty, let url = containedURL(for: path) else { throw FileServiceError.outsideProject }
|
||||
if exists(url) { throw FileServiceError.alreadyExists(path) }
|
||||
return url
|
||||
}
|
||||
|
||||
/// The fallback tree below `directory`: ignored names skipped, folders first, then files.
|
||||
private func walk(_ directory: String, depth: Int = 0) -> [FileNode] {
|
||||
guard let url = absoluteURL(for: directory) else { return [] }
|
||||
var folders: [FileNode] = []
|
||||
var files: [FileNode] = []
|
||||
for entry in DirectoryListing.entries(of: url) where !IgnoreRules.isWalkIgnored(entry.name) {
|
||||
let rel = PathUtils.join(directory, entry.name)
|
||||
switch entry.kind {
|
||||
case .directory:
|
||||
let children = depth < FileLimits.maxWalkDepth ? walk(rel, depth: depth + 1) : []
|
||||
folders.append(FileNode(name: entry.name, kind: .directory, path: rel, children: children))
|
||||
case .file:
|
||||
files.append(FileNode(name: entry.name, kind: .file, path: rel))
|
||||
}
|
||||
}
|
||||
let byName: (FileNode, FileNode) -> Bool = { $0.name.localizedStandardCompare($1.name) == .orderedAscending }
|
||||
return folders.sorted(by: byName) + files.sorted(by: byName)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user