import Foundation struct DocLinkFailure: Error, CustomStringConvertible { let description: String } struct DocLinkChecker { let root: URL let pendingMedia: Set = [ "hero-light.png", "hero-dark.png", "layouts.gif", "layouts-reduced.png", "stacks.gif", "stacks-reduced.png", "snap-undo.gif", "snap-undo-reduced.png", ] func matches(_ pattern: String, in text: String) throws -> [String] { let regex = try NSRegularExpression(pattern: pattern) return regex.matches(in: text, range: NSRange(text.startIndex..., in: text)).compactMap { guard let range = Range($0.range(at: 1), in: text) else { return nil } return String(text[range]) } } func anchors(in text: String) throws -> Set { let headings = try matches("(?m)^#{1,6} +(.+)$", in: text) + matches("]*>(.*?)", in: text) var seen: [String: Int] = [:] var result: Set = [] for heading in headings { let stripped = heading.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression) .lowercased().replacingOccurrences(of: "[^\\p{L}\\p{N}_ -]", with: "", options: .regularExpression) .replacingOccurrences(of: " ", with: "-") let count = seen[stripped, default: 0] result.insert(count == 0 ? stripped : "\(stripped)-\(count)") seen[stripped] = count + 1 } return result } func check() throws -> [String] { guard let enumerator = FileManager.default.enumerator( at: root, includingPropertiesForKeys: [.isDirectoryKey], options: [.skipsHiddenFiles]) else { throw DocLinkFailure(description: "Could not enumerate documentation") } var failures: [String] = [] for case let entry as URL in enumerator { let file = entry.resolvingSymlinksInPath() if ["build", "node_modules"].contains(file.lastPathComponent) { enumerator.skipDescendants() continue } guard file.pathExtension == "md" else { continue } let source = try String(contentsOf: file, encoding: .utf8) let text = source.replacingOccurrences( of: "(?ms)^```[^\\n]*\\n.*?^```[^\\n]*$", with: "", options: .regularExpression) let links = try matches("\\[[^\\]]*\\]\\(([^\\s)]+)(?:[^)]*)\\)", in: text) + matches("(?:src|srcset|href)=\"([^\"]+)\"", in: text) for link in links { if link.range(of: "^[A-Za-z][A-Za-z0-9+.-]*:", options: .regularExpression) != nil || link.hasPrefix("//") { continue } let parts = link.split(separator: "#", maxSplits: 1, omittingEmptySubsequences: false) guard let path = String(parts[0]).removingPercentEncoding else { throw DocLinkFailure(description: "Invalid percent encoding in \(link)") } let destination = path.isEmpty ? file : file.deletingLastPathComponent().appendingPathComponent(path).standardizedFileURL let relative = String(file.path.dropFirst(root.path.count + 1)) if !FileManager.default.fileExists(atPath: destination.path) { let isSlot = relative == "README.md" && destination.deletingLastPathComponent() == root.appendingPathComponent("docs/media") && pendingMedia.contains(destination.lastPathComponent) if !isSlot { failures.append("\(relative): missing \(link)") } continue } if parts.count == 2, !parts[1].isEmpty { let target = try String(contentsOf: destination, encoding: .utf8) guard let anchor = String(parts[1]).removingPercentEncoding else { throw DocLinkFailure(description: "Invalid anchor encoding in \(link)") } if try !anchors(in: target).contains(anchor) { failures.append("\(relative): missing anchor \(link)") } } } } return failures.sorted() } } do { let arguments = Array(CommandLine.arguments.dropFirst()) guard arguments.isEmpty || (arguments.count == 2 && arguments[0] == "--root") else { throw DocLinkFailure(description: "Usage: check-doc-links.swift [--root directory]") } let root = arguments.isEmpty ? FileManager.default.currentDirectoryPath : arguments[1] let failures = try DocLinkChecker(root: URL(fileURLWithPath: root).standardizedFileURL.resolvingSymlinksInPath()) .check() guard failures.isEmpty else { throw DocLinkFailure(description: failures.joined(separator: "\n")) } print("Documentation links and anchors passed (unrecorded README media slots are allowed).") } catch { do { try FileHandle.standardError.write(contentsOf: Data("\(error)\n".utf8)) } catch { fatalError("Could not report documentation failure: \(error)") } exit(1) }