Sources/OrgWorkspace/Discovery.swift
159 lines · 7088 bytes
1import Foundation
2import OrgCore
3import OrgIndex
4
5/// A folder the user added. Identified by its bookmark, so a moved folder is followed. In the
6/// Mac sandbox the bookmark is security-scoped, so access comes back after relaunch.
7public struct WorkspaceRoot: Sendable, Equatable, Codable {
8 public let bookmark: Data
9 /// The path when the bookmark was made or last refreshed, for display.
10 public var path: String
11
12 public init(url: URL, sandboxed: Bool = Sandbox.isActive) throws {
13 bookmark = try Sandbox.bookmark(url, sandboxed: sandboxed)
14 path = url.standardizedFileURL.path
15 }
16
17 /// The folder's current location. `isStale` means the bookmark should be made again.
18 public func resolve(sandboxed: Bool = Sandbox.isActive) throws -> (url: URL, isStale: Bool) {
19 var isStale = false
20 let options = Sandbox.bookmarkResolutionOptions(sandboxed: sandboxed)
21 let url = try URL(resolvingBookmarkData: bookmark, options: options, relativeTo: nil, bookmarkDataIsStale: &isStale)
22 _ = url.startAccessingSecurityScopedResource()
23 return (url.standardizedFileURL, isStale)
24 }
25}
26
27public struct DiscoveredFile: Sendable, Equatable {
28 public let url: URL
29 public let kind: FileKind
30 public let size: Int
31 public let mtime: Double
32}
33
34public struct Discovery: Sendable, Equatable {
35 public var files: [DiscoveredFile] = []
36 /// iCloud files not downloaded yet, by the name they will have.
37 public var placeholders: [URL] = []
38}
39
40public enum FileClassification: Sendable, Equatable {
41 case file(FileKind)
42 /// An iCloud placeholder (`.name.org.icloud`) for the file at the given name.
43 case placeholder(String)
44 case ignored
45}
46
47/// Which files and folders a scan takes in.
48public struct ScanRules: Sendable, Equatable {
49 /// Dotfiles and dot folders, other than ignored folders.
50 public var hiddenFiles: Bool
51 /// Folder names never looked into: version control, caches, build output.
52 public var ignoredFolders: Set<String>
53
54 public static let defaultIgnoredFolders: Set<String> = [
55 ".git", ".hg", ".svn", ".jj", ".bzr", ".stfolder", ".stversions", ".Trash", ".Spotlight-V100", ".fseventsd",
56 ".build", ".venv", ".cache", ".tox", ".mypy_cache", ".pytest_cache", ".gradle", ".next", ".terraform", "node_modules",
57 ]
58
59 public init(hiddenFiles: Bool = true, ignoredFolders: Set<String> = defaultIgnoredFolders) {
60 self.hiddenFiles = hiddenFiles
61 self.ignoredFolders = ignoredFolders
62 }
63
64 public func skipsFolder(_ name: String) -> Bool {
65 ignoredFolders.contains(name) || (!hiddenFiles && name.hasPrefix("."))
66 }
67}
68
69public enum WorkspaceScanner {
70 /// What a file name means to the workspace. Syncthing temp files, our own temp and backup
71 /// files, Emacs backups, auto-saves and lock files, and Finder's files are ignored, and
72 /// other dotfiles unless `rules` takes them in; files that aren't org files are `.other`.
73 public static func classify(_ name: String, rules: ScanRules = ScanRules()) -> FileClassification {
74 if name.hasPrefix(".") {
75 if name.hasSuffix(".icloud") {
76 let inner = String(name.dropFirst().dropLast(".icloud".count))
77 if case .file = classify(inner, rules: rules) { return .placeholder(inner) }
78 return .ignored
79 }
80 if !rules.hiddenFiles || name.hasPrefix(".#") || name.hasPrefix(".syncthing.") || name.contains(".orgstar-")
81 || name == ".DS_Store" || name == ".localized" {
82 return .ignored
83 }
84 }
85 if name.hasSuffix("~") || name.hasPrefix("#") { return .ignored }
86 let conflict = name.contains(".sync-conflict-")
87 if name.hasSuffix(".org") { return .file(conflict ? .conflict : .org) }
88 if name.hasSuffix(".org_archive") { return .file(conflict ? .conflict : .archive) }
89 return .file(.other)
90 }
91
92 /// Resource keys a scan reads.
93 static let keys: [URLResourceKey] = [
94 .isDirectoryKey, .fileSizeKey, .contentModificationDateKey, .isUbiquitousItemKey, .ubiquitousItemDownloadingStatusKey,
95 ]
96
97 /// An iCloud file whose contents aren't on this device: reading it would wait for the
98 /// download, so it's asked to download and indexed when it arrives. Since macOS 14 these
99 /// keep their own names rather than `.name.icloud`.
100 public static func isPending(isUbiquitous: Bool?, status: URLUbiquitousItemDownloadingStatus?) -> Bool {
101 isUbiquitous == true && status == .notDownloaded
102 }
103
104 static func isPending(_ values: URLResourceValues) -> Bool {
105 isPending(isUbiquitous: values.isUbiquitousItem, status: values.ubiquitousItemDownloadingStatus)
106 }
107
108 /// Every file under `root`, skipping the folders `rules` ignores.
109 public static func scan(_ root: URL, rules: ScanRules = ScanRules()) throws -> Discovery {
110 let keys = Self.keys
111 guard let enumerator = FileManager.default.enumerator(at: root, includingPropertiesForKeys: keys) else {
112 return Discovery()
113 }
114 var discovery = Discovery()
115 for case let url as URL in enumerator {
116 let values = try url.resourceValues(forKeys: Set(keys))
117 let name = url.lastPathComponent
118 if values.isDirectory == true {
119 if rules.skipsFolder(name) { enumerator.skipDescendants() }
120 continue
121 }
122 switch classify(name, rules: rules) {
123 case .file where isPending(values):
124 discovery.placeholders.append(url.standardizedFileURL)
125 case .file(let kind):
126 discovery.files.append(DiscoveredFile(
127 url: url.standardizedFileURL,
128 kind: kind,
129 size: values.fileSize ?? 0,
130 mtime: values.contentModificationDate?.timeIntervalSince1970 ?? 0
131 ))
132 case .placeholder(let inner):
133 discovery.placeholders.append(url.deletingLastPathComponent().appendingPathComponent(inner).standardizedFileURL)
134 case .ignored:
135 break
136 }
137 }
138 discovery.files.sort { $0.url.path < $1.url.path }
139 return discovery
140 }
141}
142
143/// Which files feed the agenda: `.org` files (not archives or conflict copies) matching one of
144/// the globs, relative to their root. No globs means every `.org` file.
145public struct AgendaScope: Sendable, Equatable {
146 public var globs: [String]
147
148 public init(globs: [String] = []) {
149 self.globs = globs
150 }
151
152 public func contains(relativePath: String, kind: FileKind) -> Bool {
153 // `org-agenda-file-regexp` leaves out dotfiles.
154 guard kind == .org, !(relativePath as NSString).lastPathComponent.hasPrefix(".") else { return false }
155 guard !globs.isEmpty else { return true }
156 // Without FNM_PATHNAME, `*` also matches `/`, so `work/*` covers nested folders.
157 return globs.contains { fnmatch($0, relativePath, 0) == 0 }
158 }
159}