Skip to content

Commit b1655f4

Browse files
committed
Json Progress File
1 parent bce44d7 commit b1655f4

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

Sources/SwiftlyCore/FileManager+FilePath.swift

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,22 @@ extension String {
190190
try self.write(to: URL(fileURLWithPath: path.string), atomically: atomically, encoding: enc)
191191
}
192192

193+
public func append(to path: FilePath, encoding enc: String.Encoding = .utf8) throws {
194+
if !FileManager.default.fileExists(atPath: path.string) {
195+
try self.write(to: path, atomically: true, encoding: enc)
196+
return
197+
}
198+
199+
let fileHandle = try FileHandle(forWritingTo: URL(fileURLWithPath: path.string))
200+
defer { fileHandle.closeFile() }
201+
fileHandle.seekToEndOfFile()
202+
if let data = self.data(using: enc) {
203+
fileHandle.write(data)
204+
} else {
205+
throw SwiftlyError(message: "Failed to convert string to data with encoding \(enc)")
206+
}
207+
}
208+
193209
public init(contentsOf path: FilePath, encoding enc: String.Encoding = .utf8) throws {
194210
try self.init(contentsOf: URL(fileURLWithPath: path.string), encoding: enc)
195211
}

Tests/SwiftlyTests/JsonFileProgressReporterTests.swift

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
import Foundation
2+
@testable import Swiftly
3+
@testable import SwiftlyCore
24
import SystemPackage
35
import Testing
46

@@ -100,6 +102,20 @@ import Testing
100102
try FileManager.default.removeItem(atPath: tempFile.string)
101103
}
102104

105+
@Test("Test clear method removes file")
106+
func testClearRemovesFile() throws {
107+
let tempFile = fs.mktemp(ext: ".json")
108+
let reporter = JsonFileProgressReporter(filePath: tempFile)
109+
110+
reporter.update(step: 1, total: 2, text: "Test")
111+
112+
#expect(FileManager.default.fileExists(atPath: tempFile.string))
113+
114+
reporter.clear()
115+
116+
#expect(!FileManager.default.fileExists(atPath: tempFile.string))
117+
}
118+
103119
@Test("Test multiple progress updates create multiple lines")
104120
func testMultipleUpdatesCreateMultipleLines() async throws {
105121
let tempFile = fs.mktemp(ext: ".json")
@@ -113,6 +129,8 @@ import Testing
113129
reporter.update(step: 50, total: 100, text: "Processing item 50")
114130
reporter.update(step: 100, total: 100, text: "Processing item 100")
115131

132+
reporter.update(step: 1, total: 3, text: "Step 1")
133+
reporter.update(step: 2, total: 3, text: "Step 2")
116134
reporter.complete(success: true)
117135
try? reporter.close()
118136

0 commit comments

Comments
 (0)