Sources/OrgCore/Lint/Lint.swift
163 lines · 7449 bytes
6 symbols in this file
1import Foundation
2
3/// How sure a checker is that what it reports is a mistake, as org-lint's `:trust`.
4public enum LintTrust: String, Sendable {
5 case high, low
6}
7
8/// The checks Lint File runs. A checker with org-lint's name reports what org-lint's checker of
9/// that name reports (`org-lint.el`, Org 9.8.7), with the same trust; the others are orgstar's.
10public enum LintChecker: String, CaseIterable, Sendable {
11 // Links.
12 case invalidFuzzyLink = "invalid-fuzzy-link"
13 case invalidCustomIDLink = "invalid-custom-id-link"
14 case invalidIDLink = "invalid-id-link"
15 case invalidCoderefLink = "invalid-coderef-link"
16 case linkToLocalFile = "link-to-local-file"
17 case invalidFileSearch = "invalid-file-search"
18 case fileApplication = "file-application"
19 // Attachments.
20 case missingAttachmentFolder = "missing-attachment-folder"
21 case orphanedAttachmentFolder = "orphaned-attachment-folder"
22 // Duplicates.
23 case duplicateID = "duplicate-id"
24 case duplicateCustomID = "duplicate-custom-id"
25 case duplicateName = "duplicate-name"
26 case duplicateTarget = "duplicate-target"
27 case duplicateFootnoteDefinition = "duplicate-footnote-definition"
28 // Structure.
29 case incompleteDrawer = "incomplete-drawer"
30 case invalidBlock = "invalid-block"
31 case misplacedPlanningInfo = "misplaced-planning-info"
32 case obsoletePropertiesDrawer = "obsolete-properties-drawer"
33 case misplacedHeading = "misplaced-heading"
34 case indentedDiarySexp = "indented-diary-sexp"
35 case invalidKeywordSyntax = "invalid-keyword-syntax"
36 case orphanedAffiliatedKeywords = "orphaned-affiliated-keywords"
37 case obsoleteAffiliatedKeywords = "obsolete-affiliated-keywords"
38 case missingLanguageInSrcBlock = "missing-language-in-src-block"
39 case missingBackendInExportBlock = "missing-backend-in-export-block"
40 case deprecatedExportBlocks = "deprecated-export-blocks"
41 case deprecatedCategorySetup = "deprecated-category-setup"
42 case nonExistentSetupfileParameter = "non-existent-setupfile-parameter"
43 // Headings and properties.
44 case unknownTodoKeyword = "unknown-todo-keyword"
45 case priority
46 case spuriousColons = "spurious-colons"
47 case quoteSection = "quote-section"
48 case specialPropertyInPropertiesDrawer = "special-property-in-properties-drawer"
49 case invalidEffortProperty = "invalid-effort-property"
50 case invalidIDProperty = "invalid-id-property"
51 // Timestamps.
52 case timestampSyntax = "timestamp-syntax"
53 case clockSyntax = "clock-syntax"
54 case planningInactive = "planning-inactive"
55 case mismatchedPlanningRepeaters = "mismatched-planning-repeaters"
56 // Footnotes.
57 case undefinedFootnoteReference = "undefined-footnote-reference"
58 case unreferencedFootnoteDefinition = "unreferenced-footnote-definition"
59
60 /// org-lint has a checker by this name.
61 public var isOrgLint: Bool {
62 switch self {
63 case .invalidFileSearch, .missingAttachmentFolder, .orphanedAttachmentFolder, .duplicateID, .unknownTodoKeyword: false
64 default: true
65 }
66 }
67
68 public var trust: LintTrust {
69 switch self {
70 case .linkToLocalFile, .invalidFileSearch, .orphanedAttachmentFolder, .incompleteDrawer, .invalidBlock, .misplacedPlanningInfo,
71 .misplacedHeading, .indentedDiarySexp, .invalidKeywordSyntax, .orphanedAffiliatedKeywords, .deprecatedExportBlocks,
72 .nonExistentSetupfileParameter, .unknownTodoKeyword, .quoteSection, .timestampSyntax, .clockSyntax,
73 .mismatchedPlanningRepeaters:
74 .low
75 default:
76 .high
77 }
78 }
79}
80
81/// One problem in a file.
82public struct LintFinding: Sendable, Equatable, Hashable, Identifiable {
83 /// UTF-16 offset in the file's text.
84 public let offset: Int
85 /// 1-based.
86 public let line: Int
87 public let checker: LintChecker
88 public let message: String
89
90 public init(offset: Int, line: Int, checker: LintChecker, message: String) {
91 self.offset = offset
92 self.line = line
93 self.checker = checker
94 self.message = message
95 }
96
97 public var trust: LintTrust { checker.trust }
98
99 public var id: String { "\(offset) \(checker.rawValue) \(message)" }
100}
101
102/// What the checkers know of the world outside the file: the file system and the workspace's
103/// IDs. The file system's paths are absolute.
104public struct LintEnvironment: Sendable {
105 public var fileExists: @Sendable (String) -> Bool
106 public var isDirectory: @Sendable (String) -> Bool
107 /// The names in a folder.
108 public var contentsOfDirectory: @Sendable (String) -> [String]
109 /// The text of an Org file another file links into.
110 public var readFile: @Sendable (String) -> String?
111 /// The other files whose entries or file property drawers have this ID. Nil without a
112 /// workspace index: IDs then resolve in the file alone, and attachment folders aren't
113 /// checked for entries.
114 public var idFiles: (@Sendable (String) -> [String])?
115 /// `org-attach-id-dir` and `org-attach-use-inheritance`, as `OrgAttach.directory` takes them.
116 public var attachIDDir: String
117 public var attachInherit: Bool?
118 /// `org-crypt-tag-matcher`: entries with this tag and an encrypted body aren't linted inside.
119 public var cryptTag: String
120
121 public init(
122 fileExists: @escaping @Sendable (String) -> Bool, isDirectory: @escaping @Sendable (String) -> Bool,
123 contentsOfDirectory: @escaping @Sendable (String) -> [String], readFile: @escaping @Sendable (String) -> String?,
124 idFiles: (@Sendable (String) -> [String])? = nil, attachIDDir: String = "data/", attachInherit: Bool? = nil, cryptTag: String = "crypt"
125 ) {
126 self.fileExists = fileExists
127 self.isDirectory = isDirectory
128 self.contentsOfDirectory = contentsOfDirectory
129 self.readFile = readFile
130 self.idFiles = idFiles
131 self.attachIDDir = attachIDDir
132 self.attachInherit = attachInherit
133 self.cryptTag = cryptTag
134 }
135
136 /// The local file system, with no workspace index.
137 public static let fileSystem = LintEnvironment(
138 fileExists: { FileManager.default.fileExists(atPath: $0) },
139 isDirectory: { path in
140 var directory: ObjCBool = false
141 return FileManager.default.fileExists(atPath: path, isDirectory: &directory) && directory.boolValue
142 },
143 contentsOfDirectory: { (try? FileManager.default.contentsOfDirectory(atPath: $0)) ?? [] },
144 readFile: { try? String(contentsOfFile: $0, encoding: .utf8) }
145 )
146}
147
148/// Lint File: problems in one Org file, as org-lint reports them. Reports only; nothing is
149/// changed. The file is the whole input, so a command over many files runs this once per file
150/// with one environment.
151public enum OrgLint {
152 /// The findings in `text`, parsed as `tree`, by offset. `path` is where the file is, for
153 /// relative links, setup files and attachments; nil skips those checks.
154 public static func lint(_ text: String, tree: OrgTree, path: String?, environment: LintEnvironment = .fileSystem) -> [LintFinding] {
155 var linter = Linter(text: text, tree: tree, path: path, environment: environment)
156 linter.run()
157 return linter.findings.sorted { ($0.offset, $0.checker.order) < ($1.offset, $1.checker.order) }
158 }
159}
160
161extension LintChecker {
162 var order: Int { Self.allCases.firstIndex(of: self)! }
163}