restores Helder in all its glory
This commit is contained in:
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import Foundation
|
||||
|
||||
public enum GitDirectory {
|
||||
/// The real git directory: `<root>/.git`, or the `gitdir:` target when `.git` is a file (worktrees, submodules).
|
||||
public static func resolve(root: URL) -> URL {
|
||||
let dot = root.appendingPathComponent(".git")
|
||||
var isDir: ObjCBool = false
|
||||
guard FileManager.default.fileExists(atPath: dot.path, isDirectory: &isDir), !isDir.boolValue,
|
||||
let text = try? String(contentsOf: dot, encoding: .utf8) else { return dot }
|
||||
let line = text.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard line.hasPrefix("gitdir:") else { return dot }
|
||||
let target = line.dropFirst("gitdir:".count).trimmingCharacters(in: .whitespaces)
|
||||
return URL(fileURLWithPath: target, relativeTo: root).standardizedFileURL
|
||||
}
|
||||
|
||||
/// The entries whose change means "git state moved": branch switch, staging, commits, pushes, merges.
|
||||
public static func watchedEntries(gitDirectory dir: URL) -> [URL] {
|
||||
["HEAD", "index", "refs/heads", "refs/remotes", "logs/HEAD", "MERGE_HEAD"].map { dir.appendingPathComponent($0) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
|
||||
public actor GitService: GitServicing {
|
||||
public nonisolated let root: URL
|
||||
private let runner: ProcessRunning
|
||||
private let statusAttempts: Int
|
||||
private let statusRetryDelay: TimeInterval
|
||||
private let pushTimeout: TimeInterval
|
||||
private let maxDiffBytes: Int
|
||||
|
||||
/// Enough overlapping `git show`s to hide process start-up, well under macOS's open-file limit.
|
||||
private static let maxConcurrentReads = 12
|
||||
private var inFlight: (id: Int, task: Task<GitSnapshot?, Error>)?
|
||||
private var trailing: Task<GitSnapshot?, Error>?
|
||||
private var readCount = 0
|
||||
/// Loads that joined the trailing read instead of starting their own.
|
||||
private(set) var coalescedLoads = 0
|
||||
|
||||
/// `statusAttempts` and `statusRetryDelay` ride out an external tool holding `.git/index.lock`.
|
||||
public init(root: URL, runner: ProcessRunning = ProcessRunner(), statusAttempts: Int = 6,
|
||||
statusRetryDelay: TimeInterval = 0.12, pushTimeout: TimeInterval = 120,
|
||||
maxDiffBytes: Int = FileLimits.maxDiffFileBytes) {
|
||||
self.root = root
|
||||
self.runner = runner
|
||||
self.statusAttempts = statusAttempts
|
||||
self.statusRetryDelay = statusRetryDelay
|
||||
self.pushTimeout = pushTimeout
|
||||
self.maxDiffBytes = maxDiffBytes
|
||||
}
|
||||
|
||||
/// Reads status plus each changed file's text on both sides of its row.
|
||||
///
|
||||
/// Overlapping calls share one read in flight plus one trailing read, because a branch switch
|
||||
/// fires several watcher pings. Binary files read as ""; a file over `maxDiffBytes` is flagged `isTooBig`.
|
||||
public func load() async throws -> GitSnapshot? {
|
||||
if let trailing {
|
||||
coalescedLoads += 1
|
||||
return try await trailing.value
|
||||
}
|
||||
if let running = inFlight?.task {
|
||||
let next = Task { () async throws -> GitSnapshot? in
|
||||
_ = try? await running.value
|
||||
return try await self.startRead()
|
||||
}
|
||||
trailing = next
|
||||
coalescedLoads += 1
|
||||
return try await next.value
|
||||
}
|
||||
return try await startRead()
|
||||
}
|
||||
|
||||
/// The text of `path` in HEAD or in the index; "" when that side has no such file or it is binary.
|
||||
public func contents(of path: String, at revision: GitRevision) async -> String {
|
||||
await Self.blob(revision.prefix + path, root: root, runner: runner, maxBytes: .max).text
|
||||
}
|
||||
|
||||
/// True inside a work tree; falls back to a `.git` on disk so a branch switch mid-probe does not blank the column.
|
||||
public func isRepository() async -> Bool {
|
||||
if let result = try? await Self.run(["rev-parse", "--is-inside-work-tree"], root: root, runner: runner),
|
||||
result.succeeded, result.stdout.trimmingCharacters(in: .whitespacesAndNewlines) == "true" {
|
||||
return true
|
||||
}
|
||||
return FileManager.default.fileExists(atPath: root.appendingPathComponent(".git").path)
|
||||
}
|
||||
|
||||
public func stage(_ paths: [String]) async throws {
|
||||
guard !paths.isEmpty else { return }
|
||||
try await git(["add", "--"] + paths)
|
||||
}
|
||||
|
||||
public func unstage(_ paths: [String]) async throws {
|
||||
guard !paths.isEmpty else { return }
|
||||
let reset = try await Self.run(["reset", "--"] + paths, root: root, runner: runner)
|
||||
if !reset.succeeded {
|
||||
// A repository without commits has no HEAD to reset to.
|
||||
try await git(["rm", "--cached", "-r", "--"] + paths)
|
||||
}
|
||||
}
|
||||
|
||||
public func commit(message: String) async throws {
|
||||
try await git(["commit", "-m", message])
|
||||
}
|
||||
|
||||
/// Pushes; retries once with `-u origin <branch>` when the branch has no upstream.
|
||||
/// Credential prompts are switched off and the whole push gives up after `pushTimeout`.
|
||||
public func push() async -> PushResult {
|
||||
let environment = Self.environment(adding: ["GIT_TERMINAL_PROMPT": "0", "GCM_INTERACTIVE": "never"])
|
||||
let runner = self.runner, root = self.root
|
||||
let attempt = Task { () async throws -> ProcessResult in
|
||||
var result = try await runner.run("git", arguments: ["push"], in: root, environment: environment)
|
||||
if !result.succeeded && Porcelain.needsUpstream(stderr: result.stderr) {
|
||||
let head = try await runner.run("git", arguments: ["rev-parse", "--abbrev-ref", "HEAD"], in: root, environment: environment)
|
||||
let branch = head.stdout.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
if !branch.isEmpty && branch != "HEAD" {
|
||||
result = try await runner.run("git", arguments: ["push", "-u", "origin", branch], in: root, environment: environment)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
let timeout = Task {
|
||||
try await Task.sleep(nanoseconds: UInt64(pushTimeout * 1_000_000_000))
|
||||
attempt.cancel()
|
||||
}
|
||||
defer { timeout.cancel() }
|
||||
do {
|
||||
let result = try await attempt.value
|
||||
return Porcelain.pushSummary(exitCode: result.exitCode, stdout: result.stdout, stderr: result.stderr)
|
||||
} catch is CancellationError {
|
||||
return PushResult(ok: false, message: "push timed out")
|
||||
} catch {
|
||||
return PushResult(ok: false, message: "\(error)")
|
||||
}
|
||||
}
|
||||
|
||||
/// A path HEAD has is checked out from HEAD (index and disk); any other path is unstaged
|
||||
/// and its file deleted. A staged rename also gets its source back. Folders are never deleted.
|
||||
public func discard(_ paths: [String]) async throws {
|
||||
let renames = paths.isEmpty ? [:] : try await stagedRenameSources()
|
||||
for path in paths {
|
||||
if let source = renames[path] {
|
||||
_ = try await Self.run(["reset", "-q", "HEAD", "--", source, path], root: root, runner: runner)
|
||||
try await git(["checkout", "HEAD", "--", source])
|
||||
}
|
||||
let known = try await Self.run(["cat-file", "-e", "HEAD:" + path], root: root, runner: runner)
|
||||
if known.succeeded {
|
||||
try await git(["checkout", "HEAD", "--", path])
|
||||
continue
|
||||
}
|
||||
_ = try await Self.run(["reset", "-q", "HEAD", "--", path], root: root, runner: runner)
|
||||
guard let url = fileURL(path) else { continue }
|
||||
var isDirectory: ObjCBool = false
|
||||
if FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory), !isDirectory.boolValue {
|
||||
try FileManager.default.removeItem(at: url)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Rename target → source for every rename in the index.
|
||||
private func stagedRenameSources() async throws -> [String: String] {
|
||||
let parsed = Porcelain.parseStatus(try await statusWithRetry())
|
||||
var sources: [String: String] = [:]
|
||||
for entry in parsed.entries where entry.isStagedRename {
|
||||
sources[entry.path] = entry.originalPath
|
||||
}
|
||||
return sources
|
||||
}
|
||||
|
||||
// MARK: - load
|
||||
|
||||
private func startRead() async throws -> GitSnapshot? {
|
||||
trailing = nil
|
||||
readCount += 1
|
||||
let id = readCount
|
||||
let task = Task { try await self.read() }
|
||||
inFlight = (id, task)
|
||||
defer { if inFlight?.id == id { inFlight = nil } }
|
||||
return try await task.value
|
||||
}
|
||||
|
||||
private func read() async throws -> GitSnapshot? {
|
||||
guard await isRepository() else { return nil }
|
||||
let raw = try await statusWithRetry()
|
||||
let parsed = Porcelain.parseStatus(raw)
|
||||
let root = self.root, runner = self.runner, maxBytes = self.maxDiffBytes
|
||||
let perEntry = try await Self.mapLimited(parsed.entries, limit: Self.maxConcurrentReads) { entry in
|
||||
await Self.changes(for: entry, root: root, runner: runner, maxBytes: maxBytes)
|
||||
}
|
||||
return GitSnapshot(branch: parsed.branch, ahead: parsed.ahead, canPush: parsed.canPush, changes: perEntry.flatMap { $0 })
|
||||
}
|
||||
|
||||
/// An external checkout briefly holds `.git/index.lock`; a status landing then fails, so retry.
|
||||
private func statusWithRetry() async throws -> String {
|
||||
var attempt = 0
|
||||
while true {
|
||||
attempt += 1
|
||||
let result = try await Self.run(Porcelain.statusArguments, root: root, runner: runner, adding: ["GIT_OPTIONAL_LOCKS": "0"])
|
||||
if result.succeeded { return result.stdout }
|
||||
if attempt >= statusAttempts {
|
||||
throw GitError.commandFailed(arguments: Porcelain.statusArguments, exitCode: result.exitCode,
|
||||
stderr: result.stderr.trimmingCharacters(in: .whitespacesAndNewlines))
|
||||
}
|
||||
try await Task.sleep(nanoseconds: UInt64(statusRetryDelay * 1_000_000_000))
|
||||
}
|
||||
}
|
||||
|
||||
/// The rows of one porcelain entry, each with the text on both sides of its half.
|
||||
///
|
||||
/// The index blob is only read when the file has both rows: with one row the index equals
|
||||
/// HEAD (unstaged only) or the disk (staged only), which saves a `git show` per file.
|
||||
private static func changes(for entry: StatusEntry, root: URL, runner: ProcessRunning, maxBytes: Int) async -> [GitFileChange] {
|
||||
let rows = Porcelain.classify(index: entry.index, working: entry.working)
|
||||
let stagedRow = rows.first { $0.staged }
|
||||
let workRow = rows.first { !$0.staged }
|
||||
let both = stagedRow != nil && workRow != nil
|
||||
let path = entry.path
|
||||
let head = { await blob(GitRevision.head.prefix + path, root: root, runner: runner, maxBytes: maxBytes) }
|
||||
let index = both ? await blob(GitRevision.index.prefix + path, root: root, runner: runner, maxBytes: maxBytes) : .text("")
|
||||
var out: [GitFileChange] = []
|
||||
if let row = stagedRow {
|
||||
let original: Side = row.status == .added ? .text("") : await head()
|
||||
let updated: Side = row.status == .deleted ? .text("") : both ? index : diskText(path, root: root, maxBytes: maxBytes)
|
||||
out.append(change(path, row, staged: true, original, updated, originalPath: entry.originalPath))
|
||||
}
|
||||
if let row = workRow {
|
||||
let original: Side = entry.index == "?" ? .text("") : both ? index : await head()
|
||||
let updated: Side = row.status == .deleted ? .text("") : diskText(path, root: root, maxBytes: maxBytes)
|
||||
out.append(change(path, row, staged: false, original, updated,
|
||||
originalPath: stagedRow == nil ? entry.originalPath : nil))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/// One side of a change: its text, or over the cap (and never read into memory as text).
|
||||
private enum Side {
|
||||
case text(String)
|
||||
case tooBig
|
||||
|
||||
var text: String {
|
||||
if case let .text(value) = self { return value }
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
private static func change(_ path: String, _ row: GitRowSpec, staged: Bool,
|
||||
_ original: Side, _ updated: Side, originalPath: String?) -> GitFileChange {
|
||||
let tooBig = if case .tooBig = original { true } else if case .tooBig = updated { true } else { false }
|
||||
return GitFileChange(path: path, status: row.status, staged: staged,
|
||||
original: tooBig ? "" : original.text, updated: tooBig ? "" : updated.text,
|
||||
originalPath: originalPath, isTooBig: tooBig)
|
||||
}
|
||||
|
||||
private static func blob(_ spec: String, root: URL, runner: ProcessRunning, maxBytes: Int) async -> Side {
|
||||
guard let result = try? await run(["show", spec], root: root, runner: runner), result.succeeded else { return .text("") }
|
||||
guard result.stdout.utf8.count <= maxBytes else { return .tooBig }
|
||||
return .text(result.stdout.prefix(8000).contains("\0") ? "" : result.stdout)
|
||||
}
|
||||
|
||||
/// The file's text, or "" when it is binary or missing; an oversized file is never read.
|
||||
private static func diskText(_ path: String, root: URL, maxBytes: Int) -> Side {
|
||||
let url = root.appendingPathComponent(path)
|
||||
guard let size = (try? FileManager.default.attributesOfItem(atPath: url.path)[.size] as? NSNumber)?.intValue else {
|
||||
return .text("")
|
||||
}
|
||||
guard size <= maxBytes else { return .tooBig }
|
||||
guard let data = try? Data(contentsOf: url), !FileLimits.looksBinary(data) else { return .text("") }
|
||||
return .text(String(decoding: data, as: UTF8.self))
|
||||
}
|
||||
|
||||
/// Maps with at most `limit` operations running at once, keeping the input order.
|
||||
private static func mapLimited<T: Sendable, R: Sendable>(_ items: [T], limit: Int,
|
||||
_ transform: @escaping @Sendable (T) async -> R) async throws -> [R] {
|
||||
var results = [R?](repeating: nil, count: items.count)
|
||||
try await withThrowingTaskGroup(of: (Int, R).self) { group in
|
||||
var next = 0
|
||||
func launch() {
|
||||
let index = next
|
||||
let item = items[index]
|
||||
group.addTask { (index, await transform(item)) }
|
||||
next += 1
|
||||
}
|
||||
while next < min(limit, items.count) { launch() }
|
||||
while let (index, value) = try await group.next() {
|
||||
results[index] = value
|
||||
if next < items.count { launch() }
|
||||
}
|
||||
}
|
||||
return results.map { $0! }
|
||||
}
|
||||
|
||||
/// Paths reach git as literal pathspecs: `pages/[id].vue` must never also match `pages/i.vue`.
|
||||
private static func environment(adding extra: [String: String] = [:]) -> [String: String] {
|
||||
var environment = ProcessInfo.processInfo.environment.merging(extra) { _, new in new }
|
||||
environment["GIT_LITERAL_PATHSPECS"] = "1"
|
||||
return environment
|
||||
}
|
||||
|
||||
private static func run(_ arguments: [String], root: URL, runner: ProcessRunning,
|
||||
adding extra: [String: String] = [:]) async throws -> ProcessResult {
|
||||
try await runner.run("git", arguments: arguments, in: root, environment: environment(adding: extra))
|
||||
}
|
||||
|
||||
/// The file for a repository path, or nil for the root itself or a path that escapes it.
|
||||
private func fileURL(_ path: String) -> URL? {
|
||||
let base = root.standardizedFileURL.path
|
||||
let url = root.appendingPathComponent(path).standardizedFileURL
|
||||
return url.path.hasPrefix(base + "/") ? url : nil
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
private func git(_ arguments: [String]) async throws -> String {
|
||||
let result = try await Self.run(arguments, root: root, runner: runner)
|
||||
guard result.succeeded else {
|
||||
throw GitError.commandFailed(arguments: arguments, exitCode: result.exitCode,
|
||||
stderr: result.stderr.trimmingCharacters(in: .whitespacesAndNewlines))
|
||||
}
|
||||
return result.stdout
|
||||
}
|
||||
}
|
||||
|
||||
/// Which stored copy of a file `GitService.contents(of:at:)` reads.
|
||||
public enum GitRevision: Sendable {
|
||||
case head
|
||||
case index
|
||||
|
||||
var prefix: String {
|
||||
switch self {
|
||||
case .head: "HEAD:"
|
||||
case .index: ":0:"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
|
||||
public enum GitError: Error, Equatable {
|
||||
/// A git command exited non-zero; `stderr` is trimmed.
|
||||
case commandFailed(arguments: [String], exitCode: Int32, stderr: String)
|
||||
}
|
||||
|
||||
public protocol GitServicing: Sendable {
|
||||
/// The working state, or nil when the project is not a git repository.
|
||||
func load() async throws -> GitSnapshot?
|
||||
/// Stages modifications, additions and deletions of the paths.
|
||||
func stage(_ paths: [String]) async throws
|
||||
func unstage(_ paths: [String]) async throws
|
||||
func commit(message: String) async throws
|
||||
/// Never throws: a failed push is a toast, not an error.
|
||||
func push() async -> PushResult
|
||||
/// Reverts each path to HEAD; a file HEAD does not have is unstaged and deleted, and a staged rename gets its source back.
|
||||
func discard(_ paths: [String]) async throws
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import Foundation
|
||||
|
||||
/// Plain-text log at `~/Library/Logs/Helder/helder.log`, written synchronously so a line
|
||||
/// survives a crash moments later. Rotates at 2 MB and keeps 3 old files.
|
||||
public final class FileLogger: LogSink, @unchecked Sendable {
|
||||
public static let maxBytes = 2 * 1024 * 1024
|
||||
public static let keep = 3
|
||||
|
||||
public let fileURL: URL
|
||||
public let minimumLevel: LogLevel
|
||||
private let directory: URL
|
||||
private let lock = NSLock()
|
||||
/// Tracked here so the common path needs no stat per line; nil until the first write.
|
||||
private var size: Int?
|
||||
|
||||
public init(directory: URL, minimumLevel: LogLevel = .debug) {
|
||||
self.directory = directory
|
||||
self.fileURL = directory.appendingPathComponent("helder.log")
|
||||
self.minimumLevel = minimumLevel
|
||||
}
|
||||
|
||||
public static var defaultDirectory: URL {
|
||||
FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask)[0].appendingPathComponent("Logs/Helder")
|
||||
}
|
||||
|
||||
/// One line per call: ISO timestamp, level, scope, message.
|
||||
///
|
||||
/// Never throws and never waits on another lock: it is called from failure paths everywhere.
|
||||
public func write(level: LogLevel, scope: String, message: String) {
|
||||
guard level >= minimumLevel else { return }
|
||||
let line = Data(Self.formatLine(level: level, scope: scope, message: message,
|
||||
pid: ProcessInfo.processInfo.processIdentifier, date: Date()).utf8)
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
if size == nil {
|
||||
try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
size = (try? FileManager.default.attributesOfItem(atPath: fileURL.path)[.size] as? Int) ?? 0
|
||||
}
|
||||
if (size ?? 0) + line.count > Self.maxBytes { rotate() }
|
||||
// O_APPEND keeps lines from sibling Helder processes sharing this file whole.
|
||||
let fd = open(fileURL.path, O_WRONLY | O_APPEND | O_CREAT, 0o644)
|
||||
guard fd >= 0 else { return }
|
||||
defer { close(fd) }
|
||||
let written = line.withUnsafeBytes { Darwin.write(fd, $0.baseAddress, $0.count) }
|
||||
if written > 0 { size = (size ?? 0) + written }
|
||||
}
|
||||
|
||||
/// `helder.log` becomes `helder.1.log`, and so on; the oldest beyond `keep` is dropped.
|
||||
/// Another process may rotate first, so every step is best effort.
|
||||
private func rotate() {
|
||||
let fm = FileManager.default
|
||||
func old(_ n: Int) -> String { directory.appendingPathComponent("helder.\(n).log").path }
|
||||
try? fm.removeItem(atPath: old(Self.keep))
|
||||
for n in stride(from: Self.keep - 1, through: 1, by: -1) {
|
||||
Darwin.rename(old(n), old(n + 1))
|
||||
}
|
||||
Darwin.rename(fileURL.path, old(1))
|
||||
size = 0
|
||||
}
|
||||
|
||||
/// `2026-07-15T10:00:00.000Z INFO 42 git loaded`; continuation lines are indented
|
||||
/// so a message with newlines never looks like a second entry.
|
||||
public static func formatLine(level: LogLevel, scope: String, message: String, pid: Int32, date: Date) -> String {
|
||||
let stamp = timestampFormatter.string(from: date)
|
||||
let indented = message.replacingOccurrences(of: "\r?\n", with: "\n ", options: .regularExpression)
|
||||
return "\(stamp) \(pad(level.rawValue.uppercased(), 5)) \(pad(String(pid), 5, left: true)) \(pad(scope, 9)) \(indented)\n"
|
||||
}
|
||||
|
||||
private static func pad(_ text: String, _ width: Int, left: Bool = false) -> String {
|
||||
let fill = String(repeating: " ", count: max(0, width - text.count))
|
||||
return left ? fill + text : text + fill
|
||||
}
|
||||
|
||||
private static let timestampFormatter: ISO8601DateFormatter = {
|
||||
let formatter = ISO8601DateFormatter()
|
||||
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
|
||||
return formatter
|
||||
}()
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import Foundation
|
||||
import os
|
||||
|
||||
public enum LogLevel: String, Sendable, Comparable {
|
||||
case debug, info, warn, error
|
||||
|
||||
private var rank: Int { [.debug: 0, .info: 1, .warn: 2, .error: 3][self] ?? 0 }
|
||||
public static func < (lhs: LogLevel, rhs: LogLevel) -> Bool { lhs.rank < rhs.rank }
|
||||
}
|
||||
|
||||
/// A destination besides the unified log, such as `FileLogger`.
|
||||
public protocol LogSink: Sendable {
|
||||
func write(level: LogLevel, scope: String, message: String)
|
||||
}
|
||||
|
||||
public enum Log {
|
||||
private static let logger = Logger(subsystem: "nl.blijnder.helder", category: "app")
|
||||
private static let sinkBox = OSAllocatedUnfairLock<LogSink?>(initialState: nil)
|
||||
|
||||
/// Installs the extra sink; nil removes it.
|
||||
public static func setSink(_ sink: LogSink?) {
|
||||
sinkBox.withLock { $0 = sink }
|
||||
}
|
||||
|
||||
public static func debug(_ scope: String, _ message: String) { write(.debug, scope, message) }
|
||||
public static func info(_ scope: String, _ message: String) { write(.info, scope, message) }
|
||||
public static func warn(_ scope: String, _ message: String) { write(.warn, scope, message) }
|
||||
public static func error(_ scope: String, _ message: String) { write(.error, scope, message) }
|
||||
|
||||
private static func write(_ level: LogLevel, _ scope: String, _ message: String) {
|
||||
let line = "[\(scope)] \(message)"
|
||||
switch level {
|
||||
case .debug: logger.debug("\(line, privacy: .public)")
|
||||
// Notice, not info: the unified log only persists notice and above.
|
||||
case .info: logger.notice("\(line, privacy: .public)")
|
||||
case .warn: logger.warning("\(line, privacy: .public)")
|
||||
case .error: logger.error("\(line, privacy: .public)")
|
||||
}
|
||||
sinkBox.withLock { $0 }?.write(level: level, scope: scope, message: message)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import Darwin
|
||||
import Foundation
|
||||
|
||||
/// Collects the exit status of a child we signalled, so it does not linger as a zombie.
|
||||
public enum ChildReaper {
|
||||
/// Waits for `pid` without blocking a thread, sends SIGKILL once `grace` has passed, and returns once it is reaped.
|
||||
///
|
||||
/// Stops at once when `pid` is not an unreaped child of ours (someone else reaped it), so a
|
||||
/// recycled pid is never signalled.
|
||||
public static func reap(_ pid: pid_t, grace: TimeInterval = 2) async {
|
||||
guard pid > 0 else { return }
|
||||
let deadline = Date().addingTimeInterval(grace)
|
||||
var killed = false
|
||||
while true {
|
||||
var status: Int32 = 0
|
||||
let result = waitpid(pid, &status, WNOHANG)
|
||||
if result == pid { return }
|
||||
if result == -1 && errno != EINTR { return }
|
||||
if result == 0 && !killed && Date() >= deadline {
|
||||
kill(pid, SIGKILL)
|
||||
killed = true
|
||||
}
|
||||
if Task.isCancelled { return }
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import Foundation
|
||||
|
||||
/// Finds command-line tools for a GUI app, whose PATH is only /usr/bin:/bin:/usr/sbin:/sbin.
|
||||
public struct ExecutableLocator: Sendable {
|
||||
/// Directories searched in order.
|
||||
public var directories: [String]
|
||||
|
||||
public init(directories: [String]) {
|
||||
self.directories = directories
|
||||
}
|
||||
|
||||
/// The app's own Helpers folder (where bundle.sh puts ripgrep), then PATH, then Homebrew.
|
||||
public static var standard: ExecutableLocator {
|
||||
var dirs: [String] = []
|
||||
dirs.append(Bundle.main.bundleURL.appendingPathComponent("Contents/Helpers").path)
|
||||
let path = ProcessInfo.processInfo.environment["PATH"] ?? "/usr/bin:/bin:/usr/sbin:/sbin"
|
||||
dirs += path.split(separator: ":").map(String.init)
|
||||
dirs += ["/opt/homebrew/bin", "/usr/local/bin"]
|
||||
var seen = Set<String>()
|
||||
return ExecutableLocator(directories: dirs.filter { seen.insert($0).inserted })
|
||||
}
|
||||
|
||||
/// The first executable file called `name`, or nil. A name with a slash is checked as given.
|
||||
public func locate(_ name: String) -> URL? {
|
||||
let fm = FileManager.default
|
||||
if name.contains("/") {
|
||||
return fm.isExecutableFile(atPath: name) ? URL(fileURLWithPath: name) : nil
|
||||
}
|
||||
for dir in directories {
|
||||
let candidate = (dir as NSString).appendingPathComponent(name)
|
||||
var isDir: ObjCBool = false
|
||||
if fm.fileExists(atPath: candidate, isDirectory: &isDir), !isDir.boolValue, fm.isExecutableFile(atPath: candidate) {
|
||||
return URL(fileURLWithPath: candidate)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import Foundation
|
||||
|
||||
/// Starts another Helder process, for a launch outside an app bundle (`swift run`).
|
||||
public enum InstanceLauncher {
|
||||
/// Passed as `-HelderProject <folder>`: AppKit reads a `-Key value` pair as a default, not as a file to open.
|
||||
public static func arguments(for root: URL?) -> [String] {
|
||||
root.map { ["-HelderProject", $0.path] } ?? []
|
||||
}
|
||||
|
||||
/// Runs `executable` on `root` (nil shows the launcher) and reaps it when it exits.
|
||||
/// `HELDER_PROJECT` is dropped from the child's environment, since it wins over the argument.
|
||||
public static func spawn(_ executable: URL, root: URL?,
|
||||
environment: [String: String] = ProcessInfo.processInfo.environment) throws {
|
||||
var environment = environment
|
||||
environment["HELDER_PROJECT"] = nil
|
||||
let process = Process()
|
||||
process.executableURL = executable
|
||||
process.arguments = arguments(for: root)
|
||||
process.environment = environment
|
||||
let id = ObjectIdentifier(process)
|
||||
process.terminationHandler = { _ in children.remove(id) }
|
||||
children.insert(process)
|
||||
do {
|
||||
try process.run()
|
||||
} catch {
|
||||
children.remove(id)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private static let children = Children()
|
||||
|
||||
/// Keeps each child's `Process` alive until it exits, so its exit status is always collected.
|
||||
private final class Children: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var running: [ObjectIdentifier: Process] = [:]
|
||||
|
||||
func insert(_ process: Process) {
|
||||
lock.withLock { running[ObjectIdentifier(process)] = process }
|
||||
}
|
||||
|
||||
func remove(_ id: ObjectIdentifier) {
|
||||
_ = lock.withLock { running.removeValue(forKey: id) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import Foundation
|
||||
|
||||
public struct ProcessResult: Sendable, Equatable {
|
||||
public var exitCode: Int32
|
||||
public var stdout: String
|
||||
public var stderr: String
|
||||
|
||||
public init(exitCode: Int32, stdout: String, stderr: String) {
|
||||
self.exitCode = exitCode
|
||||
self.stdout = stdout
|
||||
self.stderr = stderr
|
||||
}
|
||||
|
||||
public var succeeded: Bool { exitCode == 0 }
|
||||
}
|
||||
|
||||
public enum ProcessRunnerError: Error, Equatable {
|
||||
case executableNotFound(String)
|
||||
case launchFailed(String)
|
||||
}
|
||||
|
||||
/// Runs a command to completion. Services depend on this protocol so tests can script the output.
|
||||
public protocol ProcessRunning: Sendable {
|
||||
/// Runs `executable` (a name looked up on the search path, or a path) and collects its output.
|
||||
/// A non-zero exit is a normal result, not an error; `environment: nil` inherits ours.
|
||||
func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?) async throws -> ProcessResult
|
||||
}
|
||||
|
||||
extension ProcessRunning {
|
||||
public func run(_ executable: String, _ arguments: [String], in directory: URL? = nil) async throws -> ProcessResult {
|
||||
try await run(executable, arguments: arguments, in: directory, environment: nil)
|
||||
}
|
||||
}
|
||||
|
||||
public struct ProcessRunner: ProcessRunning {
|
||||
public let locator: ExecutableLocator
|
||||
|
||||
public init(locator: ExecutableLocator = .standard) {
|
||||
self.locator = locator
|
||||
}
|
||||
|
||||
public func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?) async throws -> ProcessResult {
|
||||
guard let url = locator.locate(executable) else { throw ProcessRunnerError.executableNotFound(executable) }
|
||||
let job = Job(url: url, arguments: arguments, directory: directory, environment: environment)
|
||||
return try await withTaskCancellationHandler {
|
||||
try await withCheckedThrowingContinuation { continuation in
|
||||
job.start(continuation)
|
||||
}
|
||||
} onCancel: {
|
||||
job.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One child process. Both pipes are drained on their own threads, because a child that
|
||||
/// fills one pipe while we wait on the other would deadlock.
|
||||
private final class Job: @unchecked Sendable {
|
||||
private let process = Process()
|
||||
private let lock = NSLock()
|
||||
private var cancelled = false
|
||||
|
||||
init(url: URL, arguments: [String], directory: URL?, environment: [String: String]?) {
|
||||
process.executableURL = url
|
||||
process.arguments = arguments
|
||||
if let directory { process.currentDirectoryURL = directory }
|
||||
if let environment { process.environment = environment }
|
||||
process.standardInput = FileHandle.nullDevice
|
||||
}
|
||||
|
||||
func start(_ continuation: CheckedContinuation<ProcessResult, Error>) {
|
||||
let out = Pipe()
|
||||
let err = Pipe()
|
||||
process.standardOutput = out
|
||||
process.standardError = err
|
||||
|
||||
let group = DispatchGroup()
|
||||
var outData = Data()
|
||||
var errData = Data()
|
||||
group.enter()
|
||||
process.terminationHandler = { _ in group.leave() }
|
||||
|
||||
lock.lock()
|
||||
let alreadyCancelled = cancelled
|
||||
do {
|
||||
if !alreadyCancelled { try process.run() }
|
||||
} catch {
|
||||
lock.unlock()
|
||||
continuation.resume(throwing: ProcessRunnerError.launchFailed(error.localizedDescription))
|
||||
return
|
||||
}
|
||||
lock.unlock()
|
||||
if alreadyCancelled {
|
||||
continuation.resume(throwing: CancellationError())
|
||||
return
|
||||
}
|
||||
|
||||
group.enter()
|
||||
DispatchQueue.global().async {
|
||||
outData = out.fileHandleForReading.readDataToEndOfFile()
|
||||
group.leave()
|
||||
}
|
||||
group.enter()
|
||||
DispatchQueue.global().async {
|
||||
errData = err.fileHandleForReading.readDataToEndOfFile()
|
||||
group.leave()
|
||||
}
|
||||
group.notify(queue: .global()) { [self, process] in
|
||||
if wasCancelled {
|
||||
continuation.resume(throwing: CancellationError())
|
||||
return
|
||||
}
|
||||
continuation.resume(returning: ProcessResult(
|
||||
exitCode: process.terminationStatus,
|
||||
stdout: String(decoding: outData, as: UTF8.self),
|
||||
stderr: String(decoding: errData, as: UTF8.self)
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
private var wasCancelled: Bool {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return cancelled
|
||||
}
|
||||
|
||||
func cancel() {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
cancelled = true
|
||||
if process.isRunning { process.terminate() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
|
||||
public protocol ConfigServicing: Sendable {
|
||||
/// Rewrites `config.default.json`, re-reads `config.json`, and returns the effective config.
|
||||
@discardableResult
|
||||
func resolve() async -> HelderConfig
|
||||
/// The last resolved config; the defaults before the first `resolve()`.
|
||||
func current() async -> HelderConfig
|
||||
}
|
||||
|
||||
public actor ConfigService: ConfigServicing {
|
||||
public nonisolated let root: URL
|
||||
private var config = HelderConfig.defaults
|
||||
|
||||
public init(root: URL) {
|
||||
self.root = root
|
||||
}
|
||||
|
||||
public nonisolated var folder: URL { root.appendingPathComponent(HelderConfig.folderName) }
|
||||
public nonisolated var overridesURL: URL { folder.appendingPathComponent(HelderConfig.overridesFileName) }
|
||||
|
||||
/// A read-only or missing project folder yields the defaults instead of an error.
|
||||
@discardableResult
|
||||
public func resolve() async -> HelderConfig {
|
||||
let fm = FileManager.default
|
||||
do {
|
||||
try fm.createDirectory(at: folder, withIntermediateDirectories: true)
|
||||
try HelderConfig.defaultsJSON().write(to: folder.appendingPathComponent(HelderConfig.defaultsFileName))
|
||||
let gitignore = folder.appendingPathComponent(".gitignore")
|
||||
if (try? String(contentsOf: gitignore, encoding: .utf8)) != HelderConfig.gitignoreBody {
|
||||
try Data(HelderConfig.gitignoreBody.utf8).write(to: gitignore)
|
||||
}
|
||||
} catch {
|
||||
Log.warn("config", "cannot write \(folder.path): \(error.localizedDescription)")
|
||||
}
|
||||
config = HelderConfig.resolved(overrides: try? Data(contentsOf: overridesURL))
|
||||
return config
|
||||
}
|
||||
|
||||
public func current() async -> HelderConfig {
|
||||
config
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import Foundation
|
||||
|
||||
public protocol NotesServicing: Sendable {
|
||||
/// The note's text; "" when the project has none yet.
|
||||
func read() async -> String
|
||||
func write(_ text: String) async throws
|
||||
}
|
||||
|
||||
/// The note is a plain `.notes.txt` in the project root, not JSON and not in `.helder/`,
|
||||
/// so it stays readable and editable outside Helder.
|
||||
public struct NotesService: NotesServicing {
|
||||
public static let fileName = ".notes.txt"
|
||||
public let root: URL
|
||||
|
||||
public init(root: URL) {
|
||||
self.root = root
|
||||
}
|
||||
|
||||
private var url: URL { root.appendingPathComponent(Self.fileName) }
|
||||
|
||||
public func read() async -> String {
|
||||
(try? String(contentsOf: url, encoding: .utf8)) ?? ""
|
||||
}
|
||||
|
||||
public func write(_ text: String) async throws {
|
||||
try Data(text.utf8).write(to: url, options: .atomic)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
|
||||
public enum ProjectLocator {
|
||||
/// The folder a fresh window opens: `$HELDER_PROJECT`, else the first directory argument; nil shows the launcher.
|
||||
/// A bare "." is ignored, so a development launch lands on the launcher too.
|
||||
public static func initialRoot(environment: [String: String] = ProcessInfo.processInfo.environment,
|
||||
arguments: [String] = CommandLine.arguments) -> URL? {
|
||||
if let env = environment["HELDER_PROJECT"], isDirectory(env) {
|
||||
return URL(fileURLWithPath: env).standardizedFileURL
|
||||
}
|
||||
let candidate = arguments.dropFirst().first { $0 != "." && !$0.hasPrefix("-") && isDirectory($0) }
|
||||
return candidate.map { URL(fileURLWithPath: $0).standardizedFileURL }
|
||||
}
|
||||
|
||||
/// The folder name, used for recents and the Explorer header.
|
||||
public static func name(of root: URL) -> String {
|
||||
root.lastPathComponent.isEmpty ? root.path : root.lastPathComponent
|
||||
}
|
||||
|
||||
/// The window title: `APP_NAME` from the project's `.env`, else the folder name.
|
||||
public static func title(of root: URL) -> String {
|
||||
let env = try? String(contentsOf: root.appendingPathComponent(".env"), encoding: .utf8)
|
||||
return ProjectTitle.title(folderName: name(of: root), envContents: env)
|
||||
}
|
||||
|
||||
private static func isDirectory(_ path: String) -> Bool {
|
||||
var isDir: ObjCBool = false
|
||||
return FileManager.default.fileExists(atPath: path, isDirectory: &isDir) && isDir.boolValue
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
|
||||
public protocol RecentProjectsStoring: Sendable {
|
||||
/// Newest first; projects whose folder no longer exists are left out.
|
||||
func list() async -> [RecentProject]
|
||||
/// Moves a project folder to the front of the list.
|
||||
func add(_ path: String) async
|
||||
}
|
||||
|
||||
/// Machine-wide list in `~/Library/Application Support/Helder/recent-projects.json`.
|
||||
public struct RecentProjectsStore: RecentProjectsStoring {
|
||||
public let fileURL: URL
|
||||
|
||||
public init(fileURL: URL = RecentProjectsStore.defaultURL) {
|
||||
self.fileURL = fileURL
|
||||
}
|
||||
|
||||
public static var defaultURL: URL {
|
||||
let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
|
||||
?? URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Library/Application Support")
|
||||
return support.appendingPathComponent("Helder/recent-projects.json")
|
||||
}
|
||||
|
||||
public func list() async -> [RecentProject] {
|
||||
guard let data = try? Data(contentsOf: fileURL),
|
||||
let list = try? JSONDecoder().decode([RecentProject].self, from: data) else { return [] }
|
||||
return Array(list.filter { FileManager.default.fileExists(atPath: $0.path) }.prefix(RecentLists.maxProjects))
|
||||
}
|
||||
|
||||
public func add(_ path: String) async {
|
||||
let abs = URL(fileURLWithPath: path).standardizedFileURL.path
|
||||
let entry = RecentProject(path: abs, name: PathUtils.basename(abs).isEmpty ? abs : PathUtils.basename(abs))
|
||||
let next = RecentLists.pushing(entry, onto: await list())
|
||||
do {
|
||||
try FileManager.default.createDirectory(at: fileURL.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
let encoder = JSONEncoder()
|
||||
encoder.outputFormatting = [.prettyPrinted, .withoutEscapingSlashes]
|
||||
try encoder.encode(next).write(to: fileURL, options: .atomic)
|
||||
} catch {
|
||||
Log.warn("recent", "cannot save recent projects: \(error.localizedDescription)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public protocol RecentFilesStoring: Sendable {
|
||||
/// Recently opened files of this project, newest first.
|
||||
func load() async -> [String]
|
||||
func save(_ paths: [String]) async
|
||||
}
|
||||
|
||||
/// Per-project list in `.helder/recent.json`; drives the ⌘↑/⌘↓ recent-files navigator.
|
||||
public struct RecentFilesStore: RecentFilesStoring {
|
||||
public let fileURL: URL
|
||||
|
||||
public init(root: URL) {
|
||||
fileURL = root.appendingPathComponent(HelderConfig.folderName).appendingPathComponent(RecentLists.recentFilesName)
|
||||
}
|
||||
|
||||
public func load() async -> [String] {
|
||||
guard let data = try? Data(contentsOf: fileURL),
|
||||
let list = try? JSONDecoder().decode([String].self, from: data) else { return [] }
|
||||
return Array(list.prefix(RecentLists.maxFiles))
|
||||
}
|
||||
|
||||
public func save(_ paths: [String]) async {
|
||||
do {
|
||||
try FileManager.default.createDirectory(at: fileURL.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
let encoder = JSONEncoder()
|
||||
encoder.outputFormatting = [.prettyPrinted, .withoutEscapingSlashes]
|
||||
try encoder.encode(Array(paths.prefix(RecentLists.maxFiles))).write(to: fileURL, options: .atomic)
|
||||
} catch {
|
||||
Log.warn("recent", "cannot save recent files: \(error.localizedDescription)")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
|
||||
public protocol SessionStoring: Sendable {
|
||||
func loadSession(root: String) -> SessionState?
|
||||
func saveSession(_ session: SessionState, root: String)
|
||||
func loadLayout() -> LayoutState
|
||||
func saveLayout(_ layout: LayoutState)
|
||||
}
|
||||
|
||||
/// Never throws: storage that cannot be read gives the defaults, one that cannot be written is skipped.
|
||||
public struct SessionStore: SessionStoring, @unchecked Sendable {
|
||||
private let defaults: UserDefaults
|
||||
|
||||
public init(defaults: UserDefaults = .standard) {
|
||||
self.defaults = defaults
|
||||
}
|
||||
|
||||
public func loadSession(root: String) -> SessionState? {
|
||||
defaults.data(forKey: SessionState.key(root: root)).flatMap { try? JSONDecoder().decode(SessionState.self, from: $0) }
|
||||
}
|
||||
|
||||
public func saveSession(_ session: SessionState, root: String) {
|
||||
if let data = try? JSONEncoder().encode(session) { defaults.set(data, forKey: SessionState.key(root: root)) }
|
||||
}
|
||||
|
||||
public func loadLayout() -> LayoutState {
|
||||
guard defaults.object(forKey: LayoutState.key) != nil else { return LayoutState() }
|
||||
return LayoutState(agentFraction: defaults.double(forKey: LayoutState.key))
|
||||
}
|
||||
|
||||
public func saveLayout(_ layout: LayoutState) {
|
||||
defaults.set(layout.agentFraction, forKey: LayoutState.key)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
|
||||
/// Which files a scan may enter: ripgrep's `!glob` names plus the project's file settings.
|
||||
struct ScanFilter: Sendable, Equatable {
|
||||
var base: [String]
|
||||
var files: HelderConfig.Files
|
||||
}
|
||||
|
||||
/// One line search, answered the same way by ripgrep and by the walk.
|
||||
struct LineQuery: Sendable, Equatable {
|
||||
enum Pattern: Sendable, Equatable {
|
||||
/// Fixed string; case-insensitive unless it holds an uppercase letter.
|
||||
case smartCaseLiteral(String)
|
||||
/// Case-sensitive regular expression in the subset ripgrep and ICU share.
|
||||
case regex(String)
|
||||
/// Case-sensitive literal that must stand as a whole word.
|
||||
case word(String)
|
||||
}
|
||||
|
||||
var pattern: Pattern
|
||||
/// Only files with this extension, e.g. "php".
|
||||
var fileExtension: String? = nil
|
||||
var maxPerFile: Int? = nil
|
||||
var maxColumns: Int? = nil
|
||||
/// Lets the walk stop early; ripgrep has no such flag, so callers still cap themselves.
|
||||
var maxFiles: Int? = nil
|
||||
}
|
||||
|
||||
/// Lists and searches project files; the relative paths use "/".
|
||||
protocol ProjectScanning: Sendable {
|
||||
/// Relative paths of the files under `scope` (nil is the root), sorted.
|
||||
func files(under scope: String?, filter: ScanFilter) async -> [String]
|
||||
/// Matching lines with absolute paths, grouped per file and in line order within a file.
|
||||
func matches(_ query: LineQuery, filter: ScanFilter) async -> [RipgrepMatch]
|
||||
}
|
||||
|
||||
enum ProjectScanner {
|
||||
/// `$RG_BINARY` when it names an executable, else `rg` through the locator.
|
||||
static func ripgrep(locator: ExecutableLocator, environment: [String: String]) -> URL? {
|
||||
if let override = environment["RG_BINARY"], !override.isEmpty,
|
||||
FileManager.default.isExecutableFile(atPath: override) {
|
||||
return URL(fileURLWithPath: override)
|
||||
}
|
||||
return locator.locate("rg")
|
||||
}
|
||||
|
||||
static func make(root: URL, runner: ProcessRunning, locator: ExecutableLocator,
|
||||
environment: [String: String]) -> ProjectScanning {
|
||||
if let binary = ripgrep(locator: locator, environment: environment) {
|
||||
return RipgrepScanner(root: root, binary: binary, runner: runner)
|
||||
}
|
||||
return WalkScanner(root: root, runner: runner)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ripgrep
|
||||
|
||||
struct RipgrepScanner: ProjectScanning {
|
||||
let root: URL
|
||||
let binary: URL
|
||||
let runner: ProcessRunning
|
||||
|
||||
func files(under scope: String?, filter: ScanFilter) async -> [String] {
|
||||
let target = scope.flatMap { $0.isEmpty ? nil : root.appendingPathComponent($0).path } ?? root.path
|
||||
let args = Self.fileArguments(filter: filter, target: target)
|
||||
guard let result = await run(args) else { return [] }
|
||||
return result.stdout.split(separator: "\n")
|
||||
.map { RipgrepJSON.relativePath(String($0), root: root.path) }
|
||||
.sorted()
|
||||
}
|
||||
|
||||
func matches(_ query: LineQuery, filter: ScanFilter) async -> [RipgrepMatch] {
|
||||
guard let result = await run(Self.searchArguments(query, filter: filter, target: root.path)) else { return [] }
|
||||
return result.stdout.split(separator: "\n").compactMap { RipgrepJSON.parseLine(String($0)) }
|
||||
}
|
||||
|
||||
static func fileArguments(filter: ScanFilter, target: String) -> [String] {
|
||||
["--files", "--hidden"] + IgnoreRules.ripgrepArguments(files: filter.files, base: filter.base) + ["--", target]
|
||||
}
|
||||
|
||||
static func searchArguments(_ query: LineQuery, filter: ScanFilter, target: String) -> [String] {
|
||||
var args = ["--json"]
|
||||
let needle: String
|
||||
switch query.pattern {
|
||||
case .smartCaseLiteral(let text):
|
||||
args += ["--fixed-strings", "--smart-case"]
|
||||
needle = text
|
||||
case .regex(let pattern):
|
||||
needle = pattern
|
||||
case .word(let text):
|
||||
args += ["--fixed-strings", "--word-regexp"]
|
||||
needle = text
|
||||
}
|
||||
args.append("--hidden")
|
||||
if let max = query.maxPerFile { args += ["--max-count", String(max)] }
|
||||
if let columns = query.maxColumns { args += ["--max-columns", String(columns)] }
|
||||
if let ext = query.fileExtension { args += ["--glob", "*." + ext] }
|
||||
args += IgnoreRules.ripgrepArguments(files: filter.files, base: filter.base)
|
||||
return args + ["-e", needle, "--", target]
|
||||
}
|
||||
|
||||
/// Exit 1 means "nothing found" and 2 means "some files were unreadable"; both keep their output.
|
||||
private func run(_ arguments: [String]) async -> ProcessResult? {
|
||||
do {
|
||||
return try await runner.run(binary.path, arguments: arguments, in: root, environment: nil)
|
||||
} catch {
|
||||
Log.error("search", "ripgrep failed: \(error)")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - walk
|
||||
|
||||
/// The ripgrep fallback: walks the tree in name order, never follows symlinks, and skips
|
||||
/// binary files and files over `maxFileBytes` when searching.
|
||||
struct WalkScanner: ProjectScanning {
|
||||
let root: URL
|
||||
let runner: ProcessRunning
|
||||
var maxFileBytes = FileLimits.maxIndexedFileBytes
|
||||
|
||||
func files(under scope: String?, filter: ScanFilter) async -> [String] {
|
||||
var out: [String] = []
|
||||
await walk(from: scope ?? "", filter: filter) { rel, _ in
|
||||
out.append(rel)
|
||||
return true
|
||||
}
|
||||
return out.sorted()
|
||||
}
|
||||
|
||||
func matches(_ query: LineQuery, filter: ScanFilter) async -> [RipgrepMatch] {
|
||||
guard let matcher = LineMatcher(query.pattern) else { return [] }
|
||||
var out: [RipgrepMatch] = []
|
||||
var filesWithHits = 0
|
||||
await walk(from: "", filter: filter) { rel, url in
|
||||
if let ext = query.fileExtension, (rel as NSString).pathExtension != ext { return true }
|
||||
guard let text = readText(url) else { return true }
|
||||
var hits = 0
|
||||
var lineNumber = 0
|
||||
for line in text.split(separator: "\n", omittingEmptySubsequences: false) {
|
||||
lineNumber += 1
|
||||
guard let offset = matcher.firstByteOffset(in: line) else { continue }
|
||||
out.append(RipgrepMatch(path: root.path + "/" + rel, line: lineNumber, text: String(line), byteOffset: offset))
|
||||
hits += 1
|
||||
if let max = query.maxPerFile, hits >= max { break }
|
||||
}
|
||||
if hits > 0 { filesWithHits += 1 }
|
||||
if let max = query.maxFiles, filesWithHits >= max { return false }
|
||||
return true
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
private func readText(_ url: URL) -> String? {
|
||||
guard let size = (try? url.resourceValues(forKeys: [.fileSizeKey]))?.fileSize, size <= maxFileBytes,
|
||||
let data = try? Data(contentsOf: url), !FileLimits.looksBinary(data) else { return nil }
|
||||
return String(decoding: data, as: UTF8.self)
|
||||
}
|
||||
|
||||
/// Calls `visit` for every file in scope until it returns false.
|
||||
private func walk(from scope: String, filter: ScanFilter, visit: (String, URL) -> Bool) async {
|
||||
let base = Set(filter.base)
|
||||
let excludes = filter.files.exclude.filter { !$0.isEmpty }
|
||||
let gitIgnored = filter.files.followGitignore ? await ignoredByGit() : []
|
||||
|
||||
func skipped(_ rel: String, name: String, isDirectory: Bool) -> Bool {
|
||||
if base.contains(name) { return true }
|
||||
if excludes.contains(where: { IgnoreRules.globMatches($0, path: rel) }) { return true }
|
||||
return gitIgnored.contains(isDirectory ? rel + "/" : rel)
|
||||
}
|
||||
|
||||
var stack: [String] = [scope]
|
||||
while let dir = stack.popLast() {
|
||||
let url = dir.isEmpty ? root : root.appendingPathComponent(dir)
|
||||
var subdirectories: [String] = []
|
||||
for entry in DirectoryListing.entries(of: url) {
|
||||
let rel = PathUtils.join(dir, entry.name)
|
||||
if skipped(rel, name: entry.name, isDirectory: entry.kind == .directory) { continue }
|
||||
switch entry.kind {
|
||||
case .directory: subdirectories.append(rel)
|
||||
case .file: if !visit(rel, entry.url) { return }
|
||||
}
|
||||
}
|
||||
stack += subdirectories.reversed()
|
||||
}
|
||||
}
|
||||
|
||||
/// Untracked paths git ignores, folders with a trailing slash; empty outside a repository.
|
||||
private func ignoredByGit() async -> Set<String> {
|
||||
let args = ["ls-files", "-z", "--others", "--ignored", "--exclude-standard", "--directory"]
|
||||
guard let result = try? await runner.run("git", args, in: root), result.succeeded else { return [] }
|
||||
return Set(result.stdout.split(separator: "\0").map(String.init))
|
||||
}
|
||||
}
|
||||
|
||||
/// Finds the first match in one line and reports its UTF-8 offset, the unit ripgrep uses.
|
||||
private struct LineMatcher {
|
||||
private enum Kind {
|
||||
case literal(String, String.CompareOptions)
|
||||
case regex(NSRegularExpression)
|
||||
}
|
||||
|
||||
private let kind: Kind
|
||||
|
||||
init?(_ pattern: LineQuery.Pattern) {
|
||||
switch pattern {
|
||||
case .smartCaseLiteral(let text):
|
||||
guard !text.isEmpty else { return nil }
|
||||
let caseSensitive = text.contains { $0.isUppercase }
|
||||
kind = .literal(text, caseSensitive ? [.literal] : [.literal, .caseInsensitive])
|
||||
case .regex(let pattern):
|
||||
guard let regex = try? NSRegularExpression(pattern: pattern) else { return nil }
|
||||
kind = .regex(regex)
|
||||
case .word(let text):
|
||||
let escaped = NSRegularExpression.escapedPattern(for: text)
|
||||
guard let regex = try? NSRegularExpression(pattern: "(?<!\\w)" + escaped + "(?!\\w)") else { return nil }
|
||||
kind = .regex(regex)
|
||||
}
|
||||
}
|
||||
|
||||
func firstByteOffset(in line: Substring) -> Int? {
|
||||
let text = String(line)
|
||||
switch kind {
|
||||
case .literal(let needle, let options):
|
||||
guard let range = text.range(of: needle, options: options) else { return nil }
|
||||
return text.utf8.distance(from: text.startIndex, to: range.lowerBound)
|
||||
case .regex(let regex):
|
||||
let whole = NSRange(text.startIndex..., in: text)
|
||||
guard let match = regex.firstMatch(in: text, range: whole),
|
||||
let range = Range(match.range, in: text) else { return nil }
|
||||
return text.utf8.distance(from: text.startIndex, to: range.lowerBound)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
|
||||
public protocol SearchServicing: Sendable {
|
||||
/// False when no ripgrep binary was found; callers then fall back to a walk.
|
||||
func isAvailable() async -> Bool
|
||||
/// Fixed-string, smart-case content search; [] below `SearchLimits.minContentQuery` characters.
|
||||
func searchContent(_ query: String) async -> [ContentGroup]
|
||||
/// Relative paths of every project file, dotfiles included, honouring gitignore and excludes.
|
||||
/// `directory` limits the list to one subtree; paths stay relative to the root.
|
||||
func listFiles(under directory: String?) async -> [String]
|
||||
}
|
||||
|
||||
/// Answers through ripgrep when it can be found, else through a walk with the same filters.
|
||||
public struct RipgrepSearchService: SearchServicing {
|
||||
public let root: URL
|
||||
private let config: ConfigServicing
|
||||
private let runner: ProcessRunning
|
||||
private let locator: ExecutableLocator
|
||||
private let environment: [String: String]
|
||||
|
||||
/// `environment` is read for `RG_BINARY`, which points at a ripgrep outside the search path.
|
||||
public init(root: URL, config: ConfigServicing, runner: ProcessRunning = ProcessRunner(), locator: ExecutableLocator = .standard,
|
||||
environment: [String: String] = ProcessInfo.processInfo.environment) {
|
||||
self.root = root
|
||||
self.config = config
|
||||
self.runner = runner
|
||||
self.locator = locator
|
||||
self.environment = environment
|
||||
}
|
||||
|
||||
public func isAvailable() async -> Bool {
|
||||
ProjectScanner.ripgrep(locator: locator, environment: environment) != nil
|
||||
}
|
||||
|
||||
public func searchContent(_ query: String) async -> [ContentGroup] {
|
||||
guard query.trimmingCharacters(in: .whitespacesAndNewlines).count >= SearchLimits.minContentQuery else { return [] }
|
||||
let search = LineQuery(pattern: .smartCaseLiteral(query), maxPerFile: SearchLimits.maxHitsPerFile,
|
||||
maxColumns: 2000, maxFiles: SearchLimits.maxFiles)
|
||||
var grouper = ContentGrouper(root: root.path)
|
||||
for match in await scanner.matches(search, filter: await filter()) {
|
||||
grouper.add(match)
|
||||
}
|
||||
return grouper.groups
|
||||
}
|
||||
|
||||
public func listFiles(under directory: String?) async -> [String] {
|
||||
if let directory, !directory.isEmpty, !isInsideRoot(directory) { return [] }
|
||||
return await scanner.files(under: directory, filter: await filter())
|
||||
}
|
||||
|
||||
private var scanner: ProjectScanning {
|
||||
ProjectScanner.make(root: root, runner: runner, locator: locator, environment: environment)
|
||||
}
|
||||
|
||||
private func filter() async -> ScanFilter {
|
||||
ScanFilter(base: IgnoreRules.ripgrepBaseIgnore, files: await config.current().files)
|
||||
}
|
||||
|
||||
private func isInsideRoot(_ path: String) -> Bool {
|
||||
let base = root.standardizedFileURL.path
|
||||
let target = root.appendingPathComponent(path).standardizedFileURL.path
|
||||
return target.hasPrefix(base + "/")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
|
||||
public protocol SymbolServicing: Sendable {
|
||||
/// Every declared PHP class-like name; decides which tokens ⌘-click may underline.
|
||||
func names() async -> Set<String>
|
||||
/// Declarations of `name` plus every reference, grouped by file.
|
||||
func lookup(_ name: String) async -> SymbolLookup
|
||||
/// Drops the index after a file change; the next caller rebuilds it.
|
||||
func invalidate() async
|
||||
}
|
||||
|
||||
/// Ripgrep-backed, with the same walk fallback as search when ripgrep is missing.
|
||||
public actor SymbolService: SymbolServicing {
|
||||
public nonisolated let root: URL
|
||||
private let runner: ProcessRunning
|
||||
private let config: ConfigServicing
|
||||
private let locator: ExecutableLocator
|
||||
private let environment: [String: String]
|
||||
|
||||
private var index: [String: [SymbolDef]]?
|
||||
private var building: Task<[String: [SymbolDef]], Never>?
|
||||
/// Bumped by `invalidate()`, so a build that started before a file change is not cached.
|
||||
private var generation = 0
|
||||
|
||||
/// `environment` is read for `RG_BINARY`, which points at a ripgrep outside the search path.
|
||||
public init(root: URL, config: ConfigServicing, runner: ProcessRunning = ProcessRunner(),
|
||||
locator: ExecutableLocator = .standard, environment: [String: String] = ProcessInfo.processInfo.environment) {
|
||||
self.root = root
|
||||
self.config = config
|
||||
self.runner = runner
|
||||
self.locator = locator
|
||||
self.environment = environment
|
||||
}
|
||||
|
||||
/// Builds lazily on first use; concurrent callers share one build. Two ripgrep passes over
|
||||
/// `*.php` (vendor included): `PHPSymbols.declarationPattern`, then `traitUsePattern`, where
|
||||
/// a trait belongs to the nearest declaration above it in the same file.
|
||||
public func names() async -> Set<String> {
|
||||
Set(await currentIndex().keys)
|
||||
}
|
||||
|
||||
/// Word-regexp ripgrep over `*.php` without vendor; drops import lines and the declaration
|
||||
/// lines themselves; caps at `SymbolLimits.maxReferenceFiles` files. Non-identifiers return empty.
|
||||
public func lookup(_ name: String) async -> SymbolLookup {
|
||||
guard PHPSymbols.isIdentifier(name) else { return .empty(name) }
|
||||
let definitions = PHPSymbols.sortDefinitions(await currentIndex()[name] ?? [])
|
||||
let declared = Set(definitions.map { "\($0.path):\($0.line)" })
|
||||
let query = LineQuery(pattern: .word(name), fileExtension: "php")
|
||||
let matches = await scanner.matches(query, filter: await filter(base: IgnoreRules.symbolReferenceIgnore))
|
||||
|
||||
var groups: [RefGroup] = []
|
||||
var groupIndex: [String: Int] = [:]
|
||||
var count = 0
|
||||
for match in matches {
|
||||
let path = RipgrepJSON.relativePath(match.path, root: root.path)
|
||||
if declared.contains("\(path):\(match.line)") || PHPSymbols.isImportLine(match.text) { continue }
|
||||
let hit = Self.hit(match)
|
||||
if let i = groupIndex[path] {
|
||||
groups[i].hits.append(hit)
|
||||
} else {
|
||||
guard groups.count < SymbolLimits.maxReferenceFiles else { continue }
|
||||
groupIndex[path] = groups.count
|
||||
groups.append(RefGroup(path: path, hits: [hit]))
|
||||
}
|
||||
count += 1
|
||||
}
|
||||
return SymbolLookup(name: name, definitions: definitions, references: groups, referenceCount: count)
|
||||
}
|
||||
|
||||
public func invalidate() async {
|
||||
index = nil
|
||||
building = nil
|
||||
generation += 1
|
||||
}
|
||||
|
||||
private func currentIndex() async -> [String: [SymbolDef]] {
|
||||
if let index { return index }
|
||||
if let building { return await building.value }
|
||||
let started = generation
|
||||
let task = Task { await self.build() }
|
||||
building = task
|
||||
let built = await task.value
|
||||
if generation == started {
|
||||
index = built
|
||||
building = nil
|
||||
}
|
||||
return built
|
||||
}
|
||||
|
||||
private func build() async -> [String: [SymbolDef]] {
|
||||
let started = Date()
|
||||
let filter = await filter(base: IgnoreRules.symbolDeclarationIgnore)
|
||||
let scanner = self.scanner
|
||||
var defs: [SymbolDef] = []
|
||||
var defsByFile: [String: [Int]] = [:]
|
||||
var namespaces: [String: String] = [:]
|
||||
|
||||
// A file's matches arrive together and in line order, and `namespace` precedes the
|
||||
// declarations it covers, so the last namespace seen is the right one.
|
||||
let declarations = await scanner.matches(LineQuery(pattern: .regex(PHPSymbols.declarationPattern), fileExtension: "php"), filter: filter)
|
||||
for match in declarations {
|
||||
let path = RipgrepJSON.relativePath(match.path, root: root.path)
|
||||
if let namespace = PHPSymbols.parseNamespace(match.text) {
|
||||
namespaces[path] = namespace
|
||||
continue
|
||||
}
|
||||
guard let parsed = PHPSymbols.parseDeclaration(match.text) else { continue }
|
||||
defsByFile[path, default: []].append(defs.count)
|
||||
defs.append(SymbolDef(name: parsed.name, path: path, line: match.line, kind: parsed.kind,
|
||||
namespace: namespaces[path] ?? "", parents: parsed.parents, interfaces: parsed.interfaces))
|
||||
}
|
||||
|
||||
let traitUses = await scanner.matches(LineQuery(pattern: .regex(PHPSymbols.traitUsePattern), fileExtension: "php"), filter: filter)
|
||||
for match in traitUses {
|
||||
let traits = PHPSymbols.parseTraitUse(match.text)
|
||||
let path = RipgrepJSON.relativePath(match.path, root: root.path)
|
||||
let candidates = (defsByFile[path] ?? []).filter { defs[$0].line < match.line }
|
||||
guard !traits.isEmpty, let owner = candidates.max(by: { defs[$0].line < defs[$1].line }) else { continue }
|
||||
for trait in traits where !defs[owner].traits.contains(trait) {
|
||||
defs[owner].traits.append(trait)
|
||||
}
|
||||
}
|
||||
let byName = Dictionary(grouping: defs, by: \.name)
|
||||
Log.info("symbols", "index built: \(byName.count) classes in \(Int(Date().timeIntervalSince(started) * 1000)) ms")
|
||||
return byName
|
||||
}
|
||||
|
||||
private var scanner: ProjectScanning {
|
||||
ProjectScanner.make(root: root, runner: runner, locator: locator, environment: environment)
|
||||
}
|
||||
|
||||
private func filter(base: [String]) async -> ScanFilter {
|
||||
ScanFilter(base: base, files: await config.current().files)
|
||||
}
|
||||
|
||||
/// A reference hit; ripgrep's byte offset becomes a UTF-16 offset clamped to the capped line.
|
||||
private static func hit(_ match: RipgrepMatch) -> ContentHit {
|
||||
let text = String(match.text.prefix(SymbolLimits.maxLineLength))
|
||||
let bytes = Array(match.text.utf8.prefix(match.byteOffset))
|
||||
let offset = String(decoding: bytes, as: UTF8.self).utf16.count
|
||||
return ContentHit(line: match.line, text: text, matchOffset: min(offset, text.utf16.count))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user