Packages/FoldKit/Sources/Models/ModelLibrary.swift

35 lines · 1337 bytes

5 symbols in this file
 1import FoldFormat
 2import Foundation
 3
 4public enum ModelLibraryError: Error, Equatable, Sendable {
 5    case noModel(named: String)
 6}
 7
 8/// The shipped models: `Resources/<name>.fold`, each generated by `foldc` from
 9/// `Models/<name>.foldscript` and `Models/<name>-cp.fold`.
10public enum ModelLibrary {
11    /// Every model, in the order of `names()`.
12    public static func all() throws -> [FoldFile] {
13        try names().map(model(named:))
14    }
15
16    /// The models' names, sorted.
17    public static func names() throws -> [String] {
18        try FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)
19            .filter { $0.pathExtension == "fold" }
20            .map { $0.deletingPathExtension().lastPathComponent }
21            .sorted()
22    }
23
24    public static func model(named name: String) throws -> FoldFile {
25        let url = directory.appendingPathComponent("\(name).fold")
26        guard FileManager.default.fileExists(atPath: url.path) else { throw ModelLibraryError.noModel(named: name) }
27        return try FoldFile(contentsOf: url)
28    }
29
30    /// The resource bundle's directory, where the package places `Resources/`'s files. A bundle
31    /// holding a directory named `Resources` fails code signing on iOS.
32    private static var directory: URL {
33        Bundle.module.resourceURL!
34    }
35}