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,217 @@
import CoreServices
import Foundation
import HelderCore
@testable import HelderServices
import Testing
/// Collects watcher events from any queue.
private final class EventLog: @unchecked Sendable {
private let lock = NSLock()
private var events: [WatchEvent] = []
func append(_ event: WatchEvent) { lock.withLock { events.append(event) } }
func count(_ event: WatchEvent) -> Int { lock.withLock { events.filter { $0 == event }.count } }
func clear() { lock.withLock { events.removeAll() } }
}
/// Real FSEvents against temp folders; the waits are generous so a busy machine does not fail them.
@Suite(.serialized) struct FSEventsWatcherTests {
private let debounce = WatchDebounce(project: 0.3, git: 0.2, config: 0.1)
/// Starts a watcher and lets FSEvents settle so setup writes do not leak into the test.
private func watch(_ root: URL) async -> (FSEventsWatcher, EventLog) {
let log = EventLog()
let watcher = FSEventsWatcher(debounce: debounce)
watcher.start(root: root) { log.append($0) }
try? await Task.sleep(nanoseconds: 600_000_000)
log.clear()
return (watcher, log)
}
private func settle() async {
try? await Task.sleep(nanoseconds: 1_000_000_000)
}
@Test func aBurstOfProjectChangesFiresOneDebouncedEvent() async throws {
let dir = try TempDirectory()
let (watcher, log) = await watch(dir.root)
defer { watcher.stop() }
for i in 0..<5 { try dir.write("src/file\(i).txt", "\(i)") }
#expect(await eventually { log.count(.project) >= 1 })
await settle()
#expect(log.count(.project) == 1)
#expect(log.count(.git) == 0)
}
@Test func changesInsideIgnoredFoldersAreDropped() async throws {
let dir = try TempDirectory()
try dir.mkdir("node_modules/pkg")
try dir.mkdir("vendor")
let (watcher, log) = await watch(dir.root)
defer { watcher.stop() }
try dir.write("node_modules/pkg/index.js", "x")
try dir.write("vendor/autoload.php", "x")
try dir.write(".helder/recent.json", "[]")
await settle()
#expect(log.count(.project) == 0)
}
@Test func theConfigFileFiresAConfigEventOnly() async throws {
let dir = try TempDirectory()
try dir.mkdir(".helder")
let (watcher, log) = await watch(dir.root)
defer { watcher.stop() }
try dir.write(".helder/config.json", #"{"editor":{"tabSize":2}}"#)
#expect(await eventually { log.count(.config) == 1 })
await settle()
#expect(log.count(.project) == 0)
}
@Test func aCommitFiresAGitEvent() async throws {
let repo = try TempGitRepo()
try repo.commit(["a.txt": "a\n"])
let (watcher, log) = await watch(repo.root)
defer { watcher.stop() }
try repo.run("commit", "-q", "--allow-empty", "-m", "second")
#expect(await eventually { log.count(.git) >= 1 })
}
@Test func aCommitInAWorktreeFiresAGitEvent() async throws {
let repo = try TempGitRepo()
try repo.commit(["a.txt": "a\n"])
let worktree = repo.root.deletingLastPathComponent().appendingPathComponent("helder-wt-\(UUID().uuidString)")
defer { try? FileManager.default.removeItem(at: worktree) }
try repo.run("worktree", "add", "-q", "-b", "side", worktree.path)
let (watcher, log) = await watch(worktree)
defer { watcher.stop() }
try repo.run("-C", worktree.path, "commit", "-q", "--allow-empty", "-m", "in the worktree")
#expect(await eventually { log.count(.git) >= 1 })
}
@Test func stopSilencesTheWatcher() async throws {
let dir = try TempDirectory()
let (watcher, log) = await watch(dir.root)
watcher.stop()
try dir.write("after.txt", "x")
await settle()
#expect(log.count(.project) == 0)
}
@Test func laravelCachesAndConfiguredExcludesAreDropped() async throws {
let dir = try TempDirectory()
try dir.write(".helder/config.json", #"{"files":{"exclude":["*.log"]}}"#)
try dir.mkdir("storage/framework/views")
try dir.mkdir("storage/logs")
let (watcher, log) = await watch(dir.root)
defer { watcher.stop() }
try dir.write("storage/framework/views/abc.php", "x")
try dir.write("storage/logs/laravel.log", "x")
try dir.write(".phpunit.result.cache", "x")
await settle()
#expect(log.count(.project) == 0)
try dir.write("app/User.php", "x")
#expect(await eventually { log.count(.project) == 1 })
}
@Test func gitIgnoredChangesAreDroppedWhenTheProjectFollowsGitignore() async throws {
let repo = try TempGitRepo()
try repo.commit([".gitignore": "tmp/\n", ".helder/config.json": #"{"files":{"followGitignore":true}}"#])
try FileManager.default.createDirectory(at: repo.root.appendingPathComponent("tmp"), withIntermediateDirectories: true)
let (watcher, log) = await watch(repo.root)
defer { watcher.stop() }
try repo.write("tmp/a.txt", "x")
try repo.write("tmp/b.txt", "x")
await settle()
#expect(log.count(.project) == 0)
try repo.write("tmp/c.txt", "x")
try repo.write("src/kept.txt", "x")
#expect(await eventually { log.count(.project) == 1 })
}
@Test func gitIgnoredChangesStillFireWhenTheProjectShowsIgnoredFiles() async throws {
let repo = try TempGitRepo()
try repo.commit([".gitignore": "tmp/\n"])
try FileManager.default.createDirectory(at: repo.root.appendingPathComponent("tmp"), withIntermediateDirectories: true)
let (watcher, log) = await watch(repo.root)
defer { watcher.stop() }
try repo.write("tmp/a.txt", "x")
#expect(await eventually { log.count(.project) == 1 })
}
@Test func startingAgainMovesTheWatchToTheNewRoot() async throws {
let first = try TempDirectory()
let second = try TempDirectory()
let (watcher, log) = await watch(first.root)
defer { watcher.stop() }
watcher.start(root: second.root) { log.append($0) }
try? await Task.sleep(nanoseconds: 600_000_000)
log.clear()
try first.write("old.txt", "x")
await settle()
#expect(log.count(.project) == 0)
try second.write("new.txt", "x")
#expect(await eventually { log.count(.project) == 1 })
}
}
@Suite struct EventRouterTests {
private let root = "/p"
private let git = "/p/.git"
private let none = FSEventStreamEventFlags(0)
private func classify(_ path: String, gitDirectory: String = "/p/.git", exclude: [String] = []) -> WatchEvent? {
EventRouter.classify(path: path, root: root, gitDirectory: gitDirectory, flags: none, exclude: exclude)
}
@Test func projectFilesAreProjectEvents() {
#expect(classify("/p/src/a.ts") == .project)
#expect(classify("/p/.env") == .project)
}
@Test func ignoredFoldersAtAnyDepthAreDropped() {
#expect(classify("/p/node_modules/x/y.js") == nil)
#expect(classify("/p/packages/web/dist/app.js") == nil)
#expect(classify("/p/.helder/recent.json") == nil)
#expect(classify("/p") == nil)
#expect(classify("/elsewhere/a.ts") == nil)
}
@Test func frameworkCachesAndExcludedGlobsAreDropped() {
#expect(classify("/p/storage/framework/cache/data/x") == nil)
#expect(classify("/p/bootstrap/cache/services.php") == nil)
#expect(classify("/p/storage/logs/laravel.log") == .project)
#expect(classify("/p/storage/logs/laravel.log", exclude: ["storage/logs"]) == nil)
}
@Test func theConfigFileIsAConfigEvent() {
#expect(classify("/p/.helder/config.json") == .config)
#expect(classify("/p/.helder/config.default.json") == nil)
}
@Test func onlyTheGitStateEntriesAreGitEvents() {
#expect(classify("/p/.git/HEAD") == .git)
#expect(classify("/p/.git/index") == .git)
#expect(classify("/p/.git/refs/heads/feature/x") == .git)
#expect(classify("/p/.git/refs/remotes/origin/main") == .git)
#expect(classify("/p/.git/logs/HEAD") == .git)
#expect(classify("/p/.git/MERGE_HEAD") == .git)
#expect(classify("/p/.git/objects/ab/cdef") == nil)
#expect(classify("/p/.git/index.lock") == nil)
#expect(classify("/p/.git/refs/tags/v1") == nil)
}
@Test func aWorktreeGitDirectoryOutsideTheRootIsWatchedToo() {
#expect(classify("/repo/.git/worktrees/wt/HEAD", gitDirectory: "/repo/.git/worktrees/wt") == .git)
#expect(classify("/p/.git", gitDirectory: "/repo/.git/worktrees/wt") == nil)
}
@Test func aDroppedEventBatchRescansTheProject() {
let flags = FSEventStreamEventFlags(kFSEventStreamEventFlagMustScanSubDirs)
#expect(EventRouter.classify(path: "/p/node_modules", root: root, gitDirectory: git, flags: flags) == .project)
}
@Test func realPathResolvesTheTempSymlinkEvenForAMissingFile() {
#expect(EventRouter.realPath("/var/nonexistent-helder-file") == "/private/var/nonexistent-helder-file")
#expect(EventRouter.realPath("/tmp") == "/private/tmp")
}
}
@@ -0,0 +1,120 @@
import Foundation
import HelderCore
import HelderServices
import Testing
/// Saves that must not lose data, and paths that must not leave the project through a symlink.
@Suite struct FileServiceSafetyTests {
private func service(_ root: URL) -> FileService {
FileService(root: root, search: NoRipgrepSearch())
}
private func permissions(_ url: URL) throws -> Int {
try (FileManager.default.attributesOfItem(atPath: url.path)[.posixPermissions] as? NSNumber)?.intValue ?? -1
}
// MARK: Saving
@Test func aSaveKeepsTheFilePermissions() async throws {
let dir = try TempDirectory()
try dir.write("run.sh", "echo old\n")
try FileManager.default.setAttributes([.posixPermissions: 0o750], ofItemAtPath: dir.url("run.sh").path)
try await service(dir.root).write("run.sh", contents: "echo new\n")
#expect(try dir.read("run.sh") == "echo new\n")
#expect(try permissions(dir.url("run.sh")) == 0o750)
}
@Test func aSaveThroughASymlinkWritesTheTargetAndKeepsTheLink() async throws {
let dir = try TempDirectory()
try dir.write("real/config.php", "old\n")
try FileManager.default.createSymbolicLink(atPath: dir.url("config.php").path, withDestinationPath: "real/config.php")
try await service(dir.root).write("config.php", contents: "new\n")
#expect(try dir.read("real/config.php") == "new\n")
#expect(try FileManager.default.destinationOfSymbolicLink(atPath: dir.url("config.php").path) == "real/config.php")
}
@Test func aSaveReplacesTheFileInOneStepAndLeavesNoTempFileBehind() async throws {
let dir = try TempDirectory()
try dir.write("a.txt", "old\n")
let before = try FileManager.default.attributesOfItem(atPath: dir.url("a.txt").path)[.systemFileNumber] as? NSNumber
try await service(dir.root).write("a.txt", contents: "new\n")
let after = try FileManager.default.attributesOfItem(atPath: dir.url("a.txt").path)[.systemFileNumber] as? NSNumber
#expect(before != after)
#expect(try FileManager.default.contentsOfDirectory(atPath: dir.root.path) == ["a.txt"])
}
@Test func aSaveOfANewFileCreatesIt() async throws {
let dir = try TempDirectory()
try await service(dir.root).write("fresh.txt", contents: "x\n")
#expect(try dir.read("fresh.txt") == "x\n")
}
// MARK: Symlinks out of the project
/// A project whose `link` folder is a symlink to a folder outside it holding `outside.txt`.
private func linkedProject() throws -> (project: TempDirectory, outside: TempDirectory) {
let project = try TempDirectory()
let outside = try TempDirectory()
try outside.write("outside.txt", "keep\n")
try FileManager.default.createSymbolicLink(at: project.url("link"), withDestinationURL: outside.root)
return (project, outside)
}
@Test func deleteThroughASymlinkedFolderIsRefused() async throws {
let (project, outside) = try linkedProject()
await #expect(throws: FileServiceError.outsideProject) { try await service(project.root).delete("link/outside.txt") }
#expect(outside.exists("outside.txt"))
}
@Test func renameThroughASymlinkedFolderIsRefused() async throws {
let (project, outside) = try linkedProject()
await #expect(throws: FileServiceError.outsideProject) { _ = try await service(project.root).rename("link/outside.txt", to: "moved.txt") }
#expect(outside.exists("outside.txt"))
#expect(!outside.exists("moved.txt"))
}
@Test func creatingThroughASymlinkedFolderIsRefused() async throws {
let (project, outside) = try linkedProject()
let files = service(project.root)
await #expect(throws: FileServiceError.outsideProject) { try await files.createFile("link/new.txt") }
await #expect(throws: FileServiceError.outsideProject) { try await files.createDirectory("link/sub") }
await #expect(throws: FileServiceError.outsideProject) { try await files.write("link/new.txt", contents: "x") }
#expect(!outside.exists("new.txt"))
#expect(!outside.exists("sub"))
}
@Test func editingAnExistingFileThroughASymlinkIsAllowed() async throws {
let (project, outside) = try linkedProject()
try await service(project.root).write("link/outside.txt", contents: "edited\n")
#expect(try outside.read("outside.txt") == "edited\n")
}
@Test func deletingTheSymlinkItselfRemovesOnlyTheLink() async throws {
let (project, outside) = try linkedProject()
try await service(project.root).delete("link")
#expect(!project.exists("link"))
#expect(outside.exists("outside.txt"))
}
// MARK: Case-only renames
@Test func aCaseOnlyRenameOnACaseSensitiveVolumeNeverClobbersAnotherFile() async throws {
let volume = try CaseSensitiveVolume()
let root = volume.root.appendingPathComponent("project")
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
try Data("lower\n".utf8).write(to: root.appendingPathComponent("readme.md"))
try Data("upper\n".utf8).write(to: root.appendingPathComponent("README.md"))
await #expect(throws: FileServiceError.alreadyExists("README.md")) { _ = try await service(root).rename("readme.md", to: "README.md") }
#expect(try String(contentsOf: root.appendingPathComponent("README.md"), encoding: .utf8) == "upper\n")
#expect(try String(contentsOf: root.appendingPathComponent("readme.md"), encoding: .utf8) == "lower\n")
}
@Test func aCaseOnlyRenameOnACaseSensitiveVolumeStillWorksWhenTheNameIsFree() async throws {
let volume = try CaseSensitiveVolume()
let root = volume.root.appendingPathComponent("project")
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
try Data("x\n".utf8).write(to: root.appendingPathComponent("notes.md"))
#expect(try await service(root).rename("notes.md", to: "Notes.md") == "Notes.md")
#expect(try FileManager.default.contentsOfDirectory(atPath: root.path) == ["Notes.md"])
}
}
@@ -0,0 +1,303 @@
import Foundation
import HelderCore
import HelderServices
import Testing
/// The tree and folder listings, through the walk (no ripgrep) and through ripgrep.
@Suite struct FileServiceTreeTests {
/// src/a.ts, README.md and a binary logo, plus node_modules and .git that must stay hidden.
private func fixture() throws -> TempDirectory {
let dir = try TempDirectory()
try dir.write("src/a.ts", "export const a = 1\n")
try dir.write("README.md", "# hi\n")
try dir.write("node_modules/pkg/index.js", "module.exports = 1\n")
try dir.write(".git/HEAD", "ref: refs/heads/main\n")
try dir.write("logo.bin", Data([0x00, 0x01, 0x02, 0x00, 0x99]))
return dir
}
private func walkService(_ dir: TempDirectory) -> FileService {
FileService(root: dir.root, search: NoRipgrepSearch())
}
private func ripgrepService(_ dir: TempDirectory) -> FileService {
let search = RipgrepSearchService(root: dir.root, config: FixedConfig(), locator: Ripgrep.locator, environment: [:])
return FileService(root: dir.root, search: search)
}
private func names(_ nodes: [FileNode]?) -> [String] {
(nodes ?? []).map(\.name)
}
@Test func theWalkListsFoldersBeforeFilesAndSkipsIgnoredFolders() async throws {
let dir = try fixture()
let tree = await walkService(dir).tree()
#expect(tree.name == dir.root.lastPathComponent)
#expect(tree.path == "")
#expect(names(tree.children) == ["src", "logo.bin", "README.md"])
#expect(tree.children?.first?.children == [FileNode(name: "a.ts", kind: .file, path: "src/a.ts")])
}
@Test func theWalkSortsNamesCaseInsensitively() async throws {
let dir = try TempDirectory()
for name in ["b.txt", "A.txt", "c.txt", "Zeta", "alpha"] {
if name.hasSuffix(".txt") { try dir.write(name, "") } else { try dir.mkdir(name) }
}
#expect(names(await walkService(dir).tree().children) == ["alpha", "Zeta", "A.txt", "b.txt", "c.txt"])
}
@Test func theWalkShowsEmptyFoldersAndDotfiles() async throws {
let dir = try fixture()
try dir.mkdir("empty")
try dir.write(".env", "APP_NAME=x\n")
let tree = await walkService(dir).tree()
#expect(names(tree.children) == ["empty", "src", ".env", "logo.bin", "README.md"])
#expect(tree.children?.first == FileNode(name: "empty", kind: .directory, path: "empty", children: []))
}
@Test func theWalkStopsAtTheDepthLimit() async throws {
let dir = try TempDirectory()
let deep = (0...FileLimits.maxWalkDepth + 2).map { "d\($0)" }.joined(separator: "/")
try dir.write(deep + "/leaf.txt", "x")
var node: FileNode? = await walkService(dir).tree()
var depth = 0
while let next = node?.children?.first {
node = next
depth += 1
}
#expect(depth == FileLimits.maxWalkDepth + 1)
}
@Test(.enabled(if: Ripgrep.isPresent))
func theRipgrepTreeAddsTheEmptyFoldersRipgrepCannotList() async throws {
let dir = try fixture()
try dir.mkdir("empty")
try dir.mkdir("src/nested/deep")
let tree = await ripgrepService(dir).tree()
#expect(names(tree.children) == ["empty", "src", "logo.bin", "README.md"])
let src = FileTree.find("src", in: tree)
#expect(names(src?.children) == ["nested", "a.ts"])
#expect(names(FileTree.find("src/nested", in: tree)?.children) == ["deep"])
}
@Test(.enabled(if: Ripgrep.isPresent))
func theRipgrepTreeShowsGitignoredFilesByDefault() async throws {
let repo = try TempGitRepo()
try repo.write(".gitignore", "secret.txt\n")
try repo.write("secret.txt", "shh")
let search = RipgrepSearchService(root: repo.root, config: FixedConfig(), locator: Ripgrep.locator, environment: [:])
let tree = await FileService(root: repo.root, search: search).tree()
#expect(names(tree.children) == [".gitignore", "secret.txt"])
}
@Test func childrenOfTheRootAndOfASubfolder() async throws {
let dir = try fixture()
let service = walkService(dir)
#expect(names(await service.children(of: "")) == ["src", "logo.bin", "README.md"])
#expect(await service.children(of: "src") == [FileNode(name: "a.ts", kind: .file, path: "src/a.ts")])
}
@Test func childrenAreReadFreshOnEveryCall() async throws {
let dir = try fixture()
let service = walkService(dir)
_ = await service.children(of: "src")
try dir.write("src/b.ts", "export const b = 2\n")
try FileManager.default.removeItem(at: dir.url("src/a.ts"))
try dir.mkdir("src/fresh")
#expect(await service.children(of: "src") == [
FileNode(name: "fresh", kind: .directory, path: "src/fresh", children: []),
FileNode(name: "b.ts", kind: .file, path: "src/b.ts"),
])
}
@Test func childrenOutsideTheProjectAreEmpty() async throws {
let dir = try fixture()
#expect(await walkService(dir).children(of: "../").isEmpty)
}
@Test(.enabled(if: Ripgrep.isPresent))
func ripgrepChildrenIncludeAFreshEmptyFolder() async throws {
let dir = try fixture()
try dir.mkdir("src/fresh")
let service = ripgrepService(dir)
#expect(await service.children(of: "src") == [
FileNode(name: "fresh", kind: .directory, path: "src/fresh", children: []),
FileNode(name: "a.ts", kind: .file, path: "src/a.ts"),
])
#expect(!names(await service.children(of: "")).contains("node_modules"))
}
@Test func emptyDirectoriesAreFoldersWithoutAnyFileBelow() async throws {
let dir = try fixture()
try dir.mkdir("empty")
try dir.mkdir("src/nested/deep")
try dir.mkdir("node_modules/also-empty")
let service = walkService(dir)
#expect(Set(await service.emptyDirectories()) == ["empty", "src/nested", "src/nested/deep"])
#expect(Set(await service.emptyDirectories(under: "src")) == ["src/nested", "src/nested/deep"])
}
@Test func aFolderHoldingOnlyAnIgnoredFolderCountsAsEmpty() async throws {
let dir = try TempDirectory()
try dir.write("app/node_modules/x.js", "x")
#expect(await walkService(dir).emptyDirectories() == ["app"])
}
}
/// Reading, writing, creating, renaming and deleting single entries.
@Suite struct FileServiceEntryTests {
private func service(_ dir: TempDirectory) -> FileService {
FileService(root: dir.root, search: NoRipgrepSearch())
}
@Test func writeThenReadRoundTrips() async throws {
let dir = try TempDirectory()
let files = service(dir)
try await files.write("note.txt", contents: "hello world\n")
#expect(try await files.read("note.txt") == "hello world\n")
}
@Test func aBinaryFileReadsAsEmpty() async throws {
let dir = try TempDirectory()
try dir.write("logo.bin", Data([0x89, 0x00, 0x01]))
#expect(try await service(dir).read("logo.bin") == "")
}
@Test func readTextTellsAnEmptyFileFromABinaryOne() async throws {
let dir = try TempDirectory()
try dir.write("empty.txt", "")
try dir.write("logo.bin", Data([0x89, 0x00, 0x01]))
try dir.write("note.txt", "hello\n")
let files = service(dir)
#expect(try await files.readText("empty.txt") == .text(""))
#expect(try await files.readText("logo.bin") == .binary)
#expect(try await files.readText("note.txt") == .text("hello\n"))
}
@Test func aNulByteAfterTheFirst8000BytesStillReadsAsText() async throws {
let dir = try TempDirectory()
try dir.write("long.txt", Data(repeating: 0x61, count: 8000) + Data([0x00]))
#expect(try await service(dir).readText("long.txt") == .text(String(repeating: "a", count: 8000) + "\0"))
}
@Test func readingOutsideTheProjectThrows() async throws {
let dir = try TempDirectory()
await #expect(throws: FileServiceError.outsideProject) { try await service(dir).read("../etc/passwd") }
}
@Test func createFileMakesAnEmptyFileAndItsFolders() async throws {
let dir = try TempDirectory()
try await service(dir).createFile("src/new/fresh.ts")
#expect(try dir.read("src/new/fresh.ts") == "")
}
@Test func createFileRefusesToOverwrite() async throws {
let dir = try TempDirectory()
try dir.write("keep.txt", "precious\n")
await #expect(throws: FileServiceError.alreadyExists("keep.txt")) { try await service(dir).createFile("keep.txt") }
#expect(try dir.read("keep.txt") == "precious\n")
}
@Test func createFileRefusesTheRootAndPathsOutsideIt() async throws {
let dir = try TempDirectory()
let files = service(dir)
await #expect(throws: FileServiceError.outsideProject) { try await files.createFile("../escape.txt") }
await #expect(throws: FileServiceError.outsideProject) { try await files.createFile("") }
#expect(!FileManager.default.fileExists(atPath: dir.root.deletingLastPathComponent().appendingPathComponent("escape.txt").path))
}
@Test func createDirectoryMakesNestedFolders() async throws {
let dir = try TempDirectory()
try await service(dir).createDirectory("a/b/c")
var isDirectory: ObjCBool = false
#expect(FileManager.default.fileExists(atPath: dir.url("a/b/c").path, isDirectory: &isDirectory) && isDirectory.boolValue)
}
@Test func createDirectoryRefusesATakenName() async throws {
let dir = try TempDirectory()
try dir.mkdir("taken")
try dir.write("file", "")
let files = service(dir)
await #expect(throws: FileServiceError.alreadyExists("taken")) { try await files.createDirectory("taken") }
await #expect(throws: FileServiceError.alreadyExists("file")) { try await files.createDirectory("file") }
await #expect(throws: FileServiceError.outsideProject) { try await files.createDirectory("../out") }
}
@Test func renameMovesAFileWithinItsFolder() async throws {
let dir = try TempDirectory()
try dir.write("src/old.ts", "x\n")
#expect(try await service(dir).rename("src/old.ts", to: "new.ts") == "src/new.ts")
#expect(try dir.read("src/new.ts") == "x\n")
#expect(!dir.exists("src/old.ts"))
}
@Test func renameMovesAFolderWithEverythingInside() async throws {
let dir = try TempDirectory()
try dir.write("old/a.ts", "a\n")
#expect(try await service(dir).rename("old", to: "new") == "new")
#expect(try dir.read("new/a.ts") == "a\n")
}
@Test func renameCanChangeOnlyTheCase() async throws {
let dir = try TempDirectory()
try dir.write("notes.md", "hi\n")
#expect(try await service(dir).rename("notes.md", to: "Notes.md") == "Notes.md")
#expect(try FileManager.default.contentsOfDirectory(atPath: dir.root.path) == ["Notes.md"])
}
@Test func renameToTheSameNameIsANoOp() async throws {
let dir = try TempDirectory()
try dir.write("a.txt", "a\n")
#expect(try await service(dir).rename("a.txt", to: " a.txt/ ") == "a.txt")
}
@Test func renameRefusesATakenName() async throws {
let dir = try TempDirectory()
try dir.write("a.txt", "a\n")
try dir.write("b.txt", "b\n")
await #expect(throws: FileServiceError.alreadyExists("b.txt")) { try await service(dir).rename("a.txt", to: "b.txt") }
#expect(try dir.read("b.txt") == "b\n")
#expect(try dir.read("a.txt") == "a\n")
}
@Test(arguments: ["sub/a.txt", "../a.txt", " ", "..", "."])
func renameRefusesAPathShapedOrEmptyName(_ name: String) async throws {
let dir = try TempDirectory()
try dir.mkdir("sub")
try dir.write("a.txt", "a\n")
await #expect(throws: FileServiceError.invalidName(name)) { try await service(dir).rename("a.txt", to: name) }
#expect(try dir.read("a.txt") == "a\n")
}
@Test func renameRefusesTheRootAndEscapes() async throws {
let dir = try TempDirectory()
let files = service(dir)
await #expect(throws: FileServiceError.outsideProject) { _ = try await files.rename("", to: "x") }
await #expect(throws: FileServiceError.outsideProject) { _ = try await files.rename("../x", to: "y") }
}
@Test func renameOfAMissingEntryThrows() async throws {
let dir = try TempDirectory()
await #expect(throws: (any Error).self) { _ = try await service(dir).rename("missing.txt", to: "other.txt") }
}
@Test func deleteRemovesAFolderButNeverTheRoot() async throws {
let dir = try TempDirectory()
try dir.write("folder/a.txt", "a")
let files = service(dir)
try await files.delete("folder")
#expect(!dir.exists("folder"))
await #expect(throws: FileServiceError.outsideProject) { try await files.delete("") }
#expect(FileManager.default.fileExists(atPath: dir.root.path))
}
@Test func readImageReturnsBytesOnlyForImages() async throws {
let dir = try TempDirectory()
try dir.write("pic.png", Data([0x89, 0x50, 0x4E, 0x47]))
try dir.write("notes.txt", "text")
let files = service(dir)
#expect(await files.readImage("pic.png") == Data([0x89, 0x50, 0x4E, 0x47]))
#expect(await files.readImage("notes.txt") == nil)
#expect(await files.readImage("missing.png") == nil)
}
}
@@ -0,0 +1,536 @@
import Foundation
import HelderCore
@testable import HelderServices
import Testing
@Suite struct GitServiceLoadTests {
/// A repository with `a.txt` committed as three lines.
private func repo() throws -> TempGitRepo {
let repo = try TempGitRepo()
try repo.commit(["a.txt": "1\n2\n3\n"], message: "init")
return repo
}
private func rows(_ snapshot: GitSnapshot?, _ path: String) -> [GitFileChange] {
snapshot?.changes.filter { $0.path == path } ?? []
}
@Test func aFolderOutsideGitLoadsAsNil() async throws {
let dir = try TempDirectory()
#expect(try await GitService(root: dir.root).load() == nil)
}
@Test func aModifiedFileCarriesHeadAndDiskText() async throws {
let repo = try repo()
try repo.write("a.txt", "1\nX\n3\n")
let snapshot = try #require(try await GitService(root: repo.root).load())
#expect(snapshot.branch == "main")
#expect(rows(snapshot, "a.txt") == [GitFileChange(path: "a.txt", status: .modified, staged: false, original: "1\n2\n3\n", updated: "1\nX\n3\n")])
}
@Test func anUntrackedFileIsAnUnstagedAddition() async throws {
let repo = try repo()
try repo.write("new.txt", "fresh\n")
let snapshot = try await GitService(root: repo.root).load()
#expect(rows(snapshot, "new.txt") == [GitFileChange(path: "new.txt", status: .added, staged: false, original: "", updated: "fresh\n")])
}
@Test func aStagedFileHasOneStagedRow() async throws {
let repo = try repo()
try repo.write("a.txt", "1\n2\n3\n4\n")
let service = GitService(root: repo.root)
try await service.stage(["a.txt"])
let snapshot = try await service.load()
#expect(rows(snapshot, "a.txt") == [GitFileChange(path: "a.txt", status: .modified, staged: true, original: "1\n2\n3\n", updated: "1\n2\n3\n4\n")])
}
@Test func aFileStagedThenEditedHasTwoRowsEachWithItsOwnPair() async throws {
let repo = try repo()
let service = GitService(root: repo.root)
try repo.write("a.txt", "1\nSTAGED\n3\n")
try await service.stage(["a.txt"])
try repo.write("a.txt", "1\nSTAGED\n3\n4\n")
let snapshot = try await service.load()
#expect(rows(snapshot, "a.txt") == [
GitFileChange(path: "a.txt", status: .modified, staged: true, original: "1\n2\n3\n", updated: "1\nSTAGED\n3\n"),
GitFileChange(path: "a.txt", status: .modified, staged: false, original: "1\nSTAGED\n3\n", updated: "1\nSTAGED\n3\n4\n"),
])
}
@Test func aStagedNewFileEditedAgainIsAnAdditionPlusAModification() async throws {
let repo = try repo()
let service = GitService(root: repo.root)
try repo.write("fresh.txt", "one\n")
try await service.stage(["fresh.txt"])
try repo.write("fresh.txt", "one\ntwo\n")
let snapshot = try await service.load()
#expect(rows(snapshot, "fresh.txt") == [
GitFileChange(path: "fresh.txt", status: .added, staged: true, original: "", updated: "one\n"),
GitFileChange(path: "fresh.txt", status: .modified, staged: false, original: "one\n", updated: "one\ntwo\n"),
])
}
@Test func aDeletedFileHasNoDiskText() async throws {
let repo = try repo()
try FileManager.default.removeItem(at: repo.root.appendingPathComponent("a.txt"))
let snapshot = try await GitService(root: repo.root).load()
#expect(rows(snapshot, "a.txt") == [GitFileChange(path: "a.txt", status: .deleted, staged: false, original: "1\n2\n3\n", updated: "")])
}
@Test func aStagedRenameIsOneRowUnderTheNewPath() async throws {
let repo = try repo()
try repo.run("mv", "a.txt", "b.txt")
let snapshot = try #require(try await GitService(root: repo.root).load())
#expect(snapshot.changes.map(\.path) == ["b.txt"])
#expect(snapshot.changes.first?.status == .renamed)
#expect(snapshot.changes.first?.staged == true)
}
@Test func aBinaryFileReadsAsEmptyText() async throws {
let repo = try repo()
try Data([0x00, 0x01, 0x02]).write(to: repo.root.appendingPathComponent("logo.bin"))
let snapshot = try await GitService(root: repo.root).load()
#expect(rows(snapshot, "logo.bin").first?.updated == "")
}
@Test func aheadCountsCommitsTheRemoteLacks() async throws {
let remote = try TempGitRepo(bare: true)
let repo = try repo()
try repo.run("remote", "add", "origin", remote.root.path)
try repo.run("push", "-q", "-u", "origin", "main")
try repo.commit(["b.txt": "b\n"], message: "second")
let snapshot = try #require(try await GitService(root: repo.root).load())
#expect(snapshot.ahead == 1)
#expect(snapshot.canPush)
}
@Test func aWorktreeWithAGitFileLoads() async throws {
let repo = try repo()
let worktree = repo.root.deletingLastPathComponent().appendingPathComponent("helder-wt-\(UUID().uuidString)")
defer { try? FileManager.default.removeItem(at: worktree) }
try repo.run("worktree", "add", "-q", "-b", "side", worktree.path)
try Data("changed\n".utf8).write(to: worktree.appendingPathComponent("a.txt"))
let snapshot = try #require(try await GitService(root: worktree).load())
#expect(snapshot.branch == "side")
#expect(snapshot.changes.map(\.path) == ["a.txt"])
}
@Test func aFailingStatusIsRetriedThenThrowsWithGitsStderr() async throws {
let runner = ScriptedRunner { call in
if call.arguments.first == "rev-parse" { return ProcessResult(exitCode: 0, stdout: "true\n", stderr: "") }
return ProcessResult(exitCode: 128, stdout: "", stderr: "fatal: Unable to create '.git/index.lock': File exists.\n")
}
let service = GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner, statusAttempts: 3, statusRetryDelay: 0.01)
await #expect(throws: GitError.commandFailed(arguments: Porcelain.statusArguments, exitCode: 128,
stderr: "fatal: Unable to create '.git/index.lock': File exists.")) {
try await service.load()
}
#expect(runner.calls.filter { $0.arguments == Porcelain.statusArguments }.count == 3)
#expect(runner.calls.last?.environment?["GIT_OPTIONAL_LOCKS"] == "0")
}
@Test func overlappingLoadsShareOneReadPlusOneTrailingRead() async throws {
let gate = Gate()
let runner = ScriptedRunner { call in
if call.arguments.first == "rev-parse" {
await gate.wait()
return ProcessResult(exitCode: 0, stdout: "true\n", stderr: "")
}
return ProcessResult(exitCode: 1, stdout: "", stderr: "stop here")
}
let service = GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner, statusAttempts: 1)
let first = Task { try? await service.load() }
#expect(await eventually { !runner.calls.isEmpty })
let later = (0..<5).map { _ in Task { _ = try? await service.load() } }
#expect(await eventuallyAsync { await service.coalescedLoads == 5 })
await gate.open()
_ = await first.value
for task in later { await task.value }
#expect(runner.calls.filter { $0.arguments.first == "rev-parse" }.count == 2)
}
@Test func anUntrackedFileOverTheSizeCapLoadsWithoutText() async throws {
let repo = try repo()
try repo.write("dump.sql", String(repeating: "insert;\n", count: 200))
let snapshot = try await GitService(root: repo.root, maxDiffBytes: 1000).load()
#expect(rows(snapshot, "dump.sql") == [GitFileChange(path: "dump.sql", status: .added, staged: false, original: "", updated: "",
isTooBig: true)])
}
@Test func aCommittedFileOverTheSizeCapLoadsWithoutTextOnEitherSide() async throws {
let repo = try repo()
try repo.commit(["big.txt": String(repeating: "line\n", count: 300)])
try repo.write("big.txt", String(repeating: "line\n", count: 301))
let snapshot = try await GitService(root: repo.root, maxDiffBytes: 1000).load()
#expect(rows(snapshot, "big.txt") == [GitFileChange(path: "big.txt", status: .modified, staged: false, original: "", updated: "",
isTooBig: true)])
}
@Test func aFileThatOutgrewTheCapDropsTheSmallSideToo() async throws {
let repo = try repo()
try repo.commit(["grew.txt": "small\n"])
try repo.write("grew.txt", String(repeating: "line\n", count: 300))
let snapshot = try await GitService(root: repo.root, maxDiffBytes: 1000).load()
let row = try #require(rows(snapshot, "grew.txt").first)
#expect(row.isTooBig)
#expect(row.original.isEmpty && row.updated.isEmpty)
}
@Test func aFileUnderTheSizeCapStillCarriesItsText() async throws {
let repo = try repo()
try repo.write("small.txt", "ok\n")
let snapshot = try await GitService(root: repo.root, maxDiffBytes: 1000).load()
#expect(rows(snapshot, "small.txt").first?.updated == "ok\n")
#expect(rows(snapshot, "small.txt").first?.isTooBig == false)
}
@Test func aStagedRenameCarriesItsSourcePath() async throws {
let repo = try repo()
try repo.run("mv", "a.txt", "b.txt")
let snapshot = try #require(try await GitService(root: repo.root).load())
#expect(snapshot.changes.first?.originalPath == "a.txt")
}
}
@Suite struct GitServiceWriteTests {
private func repo() throws -> TempGitRepo {
let repo = try TempGitRepo()
try repo.commit(["a.txt": "1\n2\n3\n", "b.txt": "b\n"], message: "init")
return repo
}
private func status(_ repo: TempGitRepo) throws -> String {
try repo.run("status", "--porcelain")
}
@Test func stagingADeletionRemovesTheFileFromTheIndex() async throws {
let repo = try repo()
try FileManager.default.removeItem(at: repo.root.appendingPathComponent("a.txt"))
try await GitService(root: repo.root).stage(["a.txt"])
#expect(try status(repo) == "D a.txt\n")
}
@Test func stagingBothSidesOfAMoveRecordsARename() async throws {
let repo = try repo()
try FileManager.default.moveItem(at: repo.root.appendingPathComponent("a.txt"), to: repo.root.appendingPathComponent("c.txt"))
try await GitService(root: repo.root).stage(["a.txt", "c.txt"])
#expect(try status(repo) == "R a.txt -> c.txt\n")
}
@Test func unstagingADeletionKeepsTheFileDeletedOnDisk() async throws {
let repo = try repo()
try repo.run("rm", "-q", "a.txt")
try await GitService(root: repo.root).unstage(["a.txt"])
#expect(try status(repo) == " D a.txt\n")
}
@Test func unstagingARenameLeavesTheOldPathStagedAsDeleted() async throws {
let repo = try repo()
try repo.run("mv", "a.txt", "c.txt")
try await GitService(root: repo.root).unstage(["c.txt"])
#expect(try status(repo) == "D a.txt\n?? c.txt\n")
}
@Test func unstagingWorksInARepositoryWithoutCommits() async throws {
let repo = try TempGitRepo()
try repo.write("first.txt", "x\n")
let service = GitService(root: repo.root)
try await service.stage(["first.txt"])
#expect(try status(repo) == "A first.txt\n")
try await service.unstage(["first.txt"])
#expect(try status(repo) == "?? first.txt\n")
}
@Test func stagingNothingRunsNoGit() async throws {
let runner = ScriptedRunner { _ in ProcessResult(exitCode: 0, stdout: "", stderr: "") }
let service = GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner)
try await service.stage([])
try await service.unstage([])
#expect(runner.calls.isEmpty)
}
@Test func aFailedCommitThrowsWithGitsStderr() async throws {
let repo = try repo()
do {
try await GitService(root: repo.root).commit(message: "nothing")
Issue.record("commit with nothing staged should fail")
} catch let GitError.commandFailed(arguments, exitCode, _) {
#expect(arguments == ["commit", "-m", "nothing"])
#expect(exitCode != 0)
}
}
@Test func aFailedStageCarriesStderr() async throws {
let repo = try repo()
do {
try await GitService(root: repo.root).stage(["missing.txt"])
Issue.record("staging a missing path should fail")
} catch let GitError.commandFailed(_, _, stderr) {
#expect(stderr.contains("missing.txt"))
}
}
@Test func discardRevertsAModifiedFileToHead() async throws {
let repo = try repo()
try repo.write("a.txt", "1\nCHANGED\n3\n")
try await GitService(root: repo.root).discard(["a.txt"])
#expect(try repo.read("a.txt") == "1\n2\n3\n")
#expect(try status(repo) == "")
}
@Test func discardRevertsAFileStagedThenEdited() async throws {
let repo = try repo()
try repo.write("a.txt", "staged\n")
try repo.run("add", "a.txt")
try repo.write("a.txt", "edited again\n")
try await GitService(root: repo.root).discard(["a.txt"])
#expect(try repo.read("a.txt") == "1\n2\n3\n")
#expect(try status(repo) == "")
}
@Test func discardRemovesAnUntrackedFile() async throws {
let repo = try repo()
try repo.write("new.txt", "fresh\n")
try await GitService(root: repo.root).discard(["new.txt"])
#expect(!FileManager.default.fileExists(atPath: repo.root.appendingPathComponent("new.txt").path))
}
@Test func discardUnstagesAndRemovesAStagedNewFile() async throws {
let repo = try repo()
try repo.write("staged-new.txt", "x\n")
try repo.run("add", "staged-new.txt")
try await GitService(root: repo.root).discard(["staged-new.txt"])
#expect(!FileManager.default.fileExists(atPath: repo.root.appendingPathComponent("staged-new.txt").path))
#expect(try status(repo) == "")
}
@Test func discardRestoresADeletedFile() async throws {
let repo = try repo()
try FileManager.default.removeItem(at: repo.root.appendingPathComponent("a.txt"))
try await GitService(root: repo.root).discard(["a.txt"])
#expect(try repo.read("a.txt") == "1\n2\n3\n")
}
@Test func discardRestoresAStagedDeletion() async throws {
let repo = try repo()
try repo.run("rm", "-q", "a.txt")
try await GitService(root: repo.root).discard(["a.txt"])
#expect(try repo.read("a.txt") == "1\n2\n3\n")
#expect(try status(repo) == "")
}
@Test func discardHandlesSeveralPathsInOneCall() async throws {
let repo = try repo()
try repo.write("a.txt", "changed\n")
try repo.write("new.txt", "new\n")
try await GitService(root: repo.root).discard(["a.txt", "new.txt"])
#expect(try status(repo) == "")
}
@Test func discardNeverDeletesAFolderOrAnythingOutsideTheProject() async throws {
let repo = try repo()
let outside = repo.root.deletingLastPathComponent().appendingPathComponent("helder-outside-\(UUID().uuidString).txt")
try Data("keep\n".utf8).write(to: outside)
defer { try? FileManager.default.removeItem(at: outside) }
try repo.write("folder/inner.txt", "keep\n")
let service = GitService(root: repo.root)
try await service.discard(["folder", "../" + outside.lastPathComponent])
#expect(FileManager.default.fileExists(atPath: outside.path))
#expect(try repo.read("folder/inner.txt") == "keep\n")
}
@Test func discardingAStagedRenameRestoresTheSourceAndRemovesTheTarget() async throws {
let repo = try repo()
try repo.run("mv", "a.txt", "c.txt")
try await GitService(root: repo.root).discard(["c.txt"])
#expect(try repo.read("a.txt") == "1\n2\n3\n")
#expect(!FileManager.default.fileExists(atPath: repo.root.appendingPathComponent("c.txt").path))
#expect(try status(repo) == "")
}
@Test func discardingAStagedRenameEditedAfterwardsStillRestoresTheSource() async throws {
let repo = try repo()
try repo.run("mv", "a.txt", "c.txt")
try repo.write("c.txt", "edited\n")
try await GitService(root: repo.root).discard(["c.txt"])
#expect(try repo.read("a.txt") == "1\n2\n3\n")
#expect(!FileManager.default.fileExists(atPath: repo.root.appendingPathComponent("c.txt").path))
#expect(try status(repo) == "")
}
@Test func contentsReadsTheHeadAndIndexCopies() async throws {
let repo = try repo()
try repo.write("a.txt", "staged\n")
try repo.run("add", "a.txt")
try repo.write("a.txt", "disk\n")
let service = GitService(root: repo.root)
#expect(await service.contents(of: "a.txt", at: .head) == "1\n2\n3\n")
#expect(await service.contents(of: "a.txt", at: .index) == "staged\n")
#expect(await service.contents(of: "nope.txt", at: .head) == "")
}
@Test func isRepositoryAcceptsAWorktreeGitFile() async throws {
let repo = try repo()
let worktree = repo.root.deletingLastPathComponent().appendingPathComponent("helder-wt-\(UUID().uuidString)")
defer { try? FileManager.default.removeItem(at: worktree) }
try repo.run("worktree", "add", "-q", "-b", "side", worktree.path)
let service = GitService(root: worktree)
#expect(await service.isRepository())
try Data("wt\n".utf8).write(to: worktree.appendingPathComponent("a.txt"))
try await service.discard(["a.txt"])
#expect(try String(contentsOf: worktree.appendingPathComponent("a.txt"), encoding: .utf8) == "1\n2\n3\n")
}
}
/// Names git would read as globs or options unless every pathspec is literal.
@Suite struct GitServiceLiteralPathTests {
private func repo() throws -> TempGitRepo {
let repo = try TempGitRepo()
try repo.commit([
"pages/[id].vue": "id\n", "pages/i.vue": "i\n", "pages/d.vue": "d\n",
"a*.txt": "star\n", "ab.txt": "ab\n", "a?.txt": "q\n", "ac.txt": "ac\n",
"-dash.txt": "dash\n", "with space.txt": "space\n",
], message: "init")
return repo
}
private func status(_ repo: TempGitRepo) throws -> String {
try repo.run("status", "--porcelain")
}
private func editAll(_ repo: TempGitRepo) throws {
for path in ["pages/[id].vue", "pages/i.vue", "pages/d.vue", "a*.txt", "ab.txt", "a?.txt", "ac.txt", "-dash.txt", "with space.txt"] {
try repo.write(path, "changed\n")
}
}
@Test func discardTouchesOnlyTheNamedFile() async throws {
let repo = try repo()
try editAll(repo)
try await GitService(root: repo.root).discard(["pages/[id].vue", "a*.txt", "a?.txt", "-dash.txt", "with space.txt"])
#expect(try repo.read("pages/[id].vue") == "id\n")
#expect(try repo.read("pages/i.vue") == "changed\n")
#expect(try repo.read("pages/d.vue") == "changed\n")
#expect(try repo.read("a*.txt") == "star\n")
#expect(try repo.read("ab.txt") == "changed\n")
#expect(try repo.read("ac.txt") == "changed\n")
#expect(try repo.read("-dash.txt") == "dash\n")
#expect(try repo.read("with space.txt") == "space\n")
}
@Test func discardOfAnUntrackedGlobNameRemovesOnlyThatFile() async throws {
let repo = try repo()
try repo.write("new/[x].txt", "n\n")
try repo.write("new/x.txt", "keep\n")
try await GitService(root: repo.root).discard(["new/[x].txt"])
#expect(!FileManager.default.fileExists(atPath: repo.root.appendingPathComponent("new/[x].txt").path))
#expect(try repo.read("new/x.txt") == "keep\n")
}
@Test func stageAndUnstageTouchOnlyTheNamedFile() async throws {
let repo = try repo()
try editAll(repo)
let service = GitService(root: repo.root)
try await service.stage(["pages/[id].vue", "a*.txt", "a?.txt", "-dash.txt", "with space.txt"])
let staged = try repo.run("diff", "--cached", "--name-only")
#expect(staged == "-dash.txt\na*.txt\na?.txt\npages/[id].vue\nwith space.txt\n")
try await service.stage(["pages/i.vue", "ab.txt"])
try await service.unstage(["pages/[id].vue", "a*.txt"])
#expect(try repo.run("diff", "--cached", "--name-only") == "-dash.txt\na?.txt\nab.txt\npages/i.vue\nwith space.txt\n")
}
@Test func contentsReadsANameWithGlobCharactersOrALeadingDash() async throws {
let repo = try repo()
let service = GitService(root: repo.root)
#expect(await service.contents(of: "pages/[id].vue", at: .head) == "id\n")
#expect(await service.contents(of: "-dash.txt", at: .head) == "dash\n")
#expect(await service.contents(of: "with space.txt", at: .index) == "space\n")
}
@Test func everyGitCallRunsWithLiteralPathspecs() async throws {
let runner = ScriptedRunner { call in
if call.arguments.first == "rev-parse" { return ProcessResult(exitCode: 0, stdout: "true\n", stderr: "") }
return ProcessResult(exitCode: 0, stdout: "", stderr: "")
}
let service = GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner)
_ = try await service.load()
try await service.stage(["a"])
try await service.unstage(["a"])
try await service.discard(["a"])
_ = await service.contents(of: "a", at: .head)
try await service.commit(message: "m")
_ = await service.push()
#expect(!runner.calls.isEmpty)
#expect(runner.calls.allSatisfy { $0.environment?["GIT_LITERAL_PATHSPECS"] == "1" })
}
}
@Suite struct GitServicePushTests {
/// A committed repository plus a bare remote it knows as `origin`.
private func repoWithRemote() throws -> (repo: TempGitRepo, remote: TempGitRepo) {
let remote = try TempGitRepo(bare: true)
let repo = try TempGitRepo()
try repo.commit(["a.txt": "a\n"], message: "init")
try repo.run("remote", "add", "origin", remote.root.path)
return (repo, remote)
}
@Test func aFirstPushSetsTheUpstream() async throws {
let (repo, remote) = try repoWithRemote()
defer { withExtendedLifetime(remote) {} }
let result = await GitService(root: repo.root).push()
#expect(result.ok)
#expect(result.message.contains("main"))
#expect(try repo.run("rev-parse", "--abbrev-ref", "main@{upstream}") == "origin/main\n")
}
@Test func aPushWithNothingNewReportsUpToDate() async throws {
let (repo, remote) = try repoWithRemote()
defer { withExtendedLifetime(remote) {} }
try repo.run("push", "-q", "-u", "origin", "main")
let result = await GitService(root: repo.root).push()
#expect(result == PushResult(ok: true, message: "Everything up-to-date"))
}
@Test func aPushWithoutARemoteFailsWithGitsLastLine() async throws {
let repo = try TempGitRepo()
try repo.commit(["a.txt": "a\n"])
let result = await GitService(root: repo.root).push()
#expect(!result.ok)
#expect(!result.message.isEmpty)
}
@Test func pushTurnsOffCredentialPrompts() async throws {
let runner = ScriptedRunner { _ in ProcessResult(exitCode: 0, stdout: "", stderr: "Everything up-to-date\n") }
_ = await GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner).push()
#expect(runner.calls.first?.arguments == ["push"])
#expect(runner.calls.first?.environment?["GIT_TERMINAL_PROMPT"] == "0")
}
@Test func aPushWithoutUpstreamRetriesWithTheCurrentBranch() async throws {
let runner = ScriptedRunner { call in
switch call.arguments {
case ["push"]:
return ProcessResult(exitCode: 128, stdout: "", stderr: "fatal: The current branch feature has no upstream branch.\n")
case ["rev-parse", "--abbrev-ref", "HEAD"]:
return ProcessResult(exitCode: 0, stdout: "feature\n", stderr: "")
default:
return ProcessResult(exitCode: 0, stdout: "", stderr: " * [new branch] feature -> feature\n")
}
}
let result = await GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner).push()
#expect(runner.calls.map(\.arguments).last == ["push", "-u", "origin", "feature"])
#expect(result == PushResult(ok: true, message: "* [new branch] feature -> feature"))
}
@Test func aHangingPushGivesUpAfterTheTimeout() async throws {
let runner = ScriptedRunner { _ in
try await Task.sleep(nanoseconds: 30_000_000_000)
return ProcessResult(exitCode: 0, stdout: "", stderr: "")
}
let started = Date()
let result = await GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner, pushTimeout: 0.2).push()
#expect(result == PushResult(ok: false, message: "push timed out"))
#expect(Date().timeIntervalSince(started) < 5)
}
}
@@ -0,0 +1,32 @@
import Foundation
import HelderServices
import Testing
@Suite struct TempGitRepoTests {
@Test func createsCommitsAndCleansUp() throws {
var repo: TempGitRepo? = try TempGitRepo()
let root = try #require(repo?.root)
try repo?.commit(["README.md": "hello\n"], message: "first")
try repo?.write("README.md", "hello\nworld\n")
let status = try repo?.run("status", "--porcelain")
#expect(status == " M README.md\n")
#expect(try repo?.run("log", "--format=%s") == "first\n")
repo = nil
#expect(!FileManager.default.fileExists(atPath: root.path))
}
@Test func gitServiceStagesAndCommits() async throws {
let repo = try TempGitRepo()
try repo.commit(["a.txt": "one\n"])
try repo.write("a.txt", "two\n")
let service = GitService(root: repo.root)
#expect(await service.isRepository())
try await service.stage(["a.txt"])
#expect(try repo.run("status", "--porcelain") == "M a.txt\n")
try await service.unstage(["a.txt"])
#expect(try repo.run("status", "--porcelain") == " M a.txt\n")
try await service.stage(["a.txt"])
try await service.commit(message: "second")
#expect(try repo.run("log", "--format=%s") == "second\ncommit\n")
}
}
@@ -0,0 +1,104 @@
import Foundation
import HelderServices
import Testing
@Suite struct FileLoggerTests {
private let noon = Date(timeIntervalSince1970: 1_784_109_600)
private func read(_ dir: TempDirectory, _ name: String = "helder.log") throws -> String {
try dir.read(name)
}
@Test func aLineHoldsTimestampPaddedLevelPidScopeAndMessage() {
let line = FileLogger.formatLine(level: .info, scope: "git", message: "loaded", pid: 42, date: noon)
#expect(line == "2026-07-15T10:00:00.000Z INFO 42 git loaded\n")
}
@Test func continuationLinesAreIndentedSoTheyNeverLookLikeANewEntry() {
let line = FileLogger.formatLine(level: .warn, scope: "console", message: "line one\nline two\r\nline three", pid: 1, date: noon)
#expect(line == "2026-07-15T10:00:00.000Z WARN 1 console line one\n line two\n line three\n")
}
@Test func writingCreatesTheFolderAndAppendsLines() throws {
let dir = try TempDirectory()
let logger = FileLogger(directory: dir.url("a/b"))
logger.write(level: .info, scope: "boot", message: "hello")
logger.write(level: .warn, scope: "boot", message: "careful")
let lines = try dir.read("a/b/helder.log").split(separator: "\n")
#expect(lines.count == 2)
#expect(lines[0].contains("INFO") && lines[0].hasSuffix("boot hello"))
#expect(lines[1].contains("WARN") && lines[1].hasSuffix("careful"))
#expect(logger.fileURL == dir.url("a/b/helder.log"))
}
@Test func linesBelowTheFloorAreDropped() throws {
let dir = try TempDirectory()
let logger = FileLogger(directory: dir.root, minimumLevel: .warn)
logger.write(level: .debug, scope: "x", message: "debug line")
logger.write(level: .info, scope: "x", message: "info line")
logger.write(level: .error, scope: "x", message: "error line")
let out = try read(dir)
#expect(!out.contains("debug line"))
#expect(!out.contains("info line"))
#expect(out.contains("ERROR"))
}
@Test func anUnwritableFolderIsSilentlyIgnored() throws {
let dir = try TempDirectory()
try dir.write("wall", "x")
let logger = FileLogger(directory: dir.url("wall/sub"))
logger.write(level: .error, scope: "x", message: "still fine")
#expect(!dir.exists("wall/sub/helder.log"))
}
@Test func theFileRotatesPastTheCapAndKeepsWriting() throws {
let dir = try TempDirectory()
let logger = FileLogger(directory: dir.root)
let big = String(repeating: "x", count: 4000)
for _ in 0..<700 { logger.write(level: .info, scope: "bulk", message: big) }
#expect(dir.exists("helder.1.log"))
logger.write(level: .info, scope: "after", message: "still logging")
let live = try read(dir)
#expect(live.contains("still logging"))
#expect(live.utf8.count <= FileLogger.maxBytes)
}
@Test func rotationKeepsAtMostThreeOldFiles() throws {
let dir = try TempDirectory()
let logger = FileLogger(directory: dir.root)
let big = String(repeating: "y", count: 100_000)
for _ in 0..<(21 * 5) { logger.write(level: .info, scope: "bulk", message: big) }
#expect(dir.exists("helder.3.log"))
#expect(!dir.exists("helder.4.log"))
}
@Test func aLoggerPicksUpTheSizeOfAnExistingFile() throws {
let dir = try TempDirectory()
try dir.write("helder.log", String(repeating: "z", count: FileLogger.maxBytes - 10))
FileLogger(directory: dir.root).write(level: .info, scope: "x", message: "tips it over")
#expect(dir.exists("helder.1.log"))
#expect(try read(dir).contains("tips it over"))
}
@Test func concurrentWritersNeverInterleaveWithinALine() async throws {
let dir = try TempDirectory()
let logger = FileLogger(directory: dir.root)
await withTaskGroup(of: Void.self) { group in
for i in 0..<8 {
group.addTask { for j in 0..<50 { logger.write(level: .debug, scope: "t\(i)", message: "message \(j)") } }
}
}
let lines = try read(dir).split(separator: "\n")
#expect(lines.count == 400)
#expect(lines.allSatisfy { $0.contains(" DEBUG ") && $0.contains("message ") })
}
@Test func logForwardsToTheInstalledSink() throws {
let dir = try TempDirectory()
let logger = FileLogger(directory: dir.root)
Log.setSink(logger)
Log.info("sink-test-\(dir.root.lastPathComponent)", "forwarded")
Log.setSink(nil)
#expect(try read(dir).contains("forwarded"))
}
}
@@ -0,0 +1,44 @@
import Darwin
import Foundation
import HelderServices
import Testing
/// Children spawned with `posix_spawn`, so nothing but the reaper ever waits on them.
@Suite struct ChildReaperTests {
private func spawn(_ arguments: [String]) throws -> pid_t {
var pid: pid_t = 0
let argv: [UnsafeMutablePointer<CChar>?] = arguments.map { strdup($0) } + [nil]
defer { argv.forEach { free($0) } }
let status = posix_spawn(&pid, arguments[0], nil, nil, argv, environ)
guard status == 0 else { throw POSIXError(POSIXErrorCode(rawValue: status) ?? .EIO) }
return pid
}
/// True while the pid names a process, zombies included.
private func exists(_ pid: pid_t) -> Bool {
kill(pid, 0) == 0 || errno == EPERM
}
@Test(.timeLimit(.minutes(1)))
func aTerminatedChildIsReapedInsteadOfLeftAsAZombie() async throws {
let pid = try spawn(["/bin/sleep", "30"])
kill(pid, SIGTERM)
await ChildReaper.reap(pid, grace: 5)
#expect(!exists(pid))
}
@Test(.timeLimit(.minutes(1)))
func aChildThatIgnoresSigtermIsKilledAfterTheGracePeriod() async throws {
let pid = try spawn(["/bin/sh", "-c", "trap '' TERM; while :; do sleep 1; done"])
kill(pid, SIGTERM)
let started = Date()
await ChildReaper.reap(pid, grace: 0.3)
#expect(!exists(pid))
#expect(Date().timeIntervalSince(started) < 10)
}
@Test func aPidThatIsNotOurChildIsLeftAlone() async throws {
await ChildReaper.reap(1, grace: 0.1)
#expect(exists(1))
}
}
@@ -0,0 +1,65 @@
import Foundation
import HelderServices
import Testing
@Suite struct ProcessRunnerTests {
let runner = ProcessRunner()
@Test func capturesStdoutAndExitCode() async throws {
let result = try await runner.run("echo", ["hello", "world"])
#expect(result == ProcessResult(exitCode: 0, stdout: "hello world\n", stderr: ""))
#expect(result.succeeded)
}
@Test func nonZeroExitIsAResultNotAnError() async throws {
let result = try await runner.run("sh", ["-c", "echo oops >&2; exit 3"])
#expect(result.exitCode == 3)
#expect(result.stderr == "oops\n")
#expect(!result.succeeded)
}
@Test func runsInTheGivenDirectory() async throws {
let dir = URL(fileURLWithPath: "/usr/lib")
let result = try await runner.run("pwd", [], in: dir)
#expect(result.stdout == "/usr/lib\n")
}
@Test func passesTheEnvironment() async throws {
let result = try await runner.run("sh", arguments: ["-c", "printf %s \"$HELDER_TEST\""], in: nil,
environment: ["HELDER_TEST": "yes", "PATH": "/usr/bin:/bin"])
#expect(result.stdout == "yes")
}
@Test func stdinIsClosed() async throws {
let result = try await runner.run("cat", [])
#expect(result == ProcessResult(exitCode: 0, stdout: "", stderr: ""))
}
@Test func largeOutputOnBothPipesDoesNotDeadlock() async throws {
let script = "i=0; while [ $i -lt 20000 ]; do echo line$i; echo err$i >&2; i=$((i+1)); done"
let result = try await runner.run("sh", ["-c", script])
#expect(result.stdout.split(separator: "\n").count == 20000)
#expect(result.stderr.split(separator: "\n").count == 20000)
}
@Test func unknownExecutableThrows() async {
await #expect(throws: ProcessRunnerError.executableNotFound("helder-no-such-tool")) {
try await runner.run("helder-no-such-tool", [])
}
}
@Test func cancellationTerminatesTheChild() async throws {
let started = Date()
let task = Task { try await runner.run("sleep", ["10"]) }
try await Task.sleep(for: .milliseconds(200))
task.cancel()
await #expect(throws: CancellationError.self) { try await task.value }
#expect(Date().timeIntervalSince(started) < 5)
}
@Test func locatorFindsToolsOnThePath() {
#expect(ExecutableLocator.standard.locate("sh")?.path.hasSuffix("/sh") == true)
#expect(ExecutableLocator(directories: []).locate("sh") == nil)
#expect(ExecutableLocator(directories: []).locate("/bin/sh")?.path == "/bin/sh")
}
}
@@ -0,0 +1,49 @@
import Foundation
import HelderCore
import HelderServices
import Testing
@Suite struct ConfigServiceTests {
@Test func aFreshProjectGetsTheDefaultsFileAndTheDefaults() async throws {
let dir = try TempDirectory()
let config = await ConfigService(root: dir.root).resolve()
#expect(config == .defaults)
let written = try Data(contentsOf: dir.url(".helder/config.default.json"))
#expect(try JSONDecoder().decode(HelderConfig.self, from: written) == .defaults)
}
@Test func aSparseConfigMergesOverTheDefaults() async throws {
let dir = try TempDirectory()
try dir.write(".helder/config.json", #"{"ai":{"command":"claude --model opus"},"editor":{"tabSize":2}}"#)
let config = await ConfigService(root: dir.root).resolve()
#expect(config.ai.command == "claude --model opus")
#expect(config.ai.autoLaunch)
#expect(config.editor.tabSize == 2)
#expect(!config.editor.autoSave)
#expect(config.git.confirmDiscard)
}
@Test func theDefaultsFileIsRewrittenWithTheBuiltInValues() async throws {
let dir = try TempDirectory()
try dir.write(".helder/config.json", #"{"ai":{"command":"x"}}"#)
try dir.write(".helder/config.default.json", #"{"ai":{"command":"stale"}}"#)
_ = await ConfigService(root: dir.root).resolve()
let written = try JSONDecoder().decode(HelderConfig.self, from: Data(contentsOf: dir.url(".helder/config.default.json")))
#expect(written.ai.command == "claude")
}
@Test func currentReturnsTheLastResolvedConfig() async throws {
let dir = try TempDirectory()
let service = ConfigService(root: dir.root)
#expect(await service.current() == .defaults)
try dir.write(".helder/config.json", #"{"editor":{"tabSize":8}}"#)
await service.resolve()
#expect(await service.current().editor.tabSize == 8)
}
@Test func anUnwritableProjectStillYieldsTheDefaults() async throws {
let dir = try TempDirectory()
try dir.write(".helder", "a file where the folder should be")
#expect(await ConfigService(root: dir.root).resolve() == .defaults)
}
}
@@ -0,0 +1,46 @@
import Foundation
import HelderCore
import HelderServices
import Testing
@Suite struct ProjectServicesTests {
private func tempDir() throws -> URL {
let url = FileManager.default.temporaryDirectory.appendingPathComponent("helder-test-\(UUID().uuidString)")
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
return url
}
@Test func configServiceWritesDefaultsAndReadsOverrides() async throws {
let root = try tempDir()
defer { try? FileManager.default.removeItem(at: root) }
let folder = root.appendingPathComponent(".helder")
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
try Data(#"{"editor":{"tabSize":2}}"#.utf8).write(to: folder.appendingPathComponent("config.json"))
let config = await ConfigService(root: root).resolve()
#expect(config.editor.tabSize == 2)
#expect(FileManager.default.fileExists(atPath: folder.appendingPathComponent("config.default.json").path))
#expect(try String(contentsOf: folder.appendingPathComponent(".gitignore"), encoding: .utf8) == HelderConfig.gitignoreBody)
}
@Test func notesRoundTrip() async throws {
let root = try tempDir()
defer { try? FileManager.default.removeItem(at: root) }
let notes = NotesService(root: root)
#expect(await notes.read() == "")
try await notes.write("tell the agent\n")
#expect(await notes.read() == "tell the agent\n")
}
@Test func recentProjectsAreNewestFirstAndDeduplicated() async throws {
let dir = try tempDir()
defer { try? FileManager.default.removeItem(at: dir) }
let a = try tempDir(), b = try tempDir()
defer { try? FileManager.default.removeItem(at: a); try? FileManager.default.removeItem(at: b) }
let store = RecentProjectsStore(fileURL: dir.appendingPathComponent("recent.json"))
await store.add(a.path)
await store.add(b.path)
await store.add(a.path)
#expect(await store.list().map(\.path) == [a.standardizedFileURL.path, b.standardizedFileURL.path])
}
}
@@ -0,0 +1,179 @@
import Foundation
import HelderCore
@testable import HelderServices
import Testing
@Suite struct ProjectScannerTests {
private let defaults = ScanFilter(base: IgnoreRules.ripgrepBaseIgnore, files: HelderConfig.Files())
private func walk(_ dir: TempDirectory) -> WalkScanner {
WalkScanner(root: dir.root, runner: ProcessRunner())
}
// MARK: ripgrep arguments
@Test func contentSearchPassesTheOldAppsRipgrepFlags() {
let query = LineQuery(pattern: .smartCaseLiteral("needle"), maxPerFile: 50, maxColumns: 2000)
let args = RipgrepScanner.searchArguments(query, filter: defaults, target: "/p")
#expect(Array(args.prefix(9)) == ["--json", "--fixed-strings", "--smart-case", "--hidden", "--max-count", "50", "--max-columns", "2000", "--glob"])
#expect(args.suffix(4) == ["-e", "needle", "--", "/p"])
#expect(args.contains("!node_modules"))
#expect(args.contains("--no-ignore"))
}
@Test func aRegexSearchOverPHPFilesIsCaseSensitive() {
let filter = ScanFilter(base: IgnoreRules.symbolDeclarationIgnore, files: HelderConfig.Files())
let args = RipgrepScanner.searchArguments(LineQuery(pattern: .regex("^class"), fileExtension: "php"), filter: filter, target: "/p")
#expect(Array(args.prefix(4)) == ["--json", "--hidden", "--glob", "*.php"])
#expect(!args.contains("--smart-case"))
#expect(!args.contains("!vendor"))
#expect(args.suffix(4) == ["-e", "^class", "--", "/p"])
}
@Test func aWordSearchUsesWordRegexp() {
let args = RipgrepScanner.searchArguments(LineQuery(pattern: .word("Agent"), fileExtension: "php"), filter: defaults, target: "/p")
#expect(args.contains("--word-regexp"))
#expect(args.suffix(4) == ["-e", "Agent", "--", "/p"])
}
@Test func fileListingHonoursExcludesAndGitignore() {
var files = HelderConfig.Files()
files.exclude = ["*.log", ""]
files.followGitignore = true
let args = RipgrepScanner.fileArguments(filter: ScanFilter(base: ["vendor"], files: files), target: "/p/src")
#expect(args == ["--files", "--hidden", "--glob", "!vendor", "--glob", "!*.log", "--", "/p/src"])
}
@Test func aMissingRipgrepBinaryYieldsNoResultsInsteadOfThrowing() async {
let scanner = RipgrepScanner(root: URL(fileURLWithPath: "/tmp"), binary: URL(fileURLWithPath: "/nonexistent/rg"),
runner: ProcessRunner())
#expect(await scanner.files(under: nil, filter: defaults).isEmpty)
}
@Test func rgBinaryInTheEnvironmentWinsOverTheLocator() {
#expect(ProjectScanner.ripgrep(locator: Ripgrep.absent, environment: ["RG_BINARY": "/bin/sh"])?.path == "/bin/sh")
#expect(ProjectScanner.ripgrep(locator: Ripgrep.absent, environment: ["RG_BINARY": "/nonexistent"]) == nil)
#expect(ProjectScanner.ripgrep(locator: Ripgrep.absent, environment: [:]) == nil)
}
// MARK: walk
@Test func theWalkListsFilesAndDotfilesButNotTheBaseIgnores() async throws {
let dir = try TempDirectory()
try dir.write("src/a.ts", "a")
try dir.write(".env", "x")
try dir.write(".DS_Store", "x")
try dir.write("node_modules/p/i.js", "x")
try dir.write("lib/vendor/v.php", "x")
#expect(await walk(dir).files(under: nil, filter: defaults) == [".env", "src/a.ts"])
#expect(await walk(dir).files(under: "src", filter: defaults) == ["src/a.ts"])
}
@Test func theWalkSkipsGitignoredFilesOnlyWhenAsked() async throws {
let repo = try TempGitRepo()
try repo.write(".gitignore", "secret.txt\nlogs/\n")
try repo.write("secret.txt", "shh")
try repo.write("logs/today.txt", "x")
try repo.write("keep.txt", "ok")
let scanner = WalkScanner(root: repo.root, runner: ProcessRunner())
#expect(await scanner.files(under: nil, filter: defaults) == [".gitignore", "keep.txt", "logs/today.txt", "secret.txt"])
var following = defaults
following.files.followGitignore = true
#expect(await scanner.files(under: nil, filter: following) == [".gitignore", "keep.txt"])
}
@Test
func theWalkHonoursExcludeGlobs() async throws {
let dir = try TempDirectory()
try dir.write("a.log", "x")
try dir.write("deep/b.log", "x")
try dir.write("keep.txt", "x")
var filter = defaults
filter.files.exclude = ["*.log"]
#expect(await walk(dir).files(under: nil, filter: filter) == ["keep.txt"])
}
@Test func aLowercaseQueryMatchesAnyCase() async throws {
let dir = try TempDirectory()
try dir.write("a.ts", "const x = 1\nconst Balance = 2\n")
let matches = await walk(dir).matches(LineQuery(pattern: .smartCaseLiteral("balance")), filter: defaults)
#expect(matches == [RipgrepMatch(path: dir.root.path + "/a.ts", line: 2, text: "const Balance = 2", byteOffset: 6)])
}
@Test func anUppercaseQueryIsCaseSensitive() async throws {
let dir = try TempDirectory()
try dir.write("a.ts", "balance\nBalance\n")
let matches = await walk(dir).matches(LineQuery(pattern: .smartCaseLiteral("Balance")), filter: defaults)
#expect(matches.map(\.line) == [2])
}
@Test func theByteOffsetCountsUTF8Bytes() async throws {
let dir = try TempDirectory()
try dir.write("a.txt", "héllo wörld\n")
let matches = await walk(dir).matches(LineQuery(pattern: .smartCaseLiteral("wörld")), filter: defaults)
#expect(matches.first?.byteOffset == 7)
}
@Test func theWalkStopsAtTheLimitPerFileAndAtTheFileLimit() async throws {
let dir = try TempDirectory()
for name in ["a", "b", "c"] { try dir.write("\(name).txt", String(repeating: "hit\n", count: 5)) }
let matches = await walk(dir).matches(LineQuery(pattern: .smartCaseLiteral("hit"), maxPerFile: 2, maxFiles: 2), filter: defaults)
#expect(matches.map { "\(PathUtils.basename($0.path)):\($0.line)" } == ["a.txt:1", "a.txt:2", "b.txt:1", "b.txt:2"])
}
@Test func theWalkSkipsBinaryAndOversizedFiles() async throws {
let dir = try TempDirectory()
try dir.write("bin.dat", Data("needle\0".utf8))
try dir.write("big.txt", "needle\n" + String(repeating: "x", count: 400))
try dir.write("ok.txt", "needle\n")
var scanner = walk(dir)
scanner.maxFileBytes = 100
let matches = await scanner.matches(LineQuery(pattern: .smartCaseLiteral("needle")), filter: defaults)
#expect(matches.map { PathUtils.basename($0.path) } == ["ok.txt"])
}
@Test func aRegexQueryReadsOnlyTheRequestedExtension() async throws {
let dir = try TempDirectory()
try dir.write("A.php", "<?php\nnamespace App;\nfinal class A extends B\n")
try dir.write("notes.md", "class NotPHP\n")
let query = LineQuery(pattern: .regex(PHPSymbols.declarationPattern), fileExtension: "php")
let matches = await walk(dir).matches(query, filter: defaults)
#expect(matches.map(\.text) == ["namespace App;", "final class A extends B"])
}
@Test func aWordQueryNeedsWordBoundaries() async throws {
let dir = try TempDirectory()
try dir.write("a.php", "new Agent();\nnew AgentList();\n$x = Agent::class;\n")
let matches = await walk(dir).matches(LineQuery(pattern: .word("Agent")), filter: defaults)
#expect(matches.map(\.line) == [1, 3])
#expect(matches.map(\.byteOffset) == [4, 5])
}
@Test(.enabled(if: Ripgrep.isPresent))
func ripgrepAndTheWalkFindTheSameLines() async throws {
let dir = try TempDirectory()
try dir.write("src/a.php", "<?php\nclass Agent extends Base\n{\n use HasFactory;\n}\n")
try dir.write("src/b.php", "<?php\n$a = new Agent();\n")
try dir.write("vendor/c.php", "<?php\nclass Agent {}\n")
let rg = RipgrepScanner(root: dir.root, binary: try #require(Ripgrep.binary), runner: ProcessRunner())
for query in [LineQuery(pattern: .word("Agent"), fileExtension: "php"),
LineQuery(pattern: .regex(PHPSymbols.declarationPattern), fileExtension: "php"),
LineQuery(pattern: .smartCaseLiteral("agent"))] {
let sort: (RipgrepMatch, RipgrepMatch) -> Bool = { ($0.path, $0.line) < ($1.path, $1.line) }
#expect(await rg.matches(query, filter: defaults).sorted(by: sort) == walk(dir).matches(query, filter: defaults).sorted(by: sort))
}
}
@Test(.enabled(if: Ripgrep.isPresent))
func ripgrepAndTheWalkListTheSameFiles() async throws {
let dir = try TempDirectory()
try dir.write("src/a.ts", "a")
try dir.write(".env", "x")
try dir.write(".DS_Store", "x")
try dir.write("node_modules/p/i.js", "x")
try dir.mkdir("empty")
let rg = RipgrepScanner(root: dir.root, binary: try #require(Ripgrep.binary), runner: ProcessRunner())
#expect(await rg.files(under: nil, filter: defaults) == walk(dir).files(under: nil, filter: defaults))
#expect(await rg.files(under: "src", filter: defaults) == ["src/a.ts"])
}
}
@@ -0,0 +1,128 @@
import Foundation
import HelderCore
import HelderServices
import Testing
@Suite struct RipgrepSearchServiceTests {
private func withRipgrep(_ dir: URL, config: HelderConfig = .defaults) -> RipgrepSearchService {
RipgrepSearchService(root: dir, config: FixedConfig(config: config), locator: Ripgrep.locator, environment: [:])
}
private func withoutRipgrep(_ dir: URL, config: HelderConfig = .defaults) -> RipgrepSearchService {
RipgrepSearchService(root: dir, config: FixedConfig(config: config), locator: Ripgrep.absent, environment: [:])
}
/// a.ts holds "balance" on line 2; b.ts holds nothing relevant.
private func fixture() throws -> TempDirectory {
let dir = try TempDirectory()
try dir.write("a.ts", "const x = 1\nconst balance = 2\n")
try dir.write("b.ts", "nothing relevant\n")
return dir
}
@Test func availabilityFollowsTheLocatorAndRgBinary() async throws {
let dir = try TempDirectory()
#expect(await !withoutRipgrep(dir.root).isAvailable())
let viaEnvironment = RipgrepSearchService(root: dir.root, config: FixedConfig(), locator: Ripgrep.absent,
environment: ["RG_BINARY": "/bin/sh"])
#expect(await viaEnvironment.isAvailable())
}
@Test(.enabled(if: Ripgrep.isPresent))
func ripgrepIsFoundWhereTheOldAppShipsIt() async throws {
let dir = try TempDirectory()
#expect(await withRipgrep(dir.root).isAvailable())
}
@Test(arguments: ["", "a", " b "])
func aQueryUnderTwoCharactersFindsNothing(_ query: String) async throws {
let dir = try fixture()
#expect(await withoutRipgrep(dir.root).searchContent(query).isEmpty)
#expect(await withRipgrep(dir.root).searchContent(query).isEmpty)
}
@Test(.enabled(if: Ripgrep.isPresent))
func ripgrepFindsContentWithLineAndOffset() async throws {
let dir = try fixture()
let groups = await withRipgrep(dir.root).searchContent("balance")
#expect(groups == [ContentGroup(path: "a.ts", hits: [ContentHit(line: 2, text: "const balance = 2", matchOffset: 6)])])
}
@Test
func theWalkFindsContentWithLineAndOffset() async throws {
let dir = try fixture()
let groups = await withoutRipgrep(dir.root).searchContent("balance")
#expect(groups == [ContentGroup(path: "a.ts", hits: [ContentHit(line: 2, text: "const balance = 2", matchOffset: 6)])])
}
@Test
func theWalkCapsHitsPerFile() async throws {
let dir = try TempDirectory()
try dir.write("many.txt", String(repeating: "needle\n", count: SearchLimits.maxHitsPerFile + 10))
let groups = await withoutRipgrep(dir.root).searchContent("needle")
#expect(groups.first?.hits.count == SearchLimits.maxHitsPerFile)
}
@Test(.enabled(if: Ripgrep.isPresent))
func ripgrepContentSearchSkipsExcludedFiles() async throws {
let dir = try fixture()
try dir.write("node_modules/p/index.js", "balance\n")
try dir.write("build.log", "balance\n")
var config = HelderConfig.defaults
config.files.exclude = ["*.log"]
#expect(await withRipgrep(dir.root, config: config).searchContent("balance").map(\.path) == ["a.ts"])
}
@Test(.enabled(if: Ripgrep.isPresent))
func ripgrepListsFilesIncludingDotfiles() async throws {
let dir = try fixture()
try dir.write(".env", "APP_NAME=x\n")
try dir.write(".DS_Store", "x")
try dir.write("node_modules/p/index.js", "x")
#expect(await withRipgrep(dir.root).listFiles(under: nil) == [".env", "a.ts", "b.ts"])
}
@Test(.enabled(if: Ripgrep.isPresent))
func ripgrepListsOneSubtreeWithRootRelativePaths() async throws {
let dir = try fixture()
try dir.write("src/deep/c.ts", "c")
#expect(await withRipgrep(dir.root).listFiles(under: "src") == ["src/deep/c.ts"])
}
@Test(.enabled(if: Ripgrep.isPresent))
func ripgrepShowsGitignoredFilesUnlessTheConfigFollowsGitignore() async throws {
let repo = try TempGitRepo()
try repo.write(".gitignore", "secret.txt\n")
try repo.write("secret.txt", "shh")
try repo.write("keep.txt", "ok")
#expect(await withRipgrep(repo.root).listFiles(under: nil) == [".gitignore", "keep.txt", "secret.txt"])
var config = HelderConfig.defaults
config.files.followGitignore = true
#expect(await withRipgrep(repo.root, config: config).listFiles(under: nil) == [".gitignore", "keep.txt"])
}
@Test(.enabled(if: Ripgrep.isPresent))
func ripgrepHonoursExcludeGlobs() async throws {
let dir = try fixture()
try dir.write("logs/today.log", "x")
var config = HelderConfig.defaults
config.files.exclude = ["*.log"]
#expect(await withRipgrep(dir.root, config: config).listFiles(under: nil) == ["a.ts", "b.ts"])
}
@Test func theWalkListsFilesWithoutRipgrep() async throws {
let dir = try fixture()
try dir.write(".env", "x")
try dir.write("vendor/x.php", "x")
try dir.write("src/c.ts", "c")
let search = withoutRipgrep(dir.root)
#expect(await search.listFiles(under: nil) == [".env", "a.ts", "b.ts", "src/c.ts"])
#expect(await search.listFiles(under: "src") == ["src/c.ts"])
}
@Test func listingOutsideTheProjectIsEmpty() async throws {
let dir = try fixture()
#expect(await withoutRipgrep(dir.root).listFiles(under: "..").isEmpty)
#expect(await withRipgrep(dir.root).listFiles(under: "../..").isEmpty)
}
}
@@ -0,0 +1,38 @@
import Foundation
/// A small case-sensitive APFS disk image, attached for one test and detached on deinit.
final class CaseSensitiveVolume {
let root: URL
private let image: URL
init() throws {
let base = FileManager.default.temporaryDirectory
.appendingPathComponent("helder-cs-\(UUID().uuidString)")
.resolvingSymlinksInPath()
try FileManager.default.createDirectory(at: base, withIntermediateDirectories: true)
image = base.appendingPathComponent("volume.dmg")
root = base.appendingPathComponent("mount")
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
try Self.hdiutil(["create", "-quiet", "-size", "8m", "-fs", "Case-sensitive APFS", "-volname", "HelderCS", image.path])
try Self.hdiutil(["attach", "-quiet", "-nobrowse", "-mountpoint", root.path, image.path])
}
deinit {
try? Self.hdiutil(["detach", "-quiet", "-force", root.path])
try? FileManager.default.removeItem(at: image.deletingLastPathComponent())
}
private static func hdiutil(_ arguments: [String]) throws {
let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/bin/hdiutil")
process.arguments = arguments
process.standardInput = FileHandle.nullDevice
process.standardOutput = FileHandle.nullDevice
process.standardError = FileHandle.nullDevice
try process.run()
process.waitUntilExit()
guard process.terminationStatus == 0 else {
throw NSError(domain: "hdiutil", code: Int(process.terminationStatus), userInfo: [NSLocalizedDescriptionKey: arguments.joined(separator: " ")])
}
}
}
@@ -0,0 +1,106 @@
import Foundation
import HelderCore
import HelderServices
/// A config service that always returns the same config.
struct FixedConfig: ConfigServicing {
var config = HelderConfig.defaults
func resolve() async -> HelderConfig { config }
func current() async -> HelderConfig { config }
}
/// A search service without ripgrep, which sends FileService down its walk.
struct NoRipgrepSearch: SearchServicing {
func isAvailable() async -> Bool { false }
func searchContent(_ query: String) async -> [ContentGroup] { [] }
func listFiles(under directory: String?) async -> [String] { [] }
}
/// One process call a `ScriptedRunner` saw.
struct RecordedCall: Sendable, Equatable {
var executable: String
var arguments: [String]
var environment: [String: String]?
}
/// Records every call and answers from a script; for tests of argument construction and error paths.
final class ScriptedRunner: ProcessRunning, @unchecked Sendable {
private let lock = NSLock()
private var recorded: [RecordedCall] = []
private let respond: @Sendable (RecordedCall) async throws -> ProcessResult
init(_ respond: @escaping @Sendable (RecordedCall) async throws -> ProcessResult) {
self.respond = respond
}
var calls: [RecordedCall] {
lock.withLock { recorded }
}
func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?) async throws -> ProcessResult {
let call = RecordedCall(executable: executable, arguments: arguments, environment: environment)
lock.withLock { recorded.append(call) }
return try await respond(call)
}
}
enum Ripgrep {
/// `$RG_BINARY`, or the ripgrep in `vendor/ripgrep`; nil when neither exists.
static var binary: URL? {
if let env = ProcessInfo.processInfo.environment["RG_BINARY"], FileManager.default.isExecutableFile(atPath: env) {
return URL(fileURLWithPath: env)
}
let packageRoot = URL(fileURLWithPath: #filePath)
.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
let bundled = packageRoot.appendingPathComponent("vendor/ripgrep/rg")
return FileManager.default.isExecutableFile(atPath: bundled.path) ? bundled : nil
}
static var isPresent: Bool { binary != nil }
/// A locator that finds only that ripgrep.
static var locator: ExecutableLocator {
ExecutableLocator(directories: binary.map { [$0.deletingLastPathComponent().path] } ?? [])
}
/// A locator that finds no ripgrep, whatever is installed.
static let absent = ExecutableLocator(directories: [])
}
/// Polls until `condition` holds or `timeout` passes; returns whether it held.
func eventually(timeout: TimeInterval = 5, _ condition: () -> Bool) async -> Bool {
let deadline = Date().addingTimeInterval(timeout)
while Date() < deadline {
if condition() { return true }
try? await Task.sleep(nanoseconds: 20_000_000)
}
return condition()
}
/// Polls an async condition until it holds or `timeout` passes; returns whether it held.
func eventuallyAsync(timeout: TimeInterval = 5, _ condition: () async -> Bool) async -> Bool {
let deadline = Date().addingTimeInterval(timeout)
while Date() < deadline {
if await condition() { return true }
try? await Task.sleep(nanoseconds: 5_000_000)
}
return await condition()
}
/// Holds every waiter until `open()`; waiters arriving after that pass straight through.
actor Gate {
private var isOpen = false
private var waiters: [CheckedContinuation<Void, Never>] = []
func wait() async {
if isOpen { return }
await withCheckedContinuation { waiters.append($0) }
}
func open() {
isOpen = true
waiters.forEach { $0.resume() }
waiters = []
}
}
@@ -0,0 +1,44 @@
import Foundation
/// A throwaway folder, removed on deinit.
final class TempDirectory {
let root: URL
init() throws {
root = FileManager.default.temporaryDirectory
.appendingPathComponent("helder-test-\(UUID().uuidString)")
.resolvingSymlinksInPath()
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
}
deinit {
try? FileManager.default.removeItem(at: root)
}
func url(_ path: String) -> URL {
root.appendingPathComponent(path)
}
/// Writes a file relative to the root, creating folders as needed.
func write(_ path: String, _ contents: String) throws {
try write(path, Data(contents.utf8))
}
func write(_ path: String, _ data: Data) throws {
let url = url(path)
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
try data.write(to: url)
}
func mkdir(_ path: String) throws {
try FileManager.default.createDirectory(at: url(path), withIntermediateDirectories: true)
}
func read(_ path: String) throws -> String {
try String(contentsOf: url(path), encoding: .utf8)
}
func exists(_ path: String) -> Bool {
FileManager.default.fileExists(atPath: url(path).path)
}
}
@@ -0,0 +1,74 @@
import Foundation
import HelderServices
/// A throwaway git repository in a temp folder, removed on deinit. For integration tests.
final class TempGitRepo {
let root: URL
private let git: URL
/// Creates the folder, runs `git init -b main`, and sets a local user so commits work anywhere.
/// A bare repository serves as a push remote.
init(bare: Bool = false) throws {
guard let git = ExecutableLocator.standard.locate("git") else {
throw ProcessRunnerError.executableNotFound("git")
}
self.git = git
root = FileManager.default.temporaryDirectory
.appendingPathComponent("helder-test-\(UUID().uuidString)")
.resolvingSymlinksInPath()
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
if bare {
try run("init", "-q", "--bare", "-b", "main")
return
}
try run("init", "-q", "-b", "main")
try run("config", "user.name", "Helder Tests")
try run("config", "user.email", "tests@helder.invalid")
try run("config", "commit.gpgsign", "false")
}
deinit {
try? FileManager.default.removeItem(at: root)
}
/// Writes a file relative to the root, creating folders as needed.
func write(_ path: String, _ contents: String) throws {
let url = root.appendingPathComponent(path)
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
try Data(contents.utf8).write(to: url)
}
func read(_ path: String) throws -> String {
try String(contentsOf: root.appendingPathComponent(path), encoding: .utf8)
}
/// Writes the files, stages everything and commits.
func commit(_ files: [String: String] = [:], message: String = "commit") throws {
for (path, contents) in files { try write(path, contents) }
try run("add", "-A")
try run("commit", "-q", "--allow-empty", "-m", message)
}
/// Runs git synchronously in the repo and returns stdout; throws on a non-zero exit.
@discardableResult
func run(_ arguments: String...) throws -> String {
let process = Process()
process.executableURL = git
process.arguments = arguments
process.currentDirectoryURL = root
process.standardInput = FileHandle.nullDevice
let out = Pipe()
let err = Pipe()
process.standardOutput = out
process.standardError = err
try process.run()
let data = out.fileHandleForReading.readDataToEndOfFile()
let errData = err.fileHandleForReading.readDataToEndOfFile()
process.waitUntilExit()
guard process.terminationStatus == 0 else {
throw GitError.commandFailed(arguments: arguments, exitCode: process.terminationStatus,
stderr: String(decoding: errData, as: UTF8.self))
}
return String(decoding: data, as: UTF8.self)
}
}
@@ -0,0 +1,111 @@
import Foundation
import HelderCore
import HelderServices
import Testing
/// Each test runs once through ripgrep (when present) and once through the walk.
@Suite struct SymbolServiceTests {
enum Engine: String, CaseIterable, Sendable { case ripgrep, walk }
private static let engines: [Engine] = Ripgrep.isPresent ? Engine.allCases : [.walk]
private func service(_ root: URL, _ engine: Engine) -> SymbolService {
SymbolService(root: root, config: FixedConfig(), runner: ProcessRunner(),
locator: engine == .ripgrep ? Ripgrep.locator : Ripgrep.absent, environment: [:])
}
/// A small Laravel-shaped project: a model with a trait, a controller using it, and a vendor class.
private func project() throws -> TempDirectory {
let dir = try TempDirectory()
try dir.write("app/Models/Agent.php", """
<?php
namespace App\\Models;
use Illuminate\\Database\\Eloquent\\Model;
final class Agent extends Model implements HasLabel
{
use HasFactory, Notifiable;
public function run(): void {}
}
""")
try dir.write("app/Http/AgentController.php", """
<?php
namespace App\\Http;
use App\\Models\\Agent;
class AgentController
{
public function show(): Agent
{
return new Agent();
}
}
""")
try dir.write("vendor/laravel/Model.php", "<?php\nnamespace Illuminate\\Database\\Eloquent;\nabstract class Model {}\nclass Agent {}\n")
try dir.write("vendor/laravel/Uses.php", "<?php\n$x = new Agent();\n")
return dir
}
@Test func aNonIdentifierLooksUpNothing() async throws {
let dir = try TempDirectory()
let symbols = service(dir.root, .walk)
#expect(await symbols.lookup("not a name") == .empty("not a name"))
#expect(await symbols.lookup("$agent") == .empty("$agent"))
}
@Test(arguments: engines)
func namesIncludeProjectAndVendorDeclarations(_ engine: Engine) async throws {
let dir = try project()
#expect(await service(dir.root, engine).names() == ["Agent", "AgentController", "Model"])
}
@Test(arguments: engines)
func lookupListsTheProjectDeclarationFirstWithItsNamespaceAndTraits(_ engine: Engine) async throws {
let dir = try project()
let result = await service(dir.root, engine).lookup("Agent")
#expect(result.definitions == [
SymbolDef(name: "Agent", path: "app/Models/Agent.php", line: 7, kind: "class", namespace: "App\\Models",
parents: ["Model"], interfaces: ["HasLabel"], traits: ["HasFactory", "Notifiable"]),
SymbolDef(name: "Agent", path: "vendor/laravel/Model.php", line: 4, kind: "class",
namespace: "Illuminate\\Database\\Eloquent"),
])
}
@Test(arguments: engines)
func referencesSkipImportsDeclarationsAndVendor(_ engine: Engine) async throws {
let dir = try project()
let result = await service(dir.root, engine).lookup("Agent")
#expect(result.references == [RefGroup(path: "app/Http/AgentController.php", hits: [
ContentHit(line: 9, text: " public function show(): Agent", matchOffset: 28),
ContentHit(line: 11, text: " return new Agent();", matchOffset: 19),
])])
#expect(result.referenceCount == 2)
}
@Test(arguments: engines)
func invalidateMakesTheNextCallSeeANewClass(_ engine: Engine) async throws {
let dir = try project()
let symbols = service(dir.root, engine)
#expect(await !symbols.names().contains("Fresh"))
try dir.write("app/Fresh.php", "<?php\nenum Fresh: string {}\n")
#expect(await !symbols.names().contains("Fresh"))
await symbols.invalidate()
#expect(await symbols.names().contains("Fresh"))
}
@Test(arguments: engines)
func concurrentCallersShareOneIndex(_ engine: Engine) async throws {
let dir = try project()
let symbols = service(dir.root, engine)
let results = await withTaskGroup(of: Set<String>.self) { group in
for _ in 0..<8 { group.addTask { await symbols.names() } }
return await group.reduce(into: [Set<String>]()) { $0.append($1) }
}
#expect(Set(results).count == 1)
}
}