Sources/OrgApp/ConfigFolder.swift
42 lines · 2088 bytes
1import Foundation
2import OrgCore
3
4/// A configuration folder chosen in the app, kept as a bookmark: on iOS a synced copy of the
5/// Mac's `~/.config/orgstar`, in the Mac sandbox a folder outside the container. The bookmark
6/// is security-scoped in the Mac sandbox and plain elsewhere.
7public enum ConfigFolder {
8 public static let bookmarkKey = "configFolderBookmark"
9
10 /// The chosen folder with access to it started, or nil when none is chosen or its bookmark
11 /// no longer resolves. A stale bookmark is renewed.
12 public static func resolve(defaults: UserDefaults = .standard, sandboxed: Bool = Sandbox.isActive) -> URL? {
13 guard let data = defaults.data(forKey: bookmarkKey) else { return nil }
14 var stale = false
15 guard let url = try? URL(resolvingBookmarkData: data, options: Sandbox.bookmarkResolutionOptions(sandboxed: sandboxed), bookmarkDataIsStale: &stale) else { return nil }
16 _ = url.startAccessingSecurityScopedResource()
17 if stale, let fresh = try? Sandbox.bookmark(url, sandboxed: sandboxed) {
18 defaults.set(fresh, forKey: bookmarkKey)
19 }
20 return url
21 }
22
23 /// Keeps `url`, as from a folder picker, as the chosen folder and starts access to it. False
24 /// when its bookmark can't be made, so the choice isn't kept after the app quits.
25 @discardableResult
26 public static func set(_ url: URL, defaults: UserDefaults = .standard, sandboxed: Bool = Sandbox.isActive) -> Bool {
27 _ = url.startAccessingSecurityScopedResource()
28 guard let bookmark = try? Sandbox.bookmark(url, sandboxed: sandboxed) else { return false }
29 defaults.set(bookmark, forKey: bookmarkKey)
30 return true
31 }
32
33 /// Stops using a chosen folder.
34 public static func clear(defaults: UserDefaults = .standard) {
35 defaults.removeObject(forKey: bookmarkKey)
36 }
37
38 /// `~/.config/orgstar` in the real home folder, where a folder picker starts.
39 public static var suggested: URL {
40 URL(fileURLWithPath: OrgPaths.home).appendingPathComponent(".config/orgstar")
41 }
42}