Files
helder/Sources/HelderCore/Files/FileLimits.swift
T

203 lines
8.7 KiB
Swift

import Foundation
public enum FileLimits {
/// Files above this size are left out of the content index.
public static let maxIndexedFileBytes = 300_000
public static let maxIndexedFiles = 6000
public static let maxImageBytes = 25_000_000
/// Git reads a file above this size as having no text, so one dump or lock file cannot stall the column.
public static let maxDiffFileBytes = 1_000_000
/// How deep the fallback directory walk goes.
public static let maxWalkDepth = 12
/// A NUL byte in the first 8000 bytes marks a file as binary, like git does.
public static func looksBinary(_ data: Data) -> Bool {
data.prefix(8000).contains(0)
}
public static let imageMimeTypes: [String: String] = [
"png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg", "jfif": "image/jpeg",
"gif": "image/gif", "webp": "image/webp", "svg": "image/svg+xml", "bmp": "image/bmp",
"ico": "image/x-icon", "avif": "image/avif", "apng": "image/apng",
]
}
public enum IgnoreRules {
/// Folders the fallback walk and the watcher never enter.
public static let walkIgnoredNames: Set<String> = [
"node_modules", ".git", "out", "dist", "build", ".next", ".nuxt",
".cache", "coverage", "vendor", ".idea", ".vscode", ".helder", ".turbo",
]
/// Always passed to ripgrep as `!glob`, on top of gitignore and `files.exclude`.
/// `.DS_Store` is here because `followGitignore` defaults to false (rg runs with --no-ignore).
public static let ripgrepBaseIgnore = [
"node_modules", ".git", "out", "dist", "build", ".cache",
"vendor", "coverage", ".helder", ".next", ".nuxt", ".turbo", ".idea", ".vscode",
".DS_Store",
]
/// Declarations are indexed inside `vendor/` too, so framework classes stay clickable.
public static let symbolDeclarationIgnore = ripgrepBaseIgnore.filter { $0 != "vendor" && $0 != ".DS_Store" }
/// References skip `vendor/`: nobody wants to read how a framework uses a class.
public static let symbolReferenceIgnore = ripgrepBaseIgnore.filter { $0 != ".DS_Store" }
/// True for a name the fallback walk skips.
public static func isWalkIgnored(_ name: String) -> Bool {
walkIgnoredNames.contains(name) || name == ".DS_Store"
}
/// True when any segment of a relative path is an ignored folder; the watcher drops such events.
public static func isWatchIgnored(_ relativePath: String) -> Bool {
relativePath.split(separator: "/").contains { walkIgnoredNames.contains(String($0)) }
}
/// Framework caches rewritten on every request or test run; watching them refreshes the project in a loop.
public static let watchIgnoredPrefixes = [
"storage/framework/", "bootstrap/cache/", ".phpunit.result.cache", ".phpunit.cache/",
]
/// `isWatchIgnored`, plus the framework caches and the project's `files.exclude` globs.
public static func isWatchIgnored(_ relativePath: String, exclude: [String]) -> Bool {
if isWatchIgnored(relativePath) { return true }
if watchIgnoredPrefixes.contains(where: { relativePath == $0 || relativePath.hasPrefix($0) || $0 == relativePath + "/" }) {
return true
}
return exclude.contains { !$0.isEmpty && globMatches($0, path: relativePath) }
}
/// The `--glob !x` pairs plus `--no-ignore` that make ripgrep honour the project's file settings.
public static func ripgrepArguments(files: HelderConfig.Files, base: [String] = ripgrepBaseIgnore) -> [String] {
var args: [String] = []
for glob in base { args += ["--glob", "!" + glob] }
for glob in files.exclude where !glob.isEmpty { args += ["--glob", "!" + glob] }
if !files.followGitignore { args.append("--no-ignore") }
return args
}
/// Gitignore-style glob match of a relative path, with ripgrep's `--glob` semantics.
///
/// A pattern without a slash matches a basename at any depth; `**` crosses folders, `*` and `?`
/// stop at a slash. A matching folder matches everything under it, as in ripgrep.
public static func globMatches(_ glob: String, path: String) -> Bool {
var pattern = Substring(glob)
while pattern.hasSuffix("/") { pattern = pattern.dropLast() }
let rooted = pattern.hasPrefix("/")
if rooted { pattern = pattern.dropFirst() }
guard !pattern.isEmpty else { return false }
let anchored = rooted || pattern.contains("/")
let candidates = PathUtils.ancestors(path) + [path]
for alternative in expandBraces(String(pattern)) {
let chars = Array(alternative)
for candidate in candidates {
let subject = Array(anchored ? candidate : PathUtils.basename(candidate))
var matcher = WildcardMatcher(pattern: chars, subject: subject)
if matcher.matches() { return true }
}
}
return false
}
/// `{a,b}` alternation expanded into plain patterns; nested braces expand recursively.
static func expandBraces(_ pattern: String) -> [String] {
let chars = Array(pattern)
guard let open = chars.firstIndex(of: "{") else { return [pattern] }
var depth = 0
var parts: [String] = []
var current = ""
for k in (open + 1)..<chars.count {
let c = chars[k]
if c == "{" { depth += 1 }
if c == "}" {
if depth == 0 {
parts.append(current)
let head = String(chars[..<open]), rest = String(chars[(k + 1)...])
return parts.flatMap { expandBraces(head + $0 + rest) }
}
depth -= 1
}
if c == "," && depth == 0 {
parts.append(current)
current = ""
} else {
current.append(c)
}
}
return [pattern]
}
}
/// Glob matcher: `**` crosses folders, `*` and `?` stop at a slash, `[...]` is a character class.
private struct WildcardMatcher {
let pattern: [Character]
let subject: [Character]
private var memo: [Bool?]
init(pattern: [Character], subject: [Character]) {
self.pattern = pattern
self.subject = subject
memo = Array(repeating: nil, count: (pattern.count + 1) * (subject.count + 1))
}
mutating func matches() -> Bool { match(0, 0) }
private mutating func match(_ p: Int, _ s: Int) -> Bool {
let key = p * (subject.count + 1) + s
if let known = memo[key] { return known }
let result = compute(p, s)
memo[key] = result
return result
}
private mutating func compute(_ p: Int, _ s: Int) -> Bool {
guard p < pattern.count else { return s == subject.count }
switch pattern[p] {
case "*":
if p + 1 < pattern.count && pattern[p + 1] == "*" {
let afterStars = p + 2
if afterStars < pattern.count && pattern[afterStars] == "/" && match(afterStars + 1, s) { return true }
for k in s...subject.count where match(afterStars, k) { return true }
return false
}
var k = s
while true {
if match(p + 1, k) { return true }
if k == subject.count || subject[k] == "/" { return false }
k += 1
}
case "?":
return s < subject.count && subject[s] != "/" && match(p + 1, s + 1)
case "[":
guard s < subject.count, subject[s] != "/", let (hit, next) = classMatch(p, subject[s]) else {
return s < subject.count && subject[s] == "[" && match(p + 1, s + 1)
}
return hit && match(next, s + 1)
case "\\" where p + 1 < pattern.count:
return s < subject.count && subject[s] == pattern[p + 1] && match(p + 2, s + 1)
default:
return s < subject.count && subject[s] == pattern[p] && match(p + 1, s + 1)
}
}
/// Whether `c` is in the class opening at `p`, and the index after it; nil for an unclosed `[`.
private func classMatch(_ p: Int, _ c: Character) -> (Bool, Int)? {
var k = p + 1
let negated = k < pattern.count && (pattern[k] == "!" || pattern[k] == "^")
if negated { k += 1 }
var hit = false
var first = true
while k < pattern.count {
if pattern[k] == "]" && !first { return (hit != negated, k + 1) }
first = false
if k + 2 < pattern.count && pattern[k + 1] == "-" && pattern[k + 2] != "]" {
if pattern[k] <= c && c <= pattern[k + 2] { hit = true }
k += 3
} else {
if pattern[k] == c { hit = true }
k += 1
}
}
return nil
}
}