Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123import Foundationimport Testing
@testable import ParcelConfig
@Suite(.timeLimit(.minutes(1)))struct ConfigStoreTests { @Test func defaultURLUsesTheCurrentHomeDirectory() { let expected = FileManager.default.homeDirectoryForCurrentUser .appendingPathComponent(".config/parcel/parcel.toml") #expect(ConfigStore.defaultFileURL == expected) }
@Test func initialSnapshotHasExplicitUnloadedDefaults() async { let store = ConfigStore() let snapshot = await store.snapshot #expect(snapshot.activeConfiguration == .defaults) #expect(snapshot.activeSource == .defaults) #expect(snapshot.lastGoodDocument == nil) #expect(snapshot.attemptedSource == nil) #expect(snapshot.loadState == .notLoaded) #expect(snapshot.diagnostics.isEmpty) #expect(await !store.isWatching) }
@Test func sourceLoadingPreservesCommentsAndUnicode() async { let store = ConfigStore() let source = "# 改善 café\n[layout]\nratio = 0.6 # Keep this comment.\n" let snapshot = await store.load(source: source) #expect(snapshot.activeConfiguration.layout.global.ratio == 0.6) #expect(snapshot.activeSource == .sourceText) #expect(snapshot.attemptedSource == .sourceText) #expect(snapshot.loadState == .loaded) #expect(snapshot.lastGoodDocument?.render() == source) #expect(snapshot.diagnostics.isEmpty) }
@Test func rejectedAppearanceReloadKeepsColorsAndGeometryUntilRecovery() async throws { let store = ConfigStore() let source = "[appearance]\npalette = 'kiln'\nmode = 'dark'\nactive-border-color = '#A1B2C3'\nborder-radius = 12.5\n" let good = await store.load(source: source) #expect(good.loadState == .loaded) #expect(good.activeConfiguration.appearance.palette == .kiln) let rejected = await store.load(source: "[appearance]\npalette = 'tide'\nactive-border-color = '#123'\n") #expect(rejected.loadState == .rejected) #expect(rejected.activeConfiguration == good.activeConfiguration) #expect(rejected.lastGoodDocument?.render() == source) let error = try #require(rejected.diagnostics.first) #expect(error.severity == .error) #expect(error.location.line == 3) let recovered = await store.load(source: "[appearance]\npalette = 'rose'\nborder-opacity = 0.5\n") #expect(recovered.loadState == .loaded) #expect(recovered.diagnostics.isEmpty) #expect(recovered.activeConfiguration.appearance == AppearanceConfiguration(palette: .rose, borderOpacity: 0.5)) }
@Test func initiallyInvalidSyntaxKeepsDefaultsAndParserLocation() async throws { let store = ConfigStore() let snapshot = await store.load(source: "[layout]\nratio = \n") #expect(snapshot.activeConfiguration == .defaults) #expect(snapshot.activeSource == .defaults) #expect(snapshot.lastGoodDocument == nil) #expect(snapshot.loadState == .rejected) let diagnostic = try #require(snapshot.diagnostics.first) #expect(diagnostic.severity == .error) #expect(diagnostic.location.line == 2) #expect(diagnostic.location.column > 1) }
@Test func initiallyInvalidSchemaKeepsDefaultsAndValidatorDiagnostics() async throws { let store = ConfigStore() let source = "[motion]\nspeed = -1\n" let expected = ConfigValidator.validate(try TOMLDocument(parsing: source)).diagnostics let snapshot = await store.load(source: source) #expect(snapshot.activeConfiguration == .defaults) #expect(snapshot.activeSource == .defaults) #expect(snapshot.lastGoodDocument == nil) #expect(snapshot.loadState == .rejected) #expect(snapshot.diagnostics == expected) #expect(snapshot.diagnostics.first?.location.line == 2) }
@Test(arguments: ["[layout]\nratio =\n", "[layout]\nratio = 8\n"]) func rejectedSourceKeepsTheLastGoodConfigurationAndDocument(invalid: String) async { let store = ConfigStore() let source = "# Original formatting\n[layout]\nratio=0.6\n" let good = await store.load(source: source) let rejected = await store.load(source: invalid) #expect(rejected.activeConfiguration == good.activeConfiguration) #expect(rejected.activeSource == good.activeSource) #expect(rejected.lastGoodDocument?.render() == source) #expect(rejected.loadState == .rejected) #expect(rejected.diagnostics.contains { $0.severity == .error }) }
@Test func validConfigurationWithWarningsStillBecomesLastGood() async { let store = ConfigStore() let source = "unknown-setting = true\n[layout]\nratio = 0.6\n" let snapshot = await store.load(source: source) #expect(snapshot.loadState == .loaded) #expect(snapshot.activeConfiguration.layout.global.ratio == 0.6) #expect(snapshot.lastGoodDocument?.render() == source) #expect(snapshot.diagnostics.count == 1) #expect(snapshot.diagnostics.first?.severity == .warning) }
@Test func retiredAutomaticTilingBindingLoadsWarnsAndRecoversWithoutChangingTheFile() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let source = "[layout]\ndefault = 'side'\n[keybindings]\n pause-tiling = 'ctrl-alt-p'\n" try fixture.write(source) let store = ConfigStore(fileURL: fixture.fileURL) let stream = await store.updates() var updates = stream.makeAsyncIterator() #expect(await updates.next()?.loadState == .notLoaded) let loaded = await store.reload() #expect(loaded.loadState == .loaded) #expect(loaded.activeSource == .file(fixture.fileURL)) #expect(loaded.lastGoodDocument?.render() == source) #expect(loaded.activeConfiguration.keybindings[.toggleAutomaticTiling] == nil) #expect(loaded.activeConfiguration.layout.global.defaultLayout == .side) #expect(loaded.diagnostics.count == 1) let warning = try #require(loaded.diagnostics.first) #expect(warning.severity == .warning) #expect(warning.location.line == 4) #expect(warning.location.column == 3) #expect(warning.message.contains("toggle-automatic-tiling")) #expect(await updates.next()?.diagnostics == loaded.diagnostics) #expect(try String(contentsOf: fixture.fileURL, encoding: .utf8) == source) try fixture.write( source.replacingOccurrences(of: "pause-tiling = 'ctrl-alt-p'", with: "toggle-automatic-tiling = 'cmd-f20'")) let recovered = await store.reload() #expect(recovered.loadState == .loaded) #expect(recovered.diagnostics.isEmpty) #expect( recovered.activeConfiguration.keybindings[.toggleAutomaticTiling] == KeyChord(modifiers: .cmd, key: .f20)) #expect(recovered.activeConfiguration.layout == loaded.activeConfiguration.layout) }
@Test func goodSourceRecoversAndClearsOldDiagnostics() async { let store = ConfigStore() await store.load(source: "[motion]\nspeed = -1\n") let source = "[motion]\nenabled = false\n" let recovered = await store.load(source: source) #expect(recovered.loadState == .loaded) #expect(!recovered.activeConfiguration.motion.enabled) #expect(recovered.lastGoodDocument?.render() == source) #expect(recovered.diagnostics.isEmpty) }
@Test func missingInitialFileReportsDefaultsWithoutCreatingAFile() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let store = ConfigStore(fileURL: fixture.fileURL) let snapshot = await store.reload() #expect(snapshot.loadState == .missingFileUsingDefaults) #expect(snapshot.activeConfiguration == .defaults) #expect(snapshot.activeSource == .defaults) #expect(snapshot.attemptedSource == .file(fixture.fileURL)) #expect(snapshot.lastGoodDocument == nil) #expect(snapshot.diagnostics.first?.severity == .warning) #expect(snapshot.diagnostics.first?.location == SourceLocation()) #expect(!FileManager.default.fileExists(atPath: fixture.fileURL.path)) }
@Test func utf8FileLoadingReportsItsOrigin() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let source = "# 配置\n[layout]\nratio = 0.6\n" try fixture.write(source) let store = ConfigStore(fileURL: fixture.fileURL) let snapshot = await store.reload() #expect(snapshot.activeSource == .file(fixture.fileURL)) #expect(snapshot.activeConfiguration.layout.global.ratio == 0.6) #expect(snapshot.lastGoodDocument?.render() == source) #expect(snapshot.diagnostics.isEmpty) }
@Test func initialInvalidFileReportsProblemsWithoutBecomingActive() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } try fixture.write("[motion]\nspeed = -1\n") let store = ConfigStore(fileURL: fixture.fileURL) let snapshot = await store.reload() #expect(snapshot.loadState == .rejected) #expect(snapshot.activeConfiguration == .defaults) #expect(snapshot.activeSource == .defaults) #expect(snapshot.attemptedSource == .file(fixture.fileURL)) #expect(snapshot.lastGoodDocument == nil) #expect(snapshot.diagnostics.first?.location.line == 2) }
@Test func invalidUTF8IsRejectedWithoutLossyDecoding() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } try fixture.write("[layout]\nratio = 0.6\n") let store = ConfigStore(fileURL: fixture.fileURL) let good = await store.reload() try Data([0xFF, 0xFE, 0x61]).write(to: fixture.fileURL) let bad = await store.reload() #expect(bad.loadState == .rejected) #expect(bad.activeConfiguration == good.activeConfiguration) #expect(bad.lastGoodDocument?.source == good.lastGoodDocument?.source) #expect(bad.activeSource == good.activeSource) #expect(bad.diagnostics.first?.severity == .error) #expect(bad.diagnostics.first?.location == SourceLocation()) #expect(bad.diagnostics.first?.message.contains("UTF-8") == true) }
@Test func deletingAFileWhoseValuesEqualDefaultsStillPreservesItsDocument() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let source = "# Intentionally use the defaults.\n" try fixture.write(source) let store = ConfigStore(fileURL: fixture.fileURL) await store.reload() try FileManager.default.removeItem(at: fixture.fileURL) let missing = await store.reload() #expect(missing.activeConfiguration == .defaults) #expect(missing.activeSource == .file(fixture.fileURL)) #expect(missing.lastGoodDocument?.source == source) #expect(missing.loadState == .rejected) #expect(missing.diagnostics.first?.severity == .error) }
@Test func directoryReadFailureKeepsLastGoodAndIdentifiesTheAttemptedFile() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } try FileManager.default.createDirectory(at: fixture.fileURL, withIntermediateDirectories: false) let store = ConfigStore(fileURL: fixture.fileURL) let good = await store.load(source: "[motion]\nenabled = false\n") let failed = await store.reload() #expect(failed.loadState == .rejected) #expect(failed.activeConfiguration == good.activeConfiguration) #expect(failed.lastGoodDocument?.source == good.lastGoodDocument?.source) #expect(failed.activeSource == .sourceText) #expect(failed.attemptedSource == .file(fixture.fileURL)) #expect(failed.diagnostics.first?.severity == .error) #expect(failed.diagnostics.first?.location == SourceLocation()) }
@Test func unreadableFileReportsAnIOErrorAndRecovers() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } try fixture.write("[layout]\nratio = 0.6\n") let store = ConfigStore(fileURL: fixture.fileURL) let good = await store.reload() try FileManager.default.setAttributes([.posixPermissions: 0], ofItemAtPath: fixture.fileURL.path) let failed = await store.reload() try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: fixture.fileURL.path) #expect(failed.loadState == .rejected) #expect(failed.activeConfiguration == good.activeConfiguration) #expect(failed.lastGoodDocument?.source == good.lastGoodDocument?.source) #expect(failed.diagnostics.first?.severity == .error) let recovered = await store.reload() #expect(recovered.loadState == .loaded) #expect(recovered.diagnostics.isEmpty) }
@Test func nonFileURLsAreRejectedWithoutNetworkAccess() async throws { let url = try #require(URL(string: "https://example.invalid/parcel.toml")) let store = ConfigStore(fileURL: url) let snapshot = await store.reload() #expect(snapshot.loadState == .rejected) #expect(snapshot.activeConfiguration == .defaults) #expect(snapshot.diagnostics.first?.severity == .error) }
@Test func symbolicLinksLoadTheirTarget() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let target = fixture.directory.appendingPathComponent("target.toml") let source = "[motion]\nenabled = false\n" try Data(source.utf8).write(to: target) try FileManager.default.createSymbolicLink(at: fixture.fileURL, withDestinationURL: target) let store = ConfigStore(fileURL: fixture.fileURL) let snapshot = await store.reload() #expect(snapshot.loadState == .loaded) #expect(snapshot.activeSource == .file(fixture.fileURL)) #expect(snapshot.lastGoodDocument?.source == source) }
@Test func watcherFollowsAtomicReplacement() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let original = "[layout]\nratio = 0.6\n" let replacement = "[layout]\nratio = 0.7\n" try fixture.write(original) try await fixture.withWatchingStore { store in _ = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == original } let stream = await store.updates() var iterator = stream.makeAsyncIterator() #expect(await iterator.next()?.lastGoodDocument?.source == original) try fixture.write(replacement, atomic: true) let snapshot = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == replacement } #expect(snapshot.activeConfiguration.layout.global.ratio == 0.7) #expect(snapshot.loadState == .loaded) #expect(await iterator.next()?.lastGoodDocument?.source == replacement) } }
@Test func watcherRearmsAfterRepeatedAtomicSaves() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } try fixture.write("version = 1") try await fixture.withWatchingStore { store in _ = try await waitForSnapshot(store) { $0.loadState == .loaded } for index in 0..<3 { let source = "# Save \(index)\nversion = 1" try fixture.write(source, atomic: true) _ = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == source } let edited = source + "\n# In place" try fixture.writeInPlace(edited) _ = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == edited } } } }
@Test func watcherFollowsFileDeletionAndRecreation() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let source = "[motion]\nenabled = false\n" try fixture.write(source) try await fixture.withWatchingStore { store in _ = try await waitForSnapshot(store) { $0.loadState == .loaded } try FileManager.default.removeItem(at: fixture.fileURL) let missing = try await waitForSnapshot(store) { $0.loadState == .rejected } #expect(missing.lastGoodDocument?.source == source) try fixture.write(source) let recreated = try await waitForSnapshot(store) { $0.loadState == .loaded && $0.lastGoodDocument?.source == source } #expect(recreated.lastGoodDocument?.source == source) #expect(recreated.diagnostics.isEmpty) try fixture.writeInPlace("version = 1") _ = try await waitForSnapshot(store) { $0.activeConfiguration.motion.enabled } } }
@Test func watcherFollowsEditsThroughASymlinkAndTargetReplacement() async throws { let fixture = try TemporaryConfigFile() let target = try TemporaryConfigFile() defer { fixture.remove() target.remove() } try target.write("version = 1") try FileManager.default.createSymbolicLink(at: fixture.fileURL, withDestinationURL: target.fileURL) try await fixture.withWatchingStore { store in _ = try await waitForSnapshot(store) { $0.loadState == .loaded } let edited = "[motion]\nenabled = false\n" try fixture.writeInPlace(edited) _ = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == edited } let replacement = "[layout]\nratio = 0.7\n" try target.write(replacement, atomic: true) _ = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == replacement } try target.writeInPlace(edited) _ = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == edited } try FileManager.default.removeItem(at: target.fileURL) _ = try await waitForSnapshot(store) { $0.loadState == .rejected } try target.write(replacement) let recreated = try await waitForSnapshot(store) { $0.loadState == .loaded } #expect(recreated.lastGoodDocument?.source == replacement) #expect(recreated.activeSource == .file(fixture.fileURL)) } }
@Test func watcherFollowsRelativeDanglingSymlinkAndRetargeting() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let target = fixture.directory.appendingPathComponent("nested/target.toml") try FileManager.default.createSymbolicLink( atPath: fixture.fileURL.path, withDestinationPath: "nested/target.toml") try await fixture.withWatchingStore { store in _ = try await waitForSnapshot(store) { $0.loadState == .missingFileUsingDefaults } try FileManager.default.createDirectory( at: target.deletingLastPathComponent(), withIntermediateDirectories: true) try Data("version = 1".utf8).write(to: target) _ = try await waitForSnapshot(store) { $0.loadState == .loaded } let other = fixture.directory.appendingPathComponent("other.toml") let source = "[motion]\nenabled = false\n" try Data(source.utf8).write(to: other) try FileManager.default.removeItem(at: fixture.fileURL) try FileManager.default.createSymbolicLink(atPath: fixture.fileURL.path, withDestinationPath: "other.toml") _ = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == source } try fixture.writeInPlace("version = 1") _ = try await waitForSnapshot(store) { $0.activeConfiguration.motion.enabled } } }
@Test func watcherLoadsAfterMissingAncestorDirectoriesAreCreated() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let file = fixture.directory.appendingPathComponent("one/two/parcel.toml") let store = ConfigStore(fileURL: file) try await store.startWatching() do { _ = try await waitForSnapshot(store) { $0.loadState == .missingFileUsingDefaults } try FileManager.default.createDirectory( at: file.deletingLastPathComponent(), withIntermediateDirectories: true) try Data("version = 1".utf8).write(to: file) _ = try await waitForSnapshot(store) { $0.loadState == .loaded } } catch { await store.stopWatching() throw error } await store.stopWatching() }
@Test func watcherDetectsSameSizeInPlaceWritesWithRestoredModificationTime() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let original = "[layout]\nratio = 0.6\n" let replacement = "[layout]\nratio = 0.7\n" #expect(original.utf8.count == replacement.utf8.count) try fixture.write(original) let values = try fixture.fileURL.resourceValues(forKeys: [.contentModificationDateKey]) let modified = try #require(values.contentModificationDate) try await fixture.withWatchingStore { store in _ = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == original } try fixture.writeInPlace(replacement) try FileManager.default.setAttributes([.modificationDate: modified], ofItemAtPath: fixture.fileURL.path) let snapshot = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == replacement } #expect(snapshot.activeConfiguration.layout.global.ratio == 0.7) } }
@Test func watcherRecoversFromBadSyntaxToGoodContent() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let original = "# Last good\n[layout]\nratio = 0.6\n" try fixture.write(original) try await fixture.withWatchingStore { store in _ = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == original } try fixture.write("[layout]\nratio =\n", atomic: true) let failed = try await waitForSnapshot(store) { $0.loadState == .rejected } #expect(failed.lastGoodDocument?.source == original) #expect(failed.activeConfiguration.layout.global.ratio == 0.6) #expect(failed.diagnostics.first?.location.line == 2) let replacement = "# Recovered\n[layout]\nratio = 0.8\n" try fixture.write(replacement, atomic: true) let recovered = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == replacement } #expect(recovered.loadState == .loaded) #expect(recovered.diagnostics.isEmpty) } }
@Test func watcherFollowsDeletionAndRecreationOfTheParentDirectory() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let source = "[layout]\nratio = 0.6\n" try fixture.write(source) try await fixture.withWatchingStore { store in _ = try await waitForSnapshot(store) { $0.loadState == .loaded } try FileManager.default.removeItem(at: fixture.directory) let missing = try await waitForSnapshot(store) { $0.loadState == .rejected } #expect(missing.lastGoodDocument?.source == source) #expect(missing.activeSource == .file(fixture.fileURL)) #expect(missing.diagnostics.first?.severity == .error) try FileManager.default.createDirectory(at: fixture.directory, withIntermediateDirectories: true) try fixture.write(source) let recreated = try await waitForSnapshot(store) { $0.loadState == .loaded } #expect(recreated.lastGoodDocument?.source == source) #expect(recreated.diagnostics.isEmpty) } }
@Test(arguments: [false, true]) func watcherFollowsAncestorRenameAndRecreation(throughSymlink: Bool) async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let outer = fixture.directory.appendingPathComponent("outer") let target = outer.appendingPathComponent("inner/parcel.toml") try FileManager.default.createDirectory( at: target.deletingLastPathComponent(), withIntermediateDirectories: true) try Data("[layout]\nratio = 0.6\n".utf8).write(to: target) if throughSymlink { try FileManager.default.createSymbolicLink(at: fixture.fileURL, withDestinationURL: target) } let store = ConfigStore(fileURL: throughSymlink ? fixture.fileURL : target) try await store.startWatching() do { _ = try await waitForSnapshot(store) { $0.loadState == .loaded } try FileManager.default.moveItem(at: outer, to: fixture.directory.appendingPathComponent("moved")) let missing = try await waitForSnapshot(store) { $0.loadState == .rejected } #expect(missing.activeConfiguration.layout.global.ratio == 0.6) try FileManager.default.createDirectory( at: target.deletingLastPathComponent(), withIntermediateDirectories: true) try Data("[layout]\nratio = 0.7\n".utf8).write(to: target) _ = try await waitForSnapshot(store) { $0.activeConfiguration.layout.global.ratio == 0.7 } try Data("[layout]\nratio = 0.8\n".utf8).write(to: target, options: .atomic) _ = try await waitForSnapshot(store) { $0.activeConfiguration.layout.global.ratio == 0.8 } #expect(await store.isWatching) } catch { await store.stopWatching() throw error } await store.stopWatching() }
@Test(arguments: ["deleted", "regular", "retargeted"]) func symlinkDiscoveryRetriesWhenTheLinkChangesAfterInspection(replacement: String) throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let target = fixture.directory.appendingPathComponent("target.toml") try Data("version = 1".utf8).write(to: target) try FileManager.default.createSymbolicLink(at: fixture.fileURL, withDestinationURL: target) let suffix = "/\(fixture.directory.lastPathComponent)/parcel.toml" var replaced = false let paths = try ConfigFileWatcher.watchPaths(for: fixture.fileURL) { path in if path.hasSuffix(suffix), !replaced { replaced = true try FileManager.default.removeItem(at: fixture.fileURL) if replacement == "regular" { try fixture.write("version = 1") } let destination = try ConfigFileWatcher.symlinkDestination(path) #expect(destination == nil) if replacement == "retargeted" { try FileManager.default.createSymbolicLink(at: fixture.fileURL, withDestinationURL: target) } return destination } return try ConfigFileWatcher.symlinkDestination(path) } #expect(replaced) let directory = try #require(paths.keys.first { $0.hasSuffix("/\(fixture.directory.lastPathComponent)") }) #expect(paths[directory]?.contains(.write) == true) if replacement == "regular" { #expect(paths["\(directory)/parcel.toml"]?.contains(.write) == true) } if replacement == "retargeted" { #expect(paths["\(directory)/target.toml"]?.contains(.write) == true) } }
@Test func symlinkReadDistinguishesTransientChangesFromAccessFailures() throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } #expect(try ConfigFileWatcher.symlinkDestination(fixture.fileURL.path) == nil) try fixture.write("version = 1") #expect(try ConfigFileWatcher.symlinkDestination(fixture.fileURL.path) == nil) #expect(try ConfigFileWatcher.symlinkDestination(fixture.fileURL.appendingPathComponent("child").path) == nil) let blocked = fixture.directory.appendingPathComponent("blocked") try FileManager.default.createDirectory(at: blocked, withIntermediateDirectories: false) try FileManager.default.setAttributes([.posixPermissions: 0], ofItemAtPath: blocked.path) defer { do { try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: blocked.path) } catch { Issue.record(error) } } #expect(throws: (any Error).self) { try ConfigFileWatcher.symlinkDestination(blocked.appendingPathComponent("link").path) } }
@Test func ancestorSiblingChangesDoNotScheduleReloads() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let target = fixture.directory.appendingPathComponent("inner/parcel.toml") try FileManager.default.createDirectory( at: target.deletingLastPathComponent(), withIntermediateDirectories: true) try Data("version = 1".utf8).write(to: target) let paths = try ConfigFileWatcher.watchPaths(for: target) let ancestor = try #require(paths.keys.first { $0.hasSuffix("/\(fixture.directory.lastPathComponent)") }) #expect(paths[ancestor] == [.rename, .delete, .revoke]) let recorder = WatcherRecorder() let watcher = ConfigFileWatcher( fileURL: target, debounceInterval: .milliseconds(100), sleep: { try await recorder.sleep($0) }, changed: { await recorder.changed() }, failed: { await recorder.append($0) } ) defer { watcher.cancel() } try await recorder.waitForChanges(1) for _ in 0..<3 { try fixture.write("# Unrelated sibling") try FileManager.default.removeItem(at: fixture.fileURL) } try await Task.sleep(for: .milliseconds(300)) watcher.cancel() await watcher.waitUntilFinished() #expect(await recorder.changes == 1) #expect(await recorder.sleeps == 0) #expect(await recorder.diagnostics.isEmpty) }
@Test func watcherLoadsAFileCreatedAfterAnInitialMissingFile() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } try await fixture.withWatchingStore { store in let stream = await store.updates() var updates = stream.makeAsyncIterator() let initial = try await waitForSnapshot(&updates) { $0.loadState == .missingFileUsingDefaults } #expect(initial.activeSource == .defaults) let source = "[motion]\nenabled = false\n" try fixture.write(source) let loaded = try await waitForSnapshot(&updates) { $0.lastGoodDocument?.source == source } #expect(loaded.loadState == .loaded) #expect(loaded.activeSource == .file(fixture.fileURL)) #expect(!loaded.activeConfiguration.motion.enabled) #expect(loaded.diagnostics.isEmpty) } }
@Test func watcherLoadsCompletedContentAfterAnInitiallyEmptyFile() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } try await fixture.withWatchingStore { store in let stream = await store.updates() var updates = stream.makeAsyncIterator() _ = try await waitForSnapshot(&updates) { $0.loadState == .missingFileUsingDefaults } try fixture.write("") let empty = try await waitForSnapshot(&updates) { $0.lastGoodDocument?.source == "" } #expect(empty.loadState == .loaded) #expect(empty.activeConfiguration.motion.enabled) let source = "[motion]\nenabled = false\n" try fixture.write(source) let loaded = try await waitForSnapshot(&updates) { $0.lastGoodDocument?.source == source } #expect(loaded.loadState == .loaded) #expect(loaded.activeSource == .file(fixture.fileURL)) #expect(!loaded.activeConfiguration.motion.enabled) #expect(loaded.diagnostics.isEmpty) } }
@Test func watcherRecoversFromAFileReadFailure() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } try FileManager.default.createDirectory(at: fixture.fileURL, withIntermediateDirectories: false) try await fixture.withWatchingStore { store in let failed = try await waitForSnapshot(store) { $0.loadState == .rejected } #expect(failed.activeSource == .defaults) try FileManager.default.removeItem(at: fixture.fileURL) try fixture.write("[layout]\nratio = 0.6\n") let loaded = try await waitForSnapshot(store) { $0.loadState == .loaded } #expect(loaded.activeConfiguration.layout.global.ratio == 0.6) } }
@Test func stoppedWatcherCannotPublishAndCanRestart() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let original = "[layout]\nratio = 0.6\n" let replacement = "[layout]\nratio = 0.7\n" try fixture.write(original) try await fixture.withWatchingStore { store in _ = try await waitForSnapshot(store) { $0.loadState == .loaded } await store.stopWatching() await store.stopWatching() #expect(await !store.isWatching) try fixture.write(replacement) #expect(await store.snapshot.lastGoodDocument?.source == original) try await store.startWatching(debounceInterval: .milliseconds(15)) try await store.startWatching(debounceInterval: .milliseconds(15)) let restarted = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == replacement } #expect(restarted.diagnostics.isEmpty) } }
@Test func cancellationInterruptsAPendingDebounce() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let sleep = WatcherSleepGate() defer { sleep.finish() } var starts = sleep.starts.makeAsyncIterator() var completions = sleep.completions.makeAsyncIterator() let store = ConfigStore(fileURL: fixture.fileURL) try await store.startWatching(debounceInterval: .seconds(60), sleep: { try await sleep.sleep($0) }) do { _ = try await waitForSnapshot(store) { $0.loadState == .missingFileUsingDefaults } await store.load(source: "[motion]\nenabled = false\n") let pending = try #require(await starts.next()) #expect(pending.duration == .seconds(60)) await store.stopWatching() #expect(await completions.next() == true) #expect(await !store.isWatching) #expect(await store.snapshot.activeSource == .sourceText) } catch { await store.stopWatching() throw error } }
@Test(arguments: [Duration.zero, .milliseconds(-1)]) func nonpositiveDebounceIntervalsAreRejected(interval: Duration) async throws { let store = ConfigStore() do { try await store.startWatching(debounceInterval: interval) Issue.record("An invalid debounce interval was accepted.") await store.stopWatching() } catch let diagnostic as ConfigDiagnostic { #expect(diagnostic.severity == .error) } #expect(await !store.isWatching) }
@Test func updatesIncludeCurrentStateAndRejectedLoads() async throws { let store = ConfigStore() let stream = await store.updates() var iterator = stream.makeAsyncIterator() #expect(await iterator.next()?.loadState == .notLoaded) let source = "[layout]\nratio = 0.6\n" await store.load(source: source) #expect(await iterator.next()?.lastGoodDocument?.source == source) await store.load(source: "[layout]\nratio =\n") let rejected = try #require(await iterator.next()) #expect(rejected.loadState == .rejected) #expect(rejected.lastGoodDocument?.source == source) #expect(!rejected.diagnostics.isEmpty) }
@Test func slowUpdateConsumersReceiveOnlyTheNewestSnapshot() async throws { let store = ConfigStore() let stream = await store.updates() await store.load(source: "[layout]\nratio = 0.6\n") await store.load(source: "[layout]\nratio = 0.7\n") var iterator = stream.makeAsyncIterator() let newest = try #require(await iterator.next()) #expect(newest.activeConfiguration.layout.global.ratio == 0.7) }
@Test func cancelingOneUpdateConsumerDoesNotAffectOthers() async { let store = ConfigStore() let canceledStream = await store.updates() let survivingStream = await store.updates() let consumer = Task { for await _ in canceledStream {} } consumer.cancel() await consumer.value await store.load(source: "[motion]\nenabled = false\n") var iterator = survivingStream.makeAsyncIterator() #expect(await iterator.next()?.activeConfiguration.motion.enabled == false) }
@Test func idleWatcherDoesNotRetainTheStore() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } var store: ConfigStore? = ConfigStore(fileURL: fixture.fileURL) weak let weakStore = store let updates = try #require(await store?.updates()) if let store { try await store.startWatching(debounceInterval: .seconds(60)) _ = try await waitForSnapshot(store) { $0.loadState == .missingFileUsingDefaults } } store = nil try await waitForObservation { for await _ in updates {} try Task.checkCancellation() } #expect(weakStore == nil) }
@Test func releasingStoreFinishesItsUpdateStreams() async throws { var store: ConfigStore? = ConfigStore() weak let weakStore = store let stream = try #require(await store?.updates()) var iterator = stream.makeAsyncIterator() #expect(await iterator.next()?.loadState == .notLoaded) store = nil #expect(weakStore == nil) #expect(await iterator.next() == nil) }
@Test func watcherSurfacesUnexpectedDebounceFailure() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let recorder = WatcherRecorder() let watcher = ConfigFileWatcher( fileURL: fixture.fileURL, debounceInterval: .seconds(1), sleep: { _ in throw StoreTestError.injected }, changed: { await recorder.changed() }, failed: { await recorder.append($0) } ) defer { watcher.cancel() } try await recorder.waitForChanges(1) watcher.requestReload() await watcher.waitUntilFinished() let diagnostics = await recorder.diagnostics #expect(diagnostics.count == 1) #expect(diagnostics.first?.severity == .error) #expect(diagnostics.first?.message.isEmpty == false) }
@Test func watcherHasNoIdleReadsOrSleepsAndCoalescesBurstWrites() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } try fixture.write("version = 1") let recorder = WatcherRecorder() let sleep = WatcherSleepGate() defer { sleep.finish() } let watcher = ConfigFileWatcher( fileURL: fixture.fileURL, debounceInterval: .milliseconds(100), sleep: { duration in await recorder.recordSleep() try await sleep.sleep(duration) }, changed: { await recorder.changed() }, failed: { await recorder.append($0) sleep.finish() } ) defer { watcher.cancel() } var starts = sleep.starts.makeAsyncIterator() var completions = sleep.completions.makeAsyncIterator() try await recorder.waitForChanges(1) #expect(await recorder.changes == 1) #expect(await recorder.sleeps == 0)
// Explicit events and sleep gates keep scheduling delays from splitting a burst. for burst in 1...2 { watcher.requestReload() let pending = try #require(await starts.next()) #expect(pending.duration == .milliseconds(100)) for _ in 0..<20 { watcher.requestReload() } #expect(await recorder.changes == burst) pending.resume() #expect(await completions.next() == false) try await recorder.waitForChanges(burst + 1) #expect(await recorder.changes == burst + 1) #expect(await recorder.sleeps == burst) } watcher.cancel() await watcher.waitUntilFinished() #expect(await recorder.changes == 3) #expect(await recorder.sleeps == 2) #expect(await recorder.diagnostics.isEmpty) }
@Test func siblingFileChurnCannotStarveConfigurationReload() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } try fixture.write("[motion]\nenabled = true\n", atomic: true) let store = ConfigStore(fileURL: fixture.fileURL) try await store.startWatching(debounceInterval: .milliseconds(200)) do { _ = try await waitForSnapshot(store) { $0.loadState == .loaded } try await withThrowingTaskGroup(of: Void.self) { group in defer { group.cancelAll() } let (started, continuation) = AsyncStream<Void>.makeStream(bufferingPolicy: .bufferingNewest(1)) defer { continuation.finish() } let sibling = fixture.directory.appendingPathComponent("query.stdout") group.addTask { while true { try Task.checkCancellation() try Data("query result".utf8).write(to: sibling, options: .atomic) continuation.yield(()) try await Task.sleep(for: .milliseconds(10)) } } var starts = started.makeAsyncIterator() _ = try #require(await starts.next()) try fixture.write("[motion]\nenabled = false\n", atomic: true) let loaded = try await waitForSnapshot(store) { !$0.activeConfiguration.motion.enabled } #expect(loaded.loadState == .loaded && loaded.diagnostics.isEmpty) } } catch { await store.stopWatching() throw error } await store.stopWatching() }
@Test func eventDuringReloadSchedulesAnotherBoundedWindow() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let recorder = WatcherRecorder() let sleep = WatcherSleepGate() let reload = WatcherSleepGate() defer { sleep.finish(); reload.finish() } let watcher = ConfigFileWatcher( fileURL: fixture.fileURL, debounceInterval: .milliseconds(100), sleep: { try await sleep.sleep($0) }, changed: { let result = await recorder.changed() if await recorder.changes == 2 { do { try await reload.sleep(.zero) } catch is CancellationError { return false } catch { Issue.record(error) return false } } return result }, failed: { await recorder.append($0) }) defer { watcher.cancel() } var sleeps = sleep.starts.makeAsyncIterator() var reloads = reload.starts.makeAsyncIterator() try await recorder.waitForChanges(1) watcher.requestReload() let first = try #require(await sleeps.next()) first.resume() let inFlight = try #require(await reloads.next()) watcher.requestReload() inFlight.resume() let followUp = try #require(await sleeps.next()) #expect(followUp.duration == .milliseconds(100)) followUp.resume() try await recorder.waitForChanges(3) watcher.cancel() await watcher.waitUntilFinished() #expect(await recorder.diagnostics.isEmpty) }
@Test func watcherCancellationIsNotReportedAsAFailure() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let recorder = WatcherRecorder() let sleep = WatcherSleepGate() defer { sleep.finish() } var starts = sleep.starts.makeAsyncIterator() var completions = sleep.completions.makeAsyncIterator() let watcher = ConfigFileWatcher( fileURL: fixture.fileURL, debounceInterval: .seconds(60), sleep: { try await sleep.sleep($0) }, changed: { await recorder.changed() }, failed: { await recorder.append($0) } ) defer { watcher.cancel() } try await recorder.waitForChanges(1) watcher.requestReload() let pending = try #require(await starts.next()) #expect(pending.duration == .seconds(60)) watcher.cancel() await watcher.waitUntilFinished() #expect(await completions.next() == true) #expect(await recorder.changes == 1) #expect(await recorder.diagnostics.isEmpty) }
@Test func watchedFileResumesAfterSourceTextLoading() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let original = "version = 1" try fixture.write(original) try await fixture.withWatchingStore { store in _ = try await waitForSnapshot(store) { $0.loadState == .loaded } let loaded = await store.load(source: "[motion]\nenabled = false\n") #expect(loaded.activeSource == .sourceText) let resumed = try await waitForSnapshot(store) { $0.activeSource == .file(fixture.fileURL) } #expect(resumed.lastGoodDocument?.source == original) } }
@Test func watcherReportsSetupFailureAndCanRestart() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } try FileManager.default.createSymbolicLink(at: fixture.fileURL, withDestinationURL: fixture.fileURL) let store = ConfigStore(fileURL: fixture.fileURL) try await store.startWatching() let failed = try await waitForSnapshot(store) { $0.loadState == .rejected } #expect(!failed.diagnostics.isEmpty) #expect(await !store.isWatching) try FileManager.default.removeItem(at: fixture.fileURL) try fixture.write("version = 1") try await store.startWatching() _ = try await waitForSnapshot(store) { $0.loadState == .loaded } await store.stopWatching() }
@Test func watcherRejectsNonFileURLs() async throws { let url = try #require(URL(string: "https://example.invalid/parcel.toml")) let store = ConfigStore(fileURL: url) try await store.startWatching() let failed = try await waitForSnapshot(store) { $0.loadState == .rejected } #expect(failed.activeConfiguration == .defaults) #expect(await !store.isWatching) }}
private enum StoreTestError: Error { case timedOut case observationEnded case injected}
private struct WatcherSleepGate: Sendable { struct Pending: Sendable { let duration: Duration let release: AsyncStream<Void>.Continuation
func resume() { release.finish() } }
private let started = AsyncStream<Pending>.makeStream() private let completed = AsyncStream<Bool>.makeStream()
var starts: AsyncStream<Pending> { started.stream } var completions: AsyncStream<Bool> { completed.stream }
func sleep(_ duration: Duration) async throws { let (release, continuation) = AsyncStream<Void>.makeStream() defer { continuation.finish() } started.continuation.yield(Pending(duration: duration, release: continuation)) for await _ in release {} completed.continuation.yield(Task.isCancelled) try Task.checkCancellation() }
func finish() { started.continuation.finish() completed.continuation.finish() }}
private actor WatcherRecorder { private(set) var diagnostics: [ConfigDiagnostic] = [] private(set) var changes = 0 private(set) var sleeps = 0 private let changeEvents = AsyncStream<Int>.makeStream()
deinit { changeEvents.continuation.finish() }
func changed() -> Bool { changes += 1 changeEvents.continuation.yield(changes) return true }
func recordSleep() { sleeps += 1 }
func sleep(_ duration: Duration) async throws { recordSleep() try await Task.sleep(for: duration) }
func append(_ diagnostic: ConfigDiagnostic) { diagnostics.append(diagnostic) changeEvents.continuation.finish() }
func waitForChanges(_ count: Int) async throws { if changes >= count { return } try await waitForObservation { [changeEvents] in for await current in changeEvents.stream { if current >= count { return } } throw StoreTestError.observationEnded } }}
private struct TemporaryConfigFile: Sendable { let directory: URL var fileURL: URL { directory.appendingPathComponent("parcel.toml") }
init() throws { directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) }
func write(_ text: String, atomic: Bool = false) throws { try Data(text.utf8).write(to: fileURL, options: atomic ? .atomic : []) }
func writeInPlace(_ text: String) throws { let handle = try FileHandle(forWritingTo: fileURL) defer { do { try handle.close() } catch { Issue.record(error) } } try handle.write(contentsOf: Data(text.utf8)) try handle.truncate(atOffset: UInt64(text.utf8.count)) }
func withWatchingStore(_ body: @Sendable (ConfigStore) async throws -> Void) async throws { let store = ConfigStore(fileURL: fileURL) try await store.startWatching(debounceInterval: .milliseconds(15)) do { try await body(store) } catch { await store.stopWatching() throw error } await store.stopWatching() }
func remove() { do { try FileManager.default.removeItem(at: directory) } catch { Issue.record(error) } }}
private func waitForSnapshot( _ updates: inout AsyncStream<ConfigSnapshot>.Iterator, matching predicate: (ConfigSnapshot) -> Bool) async throws -> ConfigSnapshot { while let snapshot = await updates.next() { if predicate(snapshot) { return snapshot } } throw StoreTestError.observationEnded}
private func waitForSnapshot( _ store: ConfigStore, matching predicate: @escaping @Sendable (ConfigSnapshot) -> Bool) async throws -> ConfigSnapshot { let updates = await store.updates() return try await waitForObservation { for await snapshot in updates { if predicate(snapshot) { return snapshot } } throw StoreTestError.observationEnded }}
private func waitForObservation<Value: Sendable>( _ observe: @escaping @Sendable () async throws -> Value) async throws -> Value { try await withThrowingTaskGroup(of: Value.self) { group in defer { group.cancelAll() } group.addTask { try await observe() } group.addTask { try await Task.sleep(for: .seconds(3)) throw StoreTestError.timedOut } return try #require(await group.next()) }}