@@ -11,27 +11,30 @@ enum ProgressInfo: Codable {
11
11
struct JsonFileProgressReporter : ProgressAnimationProtocol {
12
12
let filePath : FilePath
13
13
private let encoder : JSONEncoder
14
+ private let ctx : SwiftlyCoreContext
15
+ private let fileHandle : FileHandle
14
16
15
- init ( filePath: FilePath , encoder: JSONEncoder = JSONEncoder ( ) ) {
17
+ init ( _ ctx: SwiftlyCoreContext , filePath: FilePath , encoder: JSONEncoder = JSONEncoder ( ) ) throws
18
+ {
19
+ self . ctx = ctx
16
20
self . filePath = filePath
17
21
self . encoder = encoder
22
+ self . fileHandle = try FileHandle ( forWritingTo: URL ( fileURLWithPath: filePath. string) )
18
23
}
19
24
20
25
private func writeProgress( _ progress: ProgressInfo ) {
21
26
let jsonData = try ? self . encoder. encode ( progress)
22
- guard let jsonData = jsonData, let jsonString = String ( data: jsonData, encoding: . utf8)
23
- else {
24
- print ( " Failed to encode progress entry to JSON " )
27
+ guard let jsonData = jsonData else {
28
+ Task { [ ctx = self . ctx] in
29
+ await ctx. message ( " Failed to encode progress entry to JSON " )
30
+ }
25
31
return
26
32
}
27
33
28
- let jsonLine = jsonString + " \n "
29
-
30
- do {
31
- try jsonLine. append ( to: self . filePath)
32
- } catch {
33
- print ( " Failed to write progress entry to \( self . filePath) : \( error) " )
34
- }
34
+ self . fileHandle. seekToEndOfFile ( )
35
+ self . fileHandle. write ( jsonData)
36
+ self . fileHandle. write ( " \n " . data ( using: . utf8) ?? Data ( ) )
37
+ self . fileHandle. synchronizeFile ( )
35
38
}
36
39
37
40
func update( step: Int , total: Int , text: String ) {
@@ -49,10 +52,11 @@ struct JsonFileProgressReporter: ProgressAnimationProtocol {
49
52
}
50
53
51
54
func clear( ) {
52
- do {
53
- try FileManager . default. removeItem ( atPath: self . filePath. string)
54
- } catch {
55
- print ( " Failed to clear progress file at \( self . filePath) : \( error) " )
56
- }
55
+ self . fileHandle. truncateFile ( atOffset: 0 )
56
+ self . fileHandle. synchronizeFile ( )
57
+ }
58
+
59
+ func close( ) throws {
60
+ try self . fileHandle. close ( )
57
61
}
58
62
}
0 commit comments