|
| 1 | +// |
| 2 | +// BeancountIncludeResolver.swift |
| 3 | +// BeancountDriverPlugin |
| 4 | +// |
| 5 | + |
| 6 | +import Foundation |
| 7 | + |
| 8 | +struct BeancountSourceGraph: Sendable { |
| 9 | + let sourceFiles: [URL] |
| 10 | + let watchedDirectories: [URL] |
| 11 | +} |
| 12 | + |
| 13 | +enum BeancountResolverError: LocalizedError { |
| 14 | + case includeCycle(String) |
| 15 | + case unreadable(URL, Error) |
| 16 | + |
| 17 | + var errorDescription: String? { |
| 18 | + switch self { |
| 19 | + case .includeCycle(let path): |
| 20 | + return String(format: String(localized: "Beancount include cycle detected at %@"), path) |
| 21 | + case .unreadable(let url, let error): |
| 22 | + return String(format: String(localized: "Could not read %@: %@"), url.path, error.localizedDescription) |
| 23 | + } |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +final class BeancountIncludeResolver { |
| 28 | + private var visited: Set<URL> = [] |
| 29 | + private var activeStack: Set<URL> = [] |
| 30 | + private var sourceFiles: [URL] = [] |
| 31 | + private var watchedDirectories: Set<URL> = [] |
| 32 | + |
| 33 | + func resolve(fileURL: URL) throws -> BeancountSourceGraph { |
| 34 | + visited.removeAll() |
| 35 | + activeStack.removeAll() |
| 36 | + sourceFiles.removeAll() |
| 37 | + watchedDirectories.removeAll() |
| 38 | + |
| 39 | + try resolveFile(fileURL.standardizedFileURL) |
| 40 | + |
| 41 | + return BeancountSourceGraph( |
| 42 | + sourceFiles: sourceFiles, |
| 43 | + watchedDirectories: watchedDirectories.sorted { $0.path < $1.path } |
| 44 | + ) |
| 45 | + } |
| 46 | + |
| 47 | + private func resolveFile(_ url: URL) throws { |
| 48 | + let normalized = url.standardizedFileURL |
| 49 | + if activeStack.contains(normalized) { |
| 50 | + throw BeancountResolverError.includeCycle(normalized.path) |
| 51 | + } |
| 52 | + guard !visited.contains(normalized) else { return } |
| 53 | + |
| 54 | + activeStack.insert(normalized) |
| 55 | + defer { activeStack.remove(normalized) } |
| 56 | + |
| 57 | + let contents: String |
| 58 | + do { |
| 59 | + contents = try String(contentsOf: normalized, encoding: .utf8) |
| 60 | + } catch { |
| 61 | + throw BeancountResolverError.unreadable(normalized, error) |
| 62 | + } |
| 63 | + |
| 64 | + visited.insert(normalized) |
| 65 | + sourceFiles.append(normalized) |
| 66 | + |
| 67 | + for rawLine in contents.components(separatedBy: .newlines) { |
| 68 | + let trimmed = stripComment(rawLine).trimmingCharacters(in: .whitespaces) |
| 69 | + guard trimmed.hasPrefix("include "), let includePath = quotedString(in: trimmed) else { continue } |
| 70 | + let includeURLs = try resolveIncludeURLs( |
| 71 | + includePath, |
| 72 | + relativeTo: normalized.deletingLastPathComponent() |
| 73 | + ) |
| 74 | + for includeURL in includeURLs { |
| 75 | + try resolveFile(includeURL) |
| 76 | + } |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + private func resolveIncludeURLs(_ includePath: String, relativeTo directory: URL) throws -> [URL] { |
| 81 | + guard containsGlobPattern(includePath) else { |
| 82 | + return [resolveIncludeURL(includePath, relativeTo: directory)] |
| 83 | + } |
| 84 | + |
| 85 | + let patternURL = resolveIncludeURL(includePath, relativeTo: directory) |
| 86 | + let patternPath = patternURL.path |
| 87 | + let searchRoot = globSearchRoot(for: patternPath) |
| 88 | + guard searchRoot.path != "/" else { return [] } |
| 89 | + |
| 90 | + let fileManager = FileManager.default |
| 91 | + guard fileManager.fileExists(atPath: searchRoot.path) else { |
| 92 | + watchedDirectories.insert(existingWatchDirectory(for: searchRoot)) |
| 93 | + return [] |
| 94 | + } |
| 95 | + watchedDirectories.insert(searchRoot) |
| 96 | + |
| 97 | + let regex = try NSRegularExpression(pattern: globRegex(for: patternPath)) |
| 98 | + let enumerator = fileManager.enumerator( |
| 99 | + at: searchRoot, |
| 100 | + includingPropertiesForKeys: [.isDirectoryKey, .isRegularFileKey], |
| 101 | + options: [.skipsHiddenFiles] |
| 102 | + ) |
| 103 | + |
| 104 | + var matches: [URL] = [] |
| 105 | + while let candidate = enumerator?.nextObject() as? URL { |
| 106 | + let values = try? candidate.resourceValues(forKeys: [.isDirectoryKey, .isRegularFileKey]) |
| 107 | + if values?.isDirectory == true { |
| 108 | + watchedDirectories.insert(candidate.standardizedFileURL) |
| 109 | + continue |
| 110 | + } |
| 111 | + guard values?.isRegularFile == true else { continue } |
| 112 | + |
| 113 | + let path = candidate.standardizedFileURL.path |
| 114 | + let range = NSRange(location: 0, length: (path as NSString).length) |
| 115 | + if regex.firstMatch(in: path, range: range) != nil { |
| 116 | + matches.append(candidate.standardizedFileURL) |
| 117 | + } |
| 118 | + } |
| 119 | + |
| 120 | + return matches.sorted { $0.path < $1.path } |
| 121 | + } |
| 122 | + |
| 123 | + private func resolveIncludeURL(_ includePath: String, relativeTo directory: URL) -> URL { |
| 124 | + if includePath.hasPrefix("/") { |
| 125 | + return URL(fileURLWithPath: includePath).standardizedFileURL |
| 126 | + } |
| 127 | + return directory.appendingPathComponent(includePath).standardizedFileURL |
| 128 | + } |
| 129 | + |
| 130 | + private func containsGlobPattern(_ path: String) -> Bool { |
| 131 | + path.contains("*") || path.contains("?") || path.contains("[") |
| 132 | + } |
| 133 | + |
| 134 | + private func globSearchRoot(for patternPath: String) -> URL { |
| 135 | + let components = (patternPath as NSString).pathComponents |
| 136 | + let prefix = components.prefix { !containsGlobPattern($0) } |
| 137 | + let rootPath = NSString.path(withComponents: Array(prefix)) |
| 138 | + return URL(fileURLWithPath: rootPath.isEmpty ? "/" : rootPath).standardizedFileURL |
| 139 | + } |
| 140 | + |
| 141 | + private func existingWatchDirectory(for missingDirectory: URL) -> URL { |
| 142 | + var candidate = missingDirectory.standardizedFileURL |
| 143 | + let fileManager = FileManager.default |
| 144 | + while candidate.path != "/" { |
| 145 | + var isDirectory: ObjCBool = false |
| 146 | + if fileManager.fileExists(atPath: candidate.path, isDirectory: &isDirectory), |
| 147 | + isDirectory.boolValue { |
| 148 | + return candidate |
| 149 | + } |
| 150 | + candidate.deleteLastPathComponent() |
| 151 | + } |
| 152 | + return URL(fileURLWithPath: "/") |
| 153 | + } |
| 154 | + |
| 155 | + private func globRegex(for patternPath: String) -> String { |
| 156 | + let characters = Array(patternPath) |
| 157 | + var regex = "^" |
| 158 | + var index = 0 |
| 159 | + |
| 160 | + while index < characters.count { |
| 161 | + let character = characters[index] |
| 162 | + if character == "*" { |
| 163 | + let nextIndex = index + 1 |
| 164 | + if nextIndex < characters.count, characters[nextIndex] == "*" { |
| 165 | + let slashIndex = index + 2 |
| 166 | + if slashIndex < characters.count, characters[slashIndex] == "/" { |
| 167 | + regex += "(?:.*/)?" |
| 168 | + index += 3 |
| 169 | + } else { |
| 170 | + regex += ".*" |
| 171 | + index += 2 |
| 172 | + } |
| 173 | + } else { |
| 174 | + regex += "[^/]*" |
| 175 | + index += 1 |
| 176 | + } |
| 177 | + } else if character == "?" { |
| 178 | + regex += "[^/]" |
| 179 | + index += 1 |
| 180 | + } else if character == "[" { |
| 181 | + let start = index |
| 182 | + index += 1 |
| 183 | + while index < characters.count, characters[index] != "]" { |
| 184 | + index += 1 |
| 185 | + } |
| 186 | + if index < characters.count { |
| 187 | + regex += String(characters[start...index]) |
| 188 | + index += 1 |
| 189 | + } else { |
| 190 | + regex += NSRegularExpression.escapedPattern(for: String(character)) |
| 191 | + } |
| 192 | + } else { |
| 193 | + regex += NSRegularExpression.escapedPattern(for: String(character)) |
| 194 | + index += 1 |
| 195 | + } |
| 196 | + } |
| 197 | + |
| 198 | + return regex + "$" |
| 199 | + } |
| 200 | + |
| 201 | + private func quotedString(in line: String) -> String? { |
| 202 | + var inQuote = false |
| 203 | + var isEscaped = false |
| 204 | + var current = "" |
| 205 | + |
| 206 | + for character in line { |
| 207 | + if isEscaped { |
| 208 | + current.append(character) |
| 209 | + isEscaped = false |
| 210 | + continue |
| 211 | + } |
| 212 | + if character == "\\" { |
| 213 | + isEscaped = true |
| 214 | + continue |
| 215 | + } |
| 216 | + if character == "\"" { |
| 217 | + if inQuote { |
| 218 | + return current |
| 219 | + } |
| 220 | + inQuote = true |
| 221 | + continue |
| 222 | + } |
| 223 | + if inQuote { |
| 224 | + current.append(character) |
| 225 | + } |
| 226 | + } |
| 227 | + |
| 228 | + return nil |
| 229 | + } |
| 230 | + |
| 231 | + private func stripComment(_ line: String) -> String { |
| 232 | + var inQuote = false |
| 233 | + var isEscaped = false |
| 234 | + var result = "" |
| 235 | + for character in line { |
| 236 | + if isEscaped { |
| 237 | + result.append(character) |
| 238 | + isEscaped = false |
| 239 | + continue |
| 240 | + } |
| 241 | + if character == "\\" { |
| 242 | + result.append(character) |
| 243 | + isEscaped = true |
| 244 | + continue |
| 245 | + } |
| 246 | + if character == "\"" { |
| 247 | + inQuote.toggle() |
| 248 | + } |
| 249 | + if character == ";" && !inQuote { |
| 250 | + break |
| 251 | + } |
| 252 | + result.append(character) |
| 253 | + } |
| 254 | + return result |
| 255 | + } |
| 256 | +} |
0 commit comments