Sources/OrgApp/FileLint.swift
175 lines · 8594 bytes
1import Foundation
2import OrgCore
3import OrgDocument
4import OrgIndex
5
6/// Lint File in the apps: the checkers run over an open file's text off the main actor, with
7/// the file system and the workspace index for IDs in other files.
8public enum FileLint {
9 /// The checkers' environment: the file system, IDs through `index` (unsaved buffers'
10 /// from `overlay`), and the attachment and crypt settings.
11 public static func environment(index: IndexStore?, overlay: [String: FileRecord] = [:], defaults: UserDefaults = .standard) -> LintEnvironment {
12 var environment = LintEnvironment.fileSystem
13 environment.attachIDDir = OrgPreferences.attachIDDir(defaults)
14 environment.attachInherit = OrgPreferences.attachUseInheritance(defaults)
15 environment.cryptTag = OrgPreferences.cryptTag(defaults)
16 if let index {
17 environment.idFiles = { id in ((try? index.headings(withID: id, overlay: overlay)) ?? []).map(\.path) }
18 }
19 return environment
20 }
21
22 /// Whether Lint File applies to the file at `path`: Org files, and encrypted ones once
23 /// decrypted in memory.
24 public static func applies(to path: String?) -> Bool {
25 guard let path else { return false }
26 return path.hasSuffix(".org") || path.hasSuffix(".org_archive") || path.hasSuffix(".org.gpg")
27 }
28
29 /// The findings in `text`, off the main actor.
30 @concurrent
31 public static func lint(_ text: String, tree: OrgTree, path: String?, environment: LintEnvironment) async -> [LintFinding] {
32 OrgLint.lint(text, tree: tree, path: path, environment: environment)
33 }
34
35 /// One file's findings in Lint All Folders.
36 public struct FileFindings: Sendable, Identifiable {
37 public let path: String
38 public let findings: [LintFinding]
39 public var id: String { path }
40 }
41
42 /// The files Lint All Folders checks: the indexed Org files and archives. Encrypted files
43 /// (`.org.gpg`) are left out.
44 public static func folderPaths(_ files: [FileEntry]) -> [String] {
45 files.filter { ($0.kind == .org || $0.kind == .archive) && applies(to: $0.path) && !CryptVault.isEncryptedFile($0.path) }.map(\.path).sorted()
46 }
47
48 /// How Lint All Folders names each file: its path below its folder, after the folder's name
49 /// when there are several folders.
50 public static func names(_ files: [FileEntry]) -> [String: String] {
51 let several = Set(files.map(\.root)).count > 1
52 return Dictionary(files.map { ($0.path, several ? "\(($0.root as NSString).lastPathComponent)/\($0.relativePath)" : $0.relativePath) },
53 uniquingKeysWith: { first, _ in first })
54 }
55
56 /// Lint All Folders: the findings in each of `paths`, read from disk or, for an open file,
57 /// from `texts`, off the main actor and several files at a time. Files with none are left
58 /// out. An orphaned attachment folder is reported once, by the first file that finds it.
59 /// `progress` is told the number of files checked so far. Throws `CancellationError` when
60 /// the task is cancelled.
61 @concurrent
62 public static func lint(
63 paths: [String], texts: [String: String], defaults: OrgSettings = .default, environment: LintEnvironment,
64 progress: @escaping @Sendable (Int) async -> Void = { _ in }
65 ) async throws -> [FileFindings] {
66 let chunk = 32
67 let chunks = stride(from: 0, to: paths.count, by: chunk).map { Array(paths[$0..<min($0 + chunk, paths.count)]) }
68 var results = [[FileFindings]](repeating: [], count: chunks.count)
69 try await withThrowingTaskGroup(of: (Int, [FileFindings]).self) { group in
70 var next = 0
71 func add() {
72 guard next < chunks.count else { return }
73 let index = next, paths = chunks[index]
74 next += 1
75 group.addTask {
76 var found: [FileFindings] = []
77 for path in paths {
78 try Task.checkCancellation()
79 guard let text = texts[path] ?? (try? String(contentsOfFile: path, encoding: .utf8)) else { continue }
80 let findings = OrgLint.lint(text, tree: OrgParser.parse(text, defaults: defaults), path: path, environment: environment)
81 if !findings.isEmpty { found.append(FileFindings(path: path, findings: findings)) }
82 }
83 return (index, found)
84 }
85 }
86 for _ in 0..<max(1, ProcessInfo.processInfo.activeProcessorCount) { add() }
87 var done = 0
88 while let (index, found) = try await group.next() {
89 results[index] = found
90 done += chunks[index].count
91 await progress(done)
92 try Task.checkCancellation()
93 add()
94 }
95 }
96 var folders: Set<String> = []
97 return results.joined().compactMap { file in
98 let findings = file.findings.filter { $0.folder.map { folders.insert($0).inserted } ?? true }
99 return findings.isEmpty ? nil : FileFindings(path: file.path, findings: findings)
100 }
101 }
102
103 /// A finding's trust as the panels show it: org-lint's high trust as an error, low as a warning.
104 public static func severity(_ finding: LintFinding) -> String {
105 finding.trust == .high ? String(localized: "Error", comment: "Lint File: a problem org-lint trusts highly") : String(localized: "Warning", comment: "Lint File: a problem that may be intended")
106 }
107
108 /// The panels' summary line.
109 public static func summary(_ findings: [LintFinding]) -> String {
110 findings.isEmpty ? String(localized: "No problems found", comment: "Lint File") : String(localized: "\(findings.count) problems", comment: "Lint File: the number of problems found")
111 }
112}
113
114/// Lint All Folders as the panels run it: every indexed Org file checked off the main actor,
115/// with progress, until it finishes or is stopped.
116@MainActor
117@Observable
118public final class FolderLint {
119 /// The files with findings, by path; nil until a run finishes.
120 public private(set) var files: [FileLint.FileFindings]?
121 public private(set) var checked = 0
122 public private(set) var total = 0
123 public private(set) var isRunning = false
124 @ObservationIgnored private var task: Task<Void, Never>?
125 /// Counts runs, so a stopped run's last progress doesn't show in the next.
126 @ObservationIgnored private var run = 0
127
128 public init() {}
129
130 /// Checks every indexed file again; open files as their buffers have them.
131 public func run(workspace: WorkspaceModel, session: DocumentSession) {
132 task?.cancel()
133 let paths = FileLint.folderPaths(workspace.files)
134 let open = session.openDocuments
135 let texts = Dictionary(open.map { ($0.path, $0.document.text) }, uniquingKeysWith: { first, _ in first })
136 let environment = FileLint.environment(index: workspace.index, overlay: workspace.overlay(open))
137 let defaults = session.defaults
138 files = nil
139 checked = 0
140 total = paths.count
141 isRunning = true
142 run += 1
143 let run = run
144 task = Task { [weak self] in
145 let found = try? await FileLint.lint(paths: paths, texts: texts, defaults: defaults, environment: environment) { [weak self] checked in
146 await self?.progressed(checked, run: run)
147 }
148 guard let self, let found, !Task.isCancelled else { return }
149 files = found
150 isRunning = false
151 }
152 }
153
154 public func stop() {
155 task?.cancel()
156 task = nil
157 isRunning = false
158 }
159
160 private func progressed(_ count: Int, run: Int) {
161 if run == self.run { checked = count }
162 }
163
164 /// The panels' summary line.
165 public var summary: String {
166 guard let files else {
167 return isRunning
168 ? String(localized: "Checked \(checked) of \(total) files", comment: "Lint All Folders: progress")
169 : String(localized: "Stopped after \(checked) of \(total) files", comment: "Lint All Folders: stopped before the end")
170 }
171 let findings = files.flatMap(\.findings)
172 if findings.isEmpty { return String(localized: "No problems found in \(total) files", comment: "Lint All Folders") }
173 return String(localized: "\(FileLint.summary(findings)) in \(files.count) of \(total) files", comment: "Lint All Folders: the number of problems, files with problems, files checked")
174 }
175}