Sources/OrgApp/ConfigFolder.swift
40 lines · 2009 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? url.bookmarkData(options: Sandbox.bookmarkCreationOptions(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.
24 public static func set(_ url: URL, defaults: UserDefaults = .standard, sandboxed: Bool = Sandbox.isActive) {
25 _ = url.startAccessingSecurityScopedResource()
26 if let bookmark = try? url.bookmarkData(options: Sandbox.bookmarkCreationOptions(sandboxed: sandboxed)) {
27 defaults.set(bookmark, forKey: bookmarkKey)
28 }
29 }
30
31 /// Stops using a chosen folder.
32 public static func clear(defaults: UserDefaults = .standard) {
33 defaults.removeObject(forKey: bookmarkKey)
34 }
35
36 /// `~/.config/orgstar` in the real home folder, where a folder picker starts.
37 public static var suggested: URL {
38 URL(fileURLWithPath: OrgPaths.home).appendingPathComponent(".config/orgstar")
39 }
40}