restores Helder in all its glory

This commit is contained in:
2026-09-28 11:34:49 +02:00
parent c2b38b853c
commit 1d29d0952d
280 changed files with 29205 additions and 7 deletions
@@ -0,0 +1,27 @@
import Foundation
enum DirectoryListing {
struct Entry {
enum Kind { case file, directory }
let name: String
let url: URL
let kind: Kind
}
/// Regular files and real folders of one folder in byte order of their names, dotfiles
/// included. Symlinks are left out, as ripgrep without `--follow` leaves them out.
static func entries(of directory: URL) -> [Entry] {
let keys: [URLResourceKey] = [.isSymbolicLinkKey, .isRegularFileKey, .isDirectoryKey]
guard let urls = try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: keys) else {
return []
}
return urls.compactMap { url -> Entry? in
guard let values = try? url.resourceValues(forKeys: Set(keys)), values.isSymbolicLink != true else { return nil }
if values.isDirectory == true { return Entry(name: url.lastPathComponent, url: url, kind: .directory) }
if values.isRegularFile == true { return Entry(name: url.lastPathComponent, url: url, kind: .file) }
return nil
}
.sorted { $0.name < $1.name }
}
}
@@ -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)
}
}
@@ -0,0 +1,82 @@
import Foundation
import HelderCore
public enum FileServiceError: Error, Equatable {
case outsideProject
case alreadyExists(String)
case invalidName(String)
}
/// What a file holds, as far as the editor cares.
public enum FileContents: Equatable, Sendable {
case text(String)
/// A NUL byte in the first 8000 bytes.
case binary
}
public protocol FileServicing: Sendable {
var root: URL { get }
/// The project tree: ripgrep's file list (honouring the config) plus empty folders; a plain walk without ripgrep.
func tree() async -> FileNode
/// Fresh children of one folder ("" is the root), re-read on every expand and collapse.
func children(of directory: String) async -> [FileNode]
/// A text file's contents; "" for a binary file.
func read(_ path: String) async throws -> String
/// A file's text, or `.binary`, so an empty file and a binary one can be told apart.
func readText(_ path: String) async throws -> FileContents
/// An image's bytes; nil for a non-image, a file over 25 MB, or a path outside the project.
func readImage(_ path: String) async -> Data?
/// Replaces the file in one step; a symlinked file is written at its target and keeps its permissions.
func write(_ path: String, contents: String) async throws
/// Creates an empty file and its parent folders; throws `alreadyExists` rather than overwrite.
func createFile(_ path: String) async throws
func createDirectory(_ path: String) async throws
/// Renames within the same folder and returns the new relative path.
func rename(_ path: String, to name: String) async throws -> String
/// Deletes a file or a whole folder.
func delete(_ path: String) async throws
}
extension FileServicing {
/// Built on `read`, which cannot see binary files; only conformers that never meet them should rely on it.
public func readText(_ path: String) async throws -> FileContents {
.text(try await read(path))
}
/// The absolute URL for a relative path, or nil when it escapes the project root.
///
/// The check is on the spelling only, so a symlinked folder can still lead outside; anything
/// that creates, renames or deletes goes through `containedURL(for:)` instead.
public func absoluteURL(for path: String) -> URL? {
let base = root.standardizedFileURL
let target = (path.isEmpty ? base : base.appendingPathComponent(path)).standardizedFileURL
return Self.isInside(target.path, base.path) ? target : nil
}
/// `absoluteURL(for:)`, but nil unless the entry's folder, with every symlink resolved, lies inside the resolved root.
///
/// The entry itself is not resolved: deleting or renaming a symlink acts on the link, not on its target.
public func containedURL(for path: String) -> URL? {
guard let url = absoluteURL(for: path) else { return nil }
let realRoot = Self.realPath(root.standardizedFileURL.path)
if url.path == root.standardizedFileURL.path { return url }
let parent = Self.realPath(url.deletingLastPathComponent().path)
return Self.isInside(parent, realRoot) || parent == realRoot ? url : nil
}
private static func isInside(_ path: String, _ base: String) -> Bool {
let prefix = base.hasSuffix("/") ? base : base + "/"
return path == base || path.hasPrefix(prefix)
}
/// Resolves every symlink; a path that does not exist yet keeps its resolved existing ancestor.
static func realPath(_ path: String) -> String {
if let resolved = realpath(path, nil) {
defer { free(resolved) }
return String(cString: resolved)
}
let parent = (path as NSString).deletingLastPathComponent
guard !parent.isEmpty, parent != path else { return path }
return (realPath(parent) as NSString).appendingPathComponent((path as NSString).lastPathComponent)
}
}
@@ -0,0 +1,273 @@
import Foundation
import CoreServices
import HelderCore
public enum WatchEvent: Sendable, Equatable {
/// A project file changed. Also invalidates the symbol index.
case project
/// Git state moved (see `GitDirectory.watchedEntries`).
case git
/// `.helder/config.json` changed.
case config
}
public protocol FileWatching: AnyObject {
/// Starts watching; `handler` is called on an arbitrary queue. Calling again restarts the watch.
func start(root: URL, handler: @escaping @Sendable (WatchEvent) -> Void)
func stop()
}
/// Quiet periods before each event fires; every new change inside the period restarts it.
public struct WatchDebounce: Sendable, Equatable {
public var project: TimeInterval
public var git: TimeInterval
public var config: TimeInterval
public init(project: TimeInterval, git: TimeInterval, config: TimeInterval) {
self.project = project
self.git = git
self.config = config
}
public static let standard = WatchDebounce(project: 0.25, git: 0.2, config: 0.1)
func interval(for event: WatchEvent) -> TimeInterval {
switch event {
case .project: project
case .git: git
case .config: config
}
}
}
/// FSEvents-backed watcher: one stream over the project root, sorted into the three events.
///
/// Project changes honour the project's `files.exclude`, and its `.gitignore` when `files.followGitignore`
/// is on; the watcher reads `.helder/config.json` itself and again whenever it changes.
public final class FSEventsWatcher: FileWatching {
private let debounce: WatchDebounce
private let latency: TimeInterval
private let runner: ProcessRunning
private let queue = DispatchQueue(label: "nl.blijnder.helder.watcher")
private var stream: FSEventStreamRef?
private var router: EventRouter?
/// `latency` is how long FSEvents itself gathers changes before it calls back.
public init(debounce: WatchDebounce = .standard, latency: TimeInterval = 0.05, runner: ProcessRunning = ProcessRunner()) {
self.debounce = debounce
self.latency = latency
self.runner = runner
}
deinit {
stop()
}
public func start(root: URL, handler: @escaping @Sendable (WatchEvent) -> Void) {
stop()
let router = EventRouter(root: root, debounce: debounce, queue: queue, runner: runner, handler: handler)
var context = FSEventStreamContext(version: 0, info: Unmanaged.passUnretained(router).toOpaque(),
retain: nil, release: nil, copyDescription: nil)
let callback: FSEventStreamCallback = { _, info, count, paths, flags, _ in
guard let info else { return }
let router = Unmanaged<EventRouter>.fromOpaque(info).takeUnretainedValue()
let list = unsafeBitCast(paths, to: NSArray.self)
for i in 0..<count {
guard let path = list[i] as? String else { continue }
router.route(path: path, flags: flags[i])
}
}
let flags = FSEventStreamCreateFlags(kFSEventStreamCreateFlagUseCFTypes | kFSEventStreamCreateFlagFileEvents
| kFSEventStreamCreateFlagNoDefer)
guard let stream = FSEventStreamCreate(nil, callback, &context, router.watchedPaths as CFArray,
FSEventStreamEventId(kFSEventStreamEventIdSinceNow), latency, flags) else {
Log.error("watch", "cannot watch \(root.path)")
return
}
FSEventStreamSetDispatchQueue(stream, queue)
guard FSEventStreamStart(stream) else {
Log.error("watch", "cannot start watching \(root.path)")
FSEventStreamInvalidate(stream)
FSEventStreamRelease(stream)
return
}
self.stream = stream
self.router = router
}
public func stop() {
if let stream {
FSEventStreamStop(stream)
FSEventStreamInvalidate(stream)
FSEventStreamRelease(stream)
}
stream = nil
router?.cancel()
router = nil
}
}
/// Sorts raw FSEvents paths into watch events and debounces them; lives on the watcher's queue.
final class EventRouter: @unchecked Sendable {
private let root: String
private let rootURL: URL
private let gitDirectory: String
private let debounce: WatchDebounce
private let queue: DispatchQueue
private let runner: ProcessRunning
private let handler: @Sendable (WatchEvent) -> Void
private var pending: [WatchEvent: DispatchWorkItem] = [:]
private var cancelled = false
private var files: HelderConfig.Files
/// Project paths changed since the last `.project` fired; nil when the batch must fire unchecked.
private var changedPaths: Set<String>? = []
/// Git's verdict per path; cleared whenever git state or a `.gitignore` changes.
private var ignoredCache: [String: Bool] = [:]
/// Paths per `git check-ignore` call, well under the argument-length limit.
private static let checkIgnoreBatch = 200
init(root: URL, debounce: WatchDebounce, queue: DispatchQueue, runner: ProcessRunning,
handler: @escaping @Sendable (WatchEvent) -> Void) {
self.root = Self.realPath(root.path)
self.rootURL = root
self.gitDirectory = Self.realPath(GitDirectory.resolve(root: root).path)
self.debounce = debounce
self.queue = queue
self.runner = runner
self.handler = handler
self.files = Self.readFiles(root: root)
}
/// The root, plus the git directory when it lives outside the root (worktrees, submodules).
var watchedPaths: [String] {
Self.relative(gitDirectory, to: root) == nil ? [root, gitDirectory] : [root]
}
func route(path: String, flags: FSEventStreamEventFlags) {
guard let event = Self.classify(path: path, root: root, gitDirectory: gitDirectory, flags: flags, exclude: files.exclude) else {
return
}
switch event {
case .project:
let rel = Self.relative(path, to: root) ?? ""
let rescan = flags & FSEventStreamEventFlags(kFSEventStreamEventFlagMustScanSubDirs) != 0
if rescan || rel.isEmpty || PathUtils.basename(rel) == ".gitignore" {
ignoredCache = [:]
changedPaths = nil
} else {
changedPaths?.insert(rel)
}
case .git:
ignoredCache = [:]
case .config:
files = Self.readFiles(root: rootURL)
ignoredCache = [:]
}
schedule(event)
}
func cancel() {
queue.async { [self] in
cancelled = true
pending.values.forEach { $0.cancel() }
pending = [:]
}
}
private func schedule(_ event: WatchEvent) {
guard !cancelled else { return }
pending[event]?.cancel()
let item = DispatchWorkItem { [weak self] in
guard let self, !self.cancelled else { return }
self.pending[event] = nil
if event == .project {
self.fireProject()
} else {
self.handler(event)
}
}
pending[event] = item
queue.asyncAfter(deadline: .now() + debounce.interval(for: event), execute: item)
}
/// Fires `.project` unless every changed path is git-ignored and the project hides ignored files.
private func fireProject() {
let paths = changedPaths
changedPaths = []
guard files.followGitignore, let paths, !paths.isEmpty else { return handler(.project) }
if paths.contains(where: { ignoredCache[$0] == false }) { return handler(.project) }
let unknown = paths.filter { ignoredCache[$0] == nil }.sorted()
guard !unknown.isEmpty else { return }
let runner = self.runner, root = self.rootURL
Task {
let verdict = await Self.allIgnored(unknown, root: root, runner: runner)
self.queue.async { [self] in
guard !cancelled else { return }
if let verdict {
for path in unknown { ignoredCache[path] = verdict }
if verdict { return }
}
handler(.project)
}
}
}
/// True when git ignores every path, false when it ignores none, nil for a mix or when git cannot tell.
static func allIgnored(_ paths: [String], root: URL, runner: ProcessRunning) async -> Bool? {
var ignored = 0
var start = 0
while start < paths.count {
let batch = Array(paths[start..<min(start + checkIgnoreBatch, paths.count)])
start += batch.count
guard let result = try? await runner.run("git", ["check-ignore", "--"] + batch, in: root),
result.exitCode == 0 || result.exitCode == 1 else { return nil }
// One line per ignored path; git quotes odd names but never splits one over two lines.
ignored += result.stdout.split(separator: "\n").count
}
if ignored == paths.count { return true }
return ignored == 0 ? false : nil
}
private static func readFiles(root: URL) -> HelderConfig.Files {
let url = root.appendingPathComponent(HelderConfig.folderName).appendingPathComponent(HelderConfig.overridesFileName)
return HelderConfig.resolved(overrides: try? Data(contentsOf: url)).files
}
/// The event one changed path stands for, or nil when it is noise.
static func classify(path: String, root: String, gitDirectory: String, flags: FSEventStreamEventFlags,
exclude: [String] = []) -> WatchEvent? {
if flags & FSEventStreamEventFlags(kFSEventStreamEventFlagMustScanSubDirs) != 0 { return .project }
if let rel = relative(path, to: gitDirectory) {
return isGitStateEntry(rel) ? .git : nil
}
guard let rel = relative(path, to: root), !rel.isEmpty else { return nil }
if rel == HelderConfig.folderName + "/" + HelderConfig.overridesFileName { return .config }
return IgnoreRules.isWatchIgnored(rel, exclude: exclude) ? nil : .project
}
/// True for the entries `GitDirectory.watchedEntries` names, including what lies under the ref folders.
static func isGitStateEntry(_ rel: String) -> Bool {
let entries = GitDirectory.watchedEntries(gitDirectory: URL(fileURLWithPath: "/")).map { String($0.path.dropFirst()) }
return entries.contains { rel == $0 || rel.hasPrefix($0 + "/") }
}
/// `path` relative to `base` ("" for `base` itself), or nil when it lies outside.
static func relative(_ path: String, to base: String) -> String? {
if path == base { return "" }
let prefix = base.hasSuffix("/") ? base : base + "/"
return path.hasPrefix(prefix) ? String(path.dropFirst(prefix.count)) : nil
}
/// FSEvents reports resolved paths (/private/var, not /var), so the watched folders are resolved too.
/// A path that does not exist yet keeps its resolved parent.
static func realPath(_ path: String) -> String {
if let resolved = realpath(path, nil) {
defer { free(resolved) }
return String(cString: resolved)
}
let parent = (path as NSString).deletingLastPathComponent
guard !parent.isEmpty, parent != path else { return path }
return (realPath(parent) as NSString).appendingPathComponent((path as NSString).lastPathComponent)
}
}