-
Notifications
You must be signed in to change notification settings - Fork 149
/
Copy pathFoundationFileSystem.swift
77 lines (65 loc) · 2.39 KB
/
FoundationFileSystem.swift
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// Copyright 2020 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
public struct FoundationFileSystem: FileSystem {
public init() {}
public func createDirectoryIfMissing(at path: String) throws {
guard !FileManager.default.fileExists(atPath: path) else { return }
try FileManager.default.createDirectory(
atPath: path,
withIntermediateDirectories: true,
attributes: nil)
}
public func open(_ filename: String) -> File {
return FoundationFile(path: filename)
}
public func copy(source: URL, dest: URL) throws {
try FileManager.default.copyItem(at: source, to: dest)
}
}
public struct FoundationFile: File {
public let location: URL
public init(path: String) {
self.location = URL(fileURLWithPath: path)
}
public func read() throws -> Data {
return try Data(contentsOf: location, options: .alwaysMapped)
}
public func read(position: Int, count: Int) throws -> Data {
// TODO: Incorporate file offset.
return try Data(contentsOf: location, options: .alwaysMapped)
}
public func write(_ value: Data) throws {
try self.write(value, position: 0)
}
public func write(_ value: Data, position: Int) throws {
// TODO: Incorporate file offset.
try value.write(to: location)
}
/// Appends the bytes in `suffix` to the file.
public func append(_ suffix: Data) throws {
let fileHandler = try FileHandle(forUpdating: location)
#if os(macOS)
// The following are needed in order to build on macOS 10.15 (Catalina). They can be removed
// once macOS 10.16 (Big Sur) is prevalent enough as a build environment.
fileHandler.seekToEndOfFile()
fileHandler.write(suffix)
fileHandler.closeFile()
#else
try fileHandler.seekToEnd()
try fileHandler.write(contentsOf: suffix)
try fileHandler.close()
#endif
}
}