restores Helder in all its glory
This commit is contained in:
@@ -0,0 +1,235 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
|
||||
/// Which files a scan may enter: ripgrep's `!glob` names plus the project's file settings.
|
||||
struct ScanFilter: Sendable, Equatable {
|
||||
var base: [String]
|
||||
var files: HelderConfig.Files
|
||||
}
|
||||
|
||||
/// One line search, answered the same way by ripgrep and by the walk.
|
||||
struct LineQuery: Sendable, Equatable {
|
||||
enum Pattern: Sendable, Equatable {
|
||||
/// Fixed string; case-insensitive unless it holds an uppercase letter.
|
||||
case smartCaseLiteral(String)
|
||||
/// Case-sensitive regular expression in the subset ripgrep and ICU share.
|
||||
case regex(String)
|
||||
/// Case-sensitive literal that must stand as a whole word.
|
||||
case word(String)
|
||||
}
|
||||
|
||||
var pattern: Pattern
|
||||
/// Only files with this extension, e.g. "php".
|
||||
var fileExtension: String? = nil
|
||||
var maxPerFile: Int? = nil
|
||||
var maxColumns: Int? = nil
|
||||
/// Lets the walk stop early; ripgrep has no such flag, so callers still cap themselves.
|
||||
var maxFiles: Int? = nil
|
||||
}
|
||||
|
||||
/// Lists and searches project files; the relative paths use "/".
|
||||
protocol ProjectScanning: Sendable {
|
||||
/// Relative paths of the files under `scope` (nil is the root), sorted.
|
||||
func files(under scope: String?, filter: ScanFilter) async -> [String]
|
||||
/// Matching lines with absolute paths, grouped per file and in line order within a file.
|
||||
func matches(_ query: LineQuery, filter: ScanFilter) async -> [RipgrepMatch]
|
||||
}
|
||||
|
||||
enum ProjectScanner {
|
||||
/// `$RG_BINARY` when it names an executable, else `rg` through the locator.
|
||||
static func ripgrep(locator: ExecutableLocator, environment: [String: String]) -> URL? {
|
||||
if let override = environment["RG_BINARY"], !override.isEmpty,
|
||||
FileManager.default.isExecutableFile(atPath: override) {
|
||||
return URL(fileURLWithPath: override)
|
||||
}
|
||||
return locator.locate("rg")
|
||||
}
|
||||
|
||||
static func make(root: URL, runner: ProcessRunning, locator: ExecutableLocator,
|
||||
environment: [String: String]) -> ProjectScanning {
|
||||
if let binary = ripgrep(locator: locator, environment: environment) {
|
||||
return RipgrepScanner(root: root, binary: binary, runner: runner)
|
||||
}
|
||||
return WalkScanner(root: root, runner: runner)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ripgrep
|
||||
|
||||
struct RipgrepScanner: ProjectScanning {
|
||||
let root: URL
|
||||
let binary: URL
|
||||
let runner: ProcessRunning
|
||||
|
||||
func files(under scope: String?, filter: ScanFilter) async -> [String] {
|
||||
let target = scope.flatMap { $0.isEmpty ? nil : root.appendingPathComponent($0).path } ?? root.path
|
||||
let args = Self.fileArguments(filter: filter, target: target)
|
||||
guard let result = await run(args) else { return [] }
|
||||
return result.stdout.split(separator: "\n")
|
||||
.map { RipgrepJSON.relativePath(String($0), root: root.path) }
|
||||
.sorted()
|
||||
}
|
||||
|
||||
func matches(_ query: LineQuery, filter: ScanFilter) async -> [RipgrepMatch] {
|
||||
guard let result = await run(Self.searchArguments(query, filter: filter, target: root.path)) else { return [] }
|
||||
return result.stdout.split(separator: "\n").compactMap { RipgrepJSON.parseLine(String($0)) }
|
||||
}
|
||||
|
||||
static func fileArguments(filter: ScanFilter, target: String) -> [String] {
|
||||
["--files", "--hidden"] + IgnoreRules.ripgrepArguments(files: filter.files, base: filter.base) + ["--", target]
|
||||
}
|
||||
|
||||
static func searchArguments(_ query: LineQuery, filter: ScanFilter, target: String) -> [String] {
|
||||
var args = ["--json"]
|
||||
let needle: String
|
||||
switch query.pattern {
|
||||
case .smartCaseLiteral(let text):
|
||||
args += ["--fixed-strings", "--smart-case"]
|
||||
needle = text
|
||||
case .regex(let pattern):
|
||||
needle = pattern
|
||||
case .word(let text):
|
||||
args += ["--fixed-strings", "--word-regexp"]
|
||||
needle = text
|
||||
}
|
||||
args.append("--hidden")
|
||||
if let max = query.maxPerFile { args += ["--max-count", String(max)] }
|
||||
if let columns = query.maxColumns { args += ["--max-columns", String(columns)] }
|
||||
if let ext = query.fileExtension { args += ["--glob", "*." + ext] }
|
||||
args += IgnoreRules.ripgrepArguments(files: filter.files, base: filter.base)
|
||||
return args + ["-e", needle, "--", target]
|
||||
}
|
||||
|
||||
/// Exit 1 means "nothing found" and 2 means "some files were unreadable"; both keep their output.
|
||||
private func run(_ arguments: [String]) async -> ProcessResult? {
|
||||
do {
|
||||
return try await runner.run(binary.path, arguments: arguments, in: root, environment: nil)
|
||||
} catch {
|
||||
Log.error("search", "ripgrep failed: \(error)")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - walk
|
||||
|
||||
/// The ripgrep fallback: walks the tree in name order, never follows symlinks, and skips
|
||||
/// binary files and files over `maxFileBytes` when searching.
|
||||
struct WalkScanner: ProjectScanning {
|
||||
let root: URL
|
||||
let runner: ProcessRunning
|
||||
var maxFileBytes = FileLimits.maxIndexedFileBytes
|
||||
|
||||
func files(under scope: String?, filter: ScanFilter) async -> [String] {
|
||||
var out: [String] = []
|
||||
await walk(from: scope ?? "", filter: filter) { rel, _ in
|
||||
out.append(rel)
|
||||
return true
|
||||
}
|
||||
return out.sorted()
|
||||
}
|
||||
|
||||
func matches(_ query: LineQuery, filter: ScanFilter) async -> [RipgrepMatch] {
|
||||
guard let matcher = LineMatcher(query.pattern) else { return [] }
|
||||
var out: [RipgrepMatch] = []
|
||||
var filesWithHits = 0
|
||||
await walk(from: "", filter: filter) { rel, url in
|
||||
if let ext = query.fileExtension, (rel as NSString).pathExtension != ext { return true }
|
||||
guard let text = readText(url) else { return true }
|
||||
var hits = 0
|
||||
var lineNumber = 0
|
||||
for line in text.split(separator: "\n", omittingEmptySubsequences: false) {
|
||||
lineNumber += 1
|
||||
guard let offset = matcher.firstByteOffset(in: line) else { continue }
|
||||
out.append(RipgrepMatch(path: root.path + "/" + rel, line: lineNumber, text: String(line), byteOffset: offset))
|
||||
hits += 1
|
||||
if let max = query.maxPerFile, hits >= max { break }
|
||||
}
|
||||
if hits > 0 { filesWithHits += 1 }
|
||||
if let max = query.maxFiles, filesWithHits >= max { return false }
|
||||
return true
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
private func readText(_ url: URL) -> String? {
|
||||
guard let size = (try? url.resourceValues(forKeys: [.fileSizeKey]))?.fileSize, size <= maxFileBytes,
|
||||
let data = try? Data(contentsOf: url), !FileLimits.looksBinary(data) else { return nil }
|
||||
return String(decoding: data, as: UTF8.self)
|
||||
}
|
||||
|
||||
/// Calls `visit` for every file in scope until it returns false.
|
||||
private func walk(from scope: String, filter: ScanFilter, visit: (String, URL) -> Bool) async {
|
||||
let base = Set(filter.base)
|
||||
let excludes = filter.files.exclude.filter { !$0.isEmpty }
|
||||
let gitIgnored = filter.files.followGitignore ? await ignoredByGit() : []
|
||||
|
||||
func skipped(_ rel: String, name: String, isDirectory: Bool) -> Bool {
|
||||
if base.contains(name) { return true }
|
||||
if excludes.contains(where: { IgnoreRules.globMatches($0, path: rel) }) { return true }
|
||||
return gitIgnored.contains(isDirectory ? rel + "/" : rel)
|
||||
}
|
||||
|
||||
var stack: [String] = [scope]
|
||||
while let dir = stack.popLast() {
|
||||
let url = dir.isEmpty ? root : root.appendingPathComponent(dir)
|
||||
var subdirectories: [String] = []
|
||||
for entry in DirectoryListing.entries(of: url) {
|
||||
let rel = PathUtils.join(dir, entry.name)
|
||||
if skipped(rel, name: entry.name, isDirectory: entry.kind == .directory) { continue }
|
||||
switch entry.kind {
|
||||
case .directory: subdirectories.append(rel)
|
||||
case .file: if !visit(rel, entry.url) { return }
|
||||
}
|
||||
}
|
||||
stack += subdirectories.reversed()
|
||||
}
|
||||
}
|
||||
|
||||
/// Untracked paths git ignores, folders with a trailing slash; empty outside a repository.
|
||||
private func ignoredByGit() async -> Set<String> {
|
||||
let args = ["ls-files", "-z", "--others", "--ignored", "--exclude-standard", "--directory"]
|
||||
guard let result = try? await runner.run("git", args, in: root), result.succeeded else { return [] }
|
||||
return Set(result.stdout.split(separator: "\0").map(String.init))
|
||||
}
|
||||
}
|
||||
|
||||
/// Finds the first match in one line and reports its UTF-8 offset, the unit ripgrep uses.
|
||||
private struct LineMatcher {
|
||||
private enum Kind {
|
||||
case literal(String, String.CompareOptions)
|
||||
case regex(NSRegularExpression)
|
||||
}
|
||||
|
||||
private let kind: Kind
|
||||
|
||||
init?(_ pattern: LineQuery.Pattern) {
|
||||
switch pattern {
|
||||
case .smartCaseLiteral(let text):
|
||||
guard !text.isEmpty else { return nil }
|
||||
let caseSensitive = text.contains { $0.isUppercase }
|
||||
kind = .literal(text, caseSensitive ? [.literal] : [.literal, .caseInsensitive])
|
||||
case .regex(let pattern):
|
||||
guard let regex = try? NSRegularExpression(pattern: pattern) else { return nil }
|
||||
kind = .regex(regex)
|
||||
case .word(let text):
|
||||
let escaped = NSRegularExpression.escapedPattern(for: text)
|
||||
guard let regex = try? NSRegularExpression(pattern: "(?<!\\w)" + escaped + "(?!\\w)") else { return nil }
|
||||
kind = .regex(regex)
|
||||
}
|
||||
}
|
||||
|
||||
func firstByteOffset(in line: Substring) -> Int? {
|
||||
let text = String(line)
|
||||
switch kind {
|
||||
case .literal(let needle, let options):
|
||||
guard let range = text.range(of: needle, options: options) else { return nil }
|
||||
return text.utf8.distance(from: text.startIndex, to: range.lowerBound)
|
||||
case .regex(let regex):
|
||||
let whole = NSRange(text.startIndex..., in: text)
|
||||
guard let match = regex.firstMatch(in: text, range: whole),
|
||||
let range = Range(match.range, in: text) else { return nil }
|
||||
return text.utf8.distance(from: text.startIndex, to: range.lowerBound)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
|
||||
public protocol SearchServicing: Sendable {
|
||||
/// False when no ripgrep binary was found; callers then fall back to a walk.
|
||||
func isAvailable() async -> Bool
|
||||
/// Fixed-string, smart-case content search; [] below `SearchLimits.minContentQuery` characters.
|
||||
func searchContent(_ query: String) async -> [ContentGroup]
|
||||
/// Relative paths of every project file, dotfiles included, honouring gitignore and excludes.
|
||||
/// `directory` limits the list to one subtree; paths stay relative to the root.
|
||||
func listFiles(under directory: String?) async -> [String]
|
||||
}
|
||||
|
||||
/// Answers through ripgrep when it can be found, else through a walk with the same filters.
|
||||
public struct RipgrepSearchService: SearchServicing {
|
||||
public let root: URL
|
||||
private let config: ConfigServicing
|
||||
private let runner: ProcessRunning
|
||||
private let locator: ExecutableLocator
|
||||
private let environment: [String: String]
|
||||
|
||||
/// `environment` is read for `RG_BINARY`, which points at a ripgrep outside the search path.
|
||||
public init(root: URL, config: ConfigServicing, runner: ProcessRunning = ProcessRunner(), locator: ExecutableLocator = .standard,
|
||||
environment: [String: String] = ProcessInfo.processInfo.environment) {
|
||||
self.root = root
|
||||
self.config = config
|
||||
self.runner = runner
|
||||
self.locator = locator
|
||||
self.environment = environment
|
||||
}
|
||||
|
||||
public func isAvailable() async -> Bool {
|
||||
ProjectScanner.ripgrep(locator: locator, environment: environment) != nil
|
||||
}
|
||||
|
||||
public func searchContent(_ query: String) async -> [ContentGroup] {
|
||||
guard query.trimmingCharacters(in: .whitespacesAndNewlines).count >= SearchLimits.minContentQuery else { return [] }
|
||||
let search = LineQuery(pattern: .smartCaseLiteral(query), maxPerFile: SearchLimits.maxHitsPerFile,
|
||||
maxColumns: 2000, maxFiles: SearchLimits.maxFiles)
|
||||
var grouper = ContentGrouper(root: root.path)
|
||||
for match in await scanner.matches(search, filter: await filter()) {
|
||||
grouper.add(match)
|
||||
}
|
||||
return grouper.groups
|
||||
}
|
||||
|
||||
public func listFiles(under directory: String?) async -> [String] {
|
||||
if let directory, !directory.isEmpty, !isInsideRoot(directory) { return [] }
|
||||
return await scanner.files(under: directory, filter: await filter())
|
||||
}
|
||||
|
||||
private var scanner: ProjectScanning {
|
||||
ProjectScanner.make(root: root, runner: runner, locator: locator, environment: environment)
|
||||
}
|
||||
|
||||
private func filter() async -> ScanFilter {
|
||||
ScanFilter(base: IgnoreRules.ripgrepBaseIgnore, files: await config.current().files)
|
||||
}
|
||||
|
||||
private func isInsideRoot(_ path: String) -> Bool {
|
||||
let base = root.standardizedFileURL.path
|
||||
let target = root.appendingPathComponent(path).standardizedFileURL.path
|
||||
return target.hasPrefix(base + "/")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user