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)
}
}