Sources/OrgApp/WorkingCopy.swift

89cd390831f813d3a7b29905803e98849b457be9
orgstar/Sources/OrgApp/WorkingCopy.swift

147 lines · 6377 bytes

  1import Foundation
  2import Security
  3
  4/// Syncing a folder that is a git repository in Working Copy, through its x-callback-url
  5/// commands (https://workingcopyapp.com/url-schemes.html): commit everything changed, pull,
  6/// then push, with the answer coming back to `orgstar://working-copy/…`.
  7public enum WorkingCopy {
  8    public static let scheme = "working-copy"
  9    /// The host of the callbacks in orgstar's own scheme.
 10    public static let callbackHost = "working-copy"
 11
 12    /// The commit message.
 13    public static let message = "Update from orgstar"
 14
 15    /// The `chain` command that commits every changed file in `repo`, pulls and pushes, with
 16    /// `key` (Working Copy's URL key) and callbacks naming `repo`.
 17    public static func syncURL(repo: String, key: String, message: String = message) -> URL {
 18        let back = { (result: String) in
 19            "\(AppLink.scheme)://\(callbackHost)/\(result)?repo=\(encode(repo))"
 20        }
 21        // Parameters before the first `command` apply to every command; `x-success` is used by
 22        // the last one.
 23        let query = [
 24            ("repo", repo), ("key", key), ("x-success", back("success")), ("x-error", back("error")),
 25            ("command", "commit"), ("message", message), ("limit", "999"),
 26            ("command", "pull"),
 27            ("command", "push"),
 28        ]
 29        var components = URLComponents()
 30        components.scheme = scheme
 31        components.host = "x-callback-url"
 32        components.path = "/chain"
 33        components.percentEncodedQuery = query.map { "\($0)=\(encode($1))" }.joined(separator: "&")
 34        return components.url!
 35    }
 36
 37    /// Spaces as `%20`, not `+`, and every reserved character encoded, as Working Copy asks.
 38    static func encode(_ value: String) -> String {
 39        var allowed = CharacterSet.alphanumerics
 40        allowed.insert(charactersIn: "-._~")
 41        return value.addingPercentEncoding(withAllowedCharacters: allowed) ?? value
 42    }
 43
 44    /// Working Copy's answer to a sync.
 45    public enum Callback: Equatable, Sendable {
 46        case success(repo: String)
 47        /// With Working Copy's `errorMessage`, when it gave one.
 48        case failure(repo: String, message: String?)
 49    }
 50
 51    /// The callback `url` is, or nil for another URL.
 52    public static func callback(_ url: URL) -> Callback? {
 53        guard url.scheme == AppLink.scheme, url.host == callbackHost,
 54              let components = URLComponents(url: url, resolvingAgainstBaseURL: false),
 55              let repo = components.queryItems?.first(where: { $0.name == "repo" })?.value else { return nil }
 56        switch url.lastPathComponent {
 57        case "success": return .success(repo: repo)
 58        case "error":
 59            let message = components.queryItems?.first { $0.name == "errorMessage" }?.value
 60            return .failure(repo: repo, message: message.flatMap { $0.isEmpty ? nil : $0 })
 61        default: return nil
 62        }
 63    }
 64
 65    /// Whether `root` holds a git repository: a `.git` folder or file (a worktree's) at its top.
 66    /// Working Copy's own File Provider may leave `.git` out, so a folder can be set up without it.
 67    public static func isRepository(_ root: String) -> Bool {
 68        FileManager.default.fileExists(atPath: (root as NSString).appendingPathComponent(".git"))
 69    }
 70
 71    // MARK: - Settings
 72
 73    /// How a folder syncs: the repository's name in Working Copy, and whether it syncs each time
 74    /// the app opens. A folder without settings doesn't sync.
 75    public struct Folder: Codable, Equatable, Sendable {
 76        public var repository: String
 77        public var syncOnOpen: Bool
 78
 79        public init(repository: String, syncOnOpen: Bool = false) {
 80            self.repository = repository
 81            self.syncOnOpen = syncOnOpen
 82        }
 83    }
 84
 85    /// The folders set up on this device, by root path. Kept on the device: roots are at
 86    /// different paths on each.
 87    public struct Folders {
 88        static let key = "workingCopyFolders"
 89        let defaults: UserDefaults
 90
 91        public init(defaults: UserDefaults = .standard) {
 92            self.defaults = defaults
 93        }
 94
 95        public var all: [String: Folder] {
 96            guard let data = defaults.data(forKey: Self.key) else { return [:] }
 97            return (try? JSONDecoder().decode([String: Folder].self, from: data)) ?? [:]
 98        }
 99
100        public func folder(_ root: String) -> Folder? { all[root] }
101
102        /// Sets up `root`, or with nil stops syncing it.
103        public func set(_ folder: Folder?, for root: String) {
104            var all = all
105            all[root] = folder
106            defaults.set(try? JSONEncoder().encode(all), forKey: Self.key)
107        }
108
109        /// The root set up with `repository`.
110        public func root(of repository: String) -> String? {
111            all.filter { $0.value.repository == repository }.map(\.key).sorted().first
112        }
113    }
114
115    // MARK: - The key
116
117    /// Working Copy's URL key, which every command needs. Kept in the Keychain on this device
118    /// only, never in settings or logs.
119    public enum Key {
120        static let service = "sh.krz.orgstar.working-copy"
121
122        static var query: [String: Any] {
123            [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: "url-key"]
124        }
125
126        public static func stored() -> String? {
127            var q = query
128            q[kSecReturnData as String] = true
129            var result: AnyObject?
130            guard SecItemCopyMatching(q as CFDictionary, &result) == errSecSuccess, let data = result as? Data else { return nil }
131            let key = String(decoding: data, as: UTF8.self)
132            return key.isEmpty ? nil : key
133        }
134
135        /// Stores `key`, or removes it when it is nil or empty. False when the Keychain refused.
136        @discardableResult
137        public static func store(_ key: String?) -> Bool {
138            SecItemDelete(query as CFDictionary)
139            guard let key, !key.isEmpty else { return true }
140            var item = query
141            item[kSecValueData as String] = Data(key.utf8)
142            item[kSecAttrLabel as String] = "orgstar: Working Copy URL key"
143            item[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly
144            return SecItemAdd(item as CFDictionary, nil) == errSecSuccess
145        }
146    }
147}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form