forked from github/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileChangeChecker.swift
More file actions
39 lines (33 loc) · 1022 Bytes
/
FileChangeChecker.swift
File metadata and controls
39 lines (33 loc) · 1022 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import CryptoKit
import Dispatch
import Foundation
/// Check that a file is changed.
public actor FileChangeChecker {
let url: URL
var checksum: Data?
public init(fileURL: URL) async {
url = fileURL
checksum = getChecksum()
}
public func checkIfChanged() -> Bool {
guard let newChecksum = getChecksum() else { return false }
return newChecksum != checksum
}
func getChecksum() -> Data? {
let bufferSize = 16 * 1024
guard let file = try? FileHandle(forReadingFrom: url) else { return nil }
defer { try? file.close() }
var md5 = CryptoKit.Insecure.MD5()
while autoreleasepool(invoking: {
let data = file.readData(ofLength: bufferSize)
if !data.isEmpty {
md5.update(data: data)
return true // Continue
} else {
return false // End of file
}
}) {}
let data = Data(md5.finalize())
return data
}
}