Sources/OrgWorkspace/Discovery.swift

49c5da97098ed000be935c19462d4102812b0471
orgstar/Sources/OrgWorkspace/Discovery.swift

161 lines · 7251 bytes

14 symbols in this file
  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; Markdown and `.txt` files are `.text`, other
 73    /// files that aren't org files `.other`.
 74    public static func classify(_ name: String, rules: ScanRules = ScanRules()) -> FileClassification {
 75        if name.hasPrefix(".") {
 76            if name.hasSuffix(".icloud") {
 77                let inner = String(name.dropFirst().dropLast(".icloud".count))
 78                if case .file = classify(inner, rules: rules) { return .placeholder(inner) }
 79                return .ignored
 80            }
 81            if !rules.hiddenFiles || name.hasPrefix(".#") || name.hasPrefix(".syncthing.") || name.contains(".orgstar-")
 82                || name == ".DS_Store" || name == ".localized" {
 83                return .ignored
 84            }
 85        }
 86        if name.hasSuffix("~") || name.hasPrefix("#") { return .ignored }
 87        let conflict = name.contains(".sync-conflict-")
 88        if name.hasSuffix(".org") { return .file(conflict ? .conflict : .org) }
 89        if name.hasSuffix(".org_archive") { return .file(conflict ? .conflict : .archive) }
 90        if Markdown.isPath(name) || Markdown.isPlainTextPath(name) { return .file(conflict ? .conflict : .text) }
 91        return .file(.other)
 92    }
 93
 94    /// Resource keys a scan reads.
 95    static let keys: [URLResourceKey] = [
 96        .isDirectoryKey, .fileSizeKey, .contentModificationDateKey, .isUbiquitousItemKey, .ubiquitousItemDownloadingStatusKey,
 97    ]
 98
 99    /// An iCloud file whose contents aren't on this device: reading it would wait for the
100    /// download, so it's asked to download and indexed when it arrives. Since macOS 14 these
101    /// keep their own names rather than `.name.icloud`.
102    public static func isPending(isUbiquitous: Bool?, status: URLUbiquitousItemDownloadingStatus?) -> Bool {
103        isUbiquitous == true && status == .notDownloaded
104    }
105
106    static func isPending(_ values: URLResourceValues) -> Bool {
107        isPending(isUbiquitous: values.isUbiquitousItem, status: values.ubiquitousItemDownloadingStatus)
108    }
109
110    /// Every file under `root`, skipping the folders `rules` ignores.
111    public static func scan(_ root: URL, rules: ScanRules = ScanRules()) throws -> Discovery {
112        let keys = Self.keys
113        guard let enumerator = FileManager.default.enumerator(at: root, includingPropertiesForKeys: keys) else {
114            return Discovery()
115        }
116        var discovery = Discovery()
117        for case let url as URL in enumerator {
118            let values = try url.resourceValues(forKeys: Set(keys))
119            let name = url.lastPathComponent
120            if values.isDirectory == true {
121                if rules.skipsFolder(name) { enumerator.skipDescendants() }
122                continue
123            }
124            switch classify(name, rules: rules) {
125            case .file where isPending(values):
126                discovery.placeholders.append(url.standardizedFileURL)
127            case .file(let kind):
128                discovery.files.append(DiscoveredFile(
129                    url: url.standardizedFileURL,
130                    kind: kind,
131                    size: values.fileSize ?? 0,
132                    mtime: values.contentModificationDate?.timeIntervalSince1970 ?? 0
133                ))
134            case .placeholder(let inner):
135                discovery.placeholders.append(url.deletingLastPathComponent().appendingPathComponent(inner).standardizedFileURL)
136            case .ignored:
137                break
138            }
139        }
140        discovery.files.sort { $0.url.path < $1.url.path }
141        return discovery
142    }
143}
144
145/// Which files feed the agenda: `.org` files (not archives or conflict copies) matching one of
146/// the globs, relative to their root. No globs means every `.org` file.
147public struct AgendaScope: Sendable, Equatable {
148    public var globs: [String]
149
150    public init(globs: [String] = []) {
151        self.globs = globs
152    }
153
154    public func contains(relativePath: String, kind: FileKind) -> Bool {
155        // `org-agenda-file-regexp` leaves out dotfiles.
156        guard kind == .org, !(relativePath as NSString).lastPathComponent.hasPrefix(".") else { return false }
157        guard !globs.isEmpty else { return true }
158        // Without FNM_PATHNAME, `*` also matches `/`, so `work/*` covers nested folders.
159        return globs.contains { fnmatch($0, relativePath, 0) == 0 }
160    }
161}
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