From 3b5d7a451a74c0763f6b68fd1cbb2b30bea501f8 Mon Sep 17 00:00:00 2001 From: Vitalii Budnik Date: Wed, 8 Apr 2026 15:51:52 +0300 Subject: [PATCH] chore: ensure directory exists before saving har --- Sources/Replay/HAR.swift | 7 +++++++ Tests/ReplayTests/HARTests.swift | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/Sources/Replay/HAR.swift b/Sources/Replay/HAR.swift index e75495f..1f2bc30 100644 --- a/Sources/Replay/HAR.swift +++ b/Sources/Replay/HAR.swift @@ -787,6 +787,13 @@ extension HAR { /// with fractional seconds and pretty-printed output. public static func save(_ log: Log, to url: URL) throws { let data = try encode(log) + + // Ensure the directory exists + let directory = url.deletingLastPathComponent() + if !FileManager.default.fileExists(atPath: directory.path) { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + try data.write(to: url) } diff --git a/Tests/ReplayTests/HARTests.swift b/Tests/ReplayTests/HARTests.swift index 6070a52..a335334 100644 --- a/Tests/ReplayTests/HARTests.swift +++ b/Tests/ReplayTests/HARTests.swift @@ -1319,6 +1319,24 @@ struct HARTests { #expect(log.creator.name == "MyApp/2.0") } + @Test("save to non existing directory") + func saveToNonExistingDirectory() throws { + var log = HAR.create() + log.entries.append(makeTestEntry()) + log.comment = "Test HAR file" + + let tempSubdirURL = URL(fileURLWithPath: NSTemporaryDirectory()) + .appendingPathComponent("subdir") + let tempURL = tempSubdirURL + .appendingPathComponent("HARTests_saveAndLoad.har") + + try HAR.save(log, to: tempURL) + + #expect(FileManager.default.fileExists(atPath: tempURL.path)) + + try? FileManager.default.removeItem(at: tempSubdirURL) + } + @Test("save and load roundtrip") func saveAndLoad() throws { var log = HAR.create()