Sources/OrgCore/Lint/Lint.swift

1136db9ac14f93d2ef778c0b591f9c5ec322ed1c
orgstar/Sources/OrgCore/Lint/Lint.swift

166 lines · 7621 bytes

  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    /// For an orphaned attachment folder, its path, which every file beside it reports.
 90    public let folder: String?
 91
 92    public init(offset: Int, line: Int, checker: LintChecker, message: String, folder: String? = nil) {
 93        self.offset = offset
 94        self.line = line
 95        self.checker = checker
 96        self.message = message
 97        self.folder = folder
 98    }
 99
100    public var trust: LintTrust { checker.trust }
101
102    public var id: String { "\(offset) \(checker.rawValue) \(message)" }
103}
104
105/// What the checkers know of the world outside the file: the file system and the workspace's
106/// IDs. The file system's paths are absolute.
107public struct LintEnvironment: Sendable {
108    public var fileExists: @Sendable (String) -> Bool
109    public var isDirectory: @Sendable (String) -> Bool
110    /// The names in a folder.
111    public var contentsOfDirectory: @Sendable (String) -> [String]
112    /// The text of an Org file another file links into.
113    public var readFile: @Sendable (String) -> String?
114    /// The other files whose entries or file property drawers have this ID. Nil without a
115    /// workspace index: IDs then resolve in the file alone, and attachment folders aren't
116    /// checked for entries.
117    public var idFiles: (@Sendable (String) -> [String])?
118    /// `org-attach-id-dir` and `org-attach-use-inheritance`, as `OrgAttach.directory` takes them.
119    public var attachIDDir: String
120    public var attachInherit: Bool?
121    /// `org-crypt-tag-matcher`: entries with this tag and an encrypted body aren't linted inside.
122    public var cryptTag: String
123
124    public init(
125        fileExists: @escaping @Sendable (String) -> Bool, isDirectory: @escaping @Sendable (String) -> Bool,
126        contentsOfDirectory: @escaping @Sendable (String) -> [String], readFile: @escaping @Sendable (String) -> String?,
127        idFiles: (@Sendable (String) -> [String])? = nil, attachIDDir: String = "data/", attachInherit: Bool? = nil, cryptTag: String = "crypt"
128    ) {
129        self.fileExists = fileExists
130        self.isDirectory = isDirectory
131        self.contentsOfDirectory = contentsOfDirectory
132        self.readFile = readFile
133        self.idFiles = idFiles
134        self.attachIDDir = attachIDDir
135        self.attachInherit = attachInherit
136        self.cryptTag = cryptTag
137    }
138
139    /// The local file system, with no workspace index.
140    public static let fileSystem = LintEnvironment(
141        fileExists: { FileManager.default.fileExists(atPath: $0) },
142        isDirectory: { path in
143            var directory: ObjCBool = false
144            return FileManager.default.fileExists(atPath: path, isDirectory: &directory) && directory.boolValue
145        },
146        contentsOfDirectory: { (try? FileManager.default.contentsOfDirectory(atPath: $0)) ?? [] },
147        readFile: { try? String(contentsOfFile: $0, encoding: .utf8) }
148    )
149}
150
151/// Lint File: problems in one Org file, as org-lint reports them. Reports only; nothing is
152/// changed. The file is the whole input, so a command over many files runs this once per file
153/// with one environment.
154public enum OrgLint {
155    /// The findings in `text`, parsed as `tree`, by offset. `path` is where the file is, for
156    /// relative links, setup files and attachments; nil skips those checks.
157    public static func lint(_ text: String, tree: OrgTree, path: String?, environment: LintEnvironment = .fileSystem) -> [LintFinding] {
158        var linter = Linter(text: text, tree: tree, path: path, environment: environment)
159        linter.run()
160        return linter.findings.sorted { ($0.offset, $0.checker.order) < ($1.offset, $1.checker.order) }
161    }
162}
163
164extension LintChecker {
165    var order: Int { Self.allCases.firstIndex(of: self)! }
166}
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