xtool.git
Publicgit clone https://git.maproj.org/xtool.gitxtool.git / Sources / PackLib / ToolRegistry.swift
ToolRegistry.swift47 lines · 1.4 KiBRaw
| 1 | import Foundation |
| 2 | import Subprocess |
| 3 | |
| 4 | package enum ToolRegistry { |
| 5 | package enum Errors: Error, CustomStringConvertible { |
| 6 | case toolNotFound(String) |
| 7 | |
| 8 | package var description: String { |
| 9 | switch self { |
| 10 | case .toolNotFound(let tool): |
| 11 | "Could not find executable '\(tool)' in PATH" |
| 12 | } |
| 13 | } |
| 14 | } |
| 15 | |
| 16 | private static let cache = Cache() |
| 17 | |
| 18 | /// Obtain the full path to a tool in the user's `PATH`. |
| 19 | /// |
| 20 | /// - Throws: `Errors.toolNotFound` if the tool could not be located. |
| 21 | package static func locate(_ tool: String) async throws -> URL { |
| 22 | try await cache.locate(tool: tool) |
| 23 | } |
| 24 | |
| 25 | private actor Cache { |
| 26 | private var cache: [String: Task<URL, Error>] = [:] |
| 27 | |
| 28 | private func _locate(tool: String) async throws -> URL { |
| 29 | guard let path = try? await Executable.name(tool).resolveExecutablePath(in: .inherit), |
| 30 | let url = URL(filePath: path) |
| 31 | else { throw Errors.toolNotFound(tool) } |
| 32 | return url |
| 33 | } |
| 34 | |
| 35 | func locate(tool: String) async throws -> URL { |
| 36 | let task: Task<URL, Error> |
| 37 | if let cached = cache[tool] { |
| 38 | task = cached |
| 39 | } else { |
| 40 | task = Task { try await _locate(tool: tool) } |
| 41 | cache[tool] = task |
| 42 | } |
| 43 | |
| 44 | return try await task.value |
| 45 | } |
| 46 | } |
| 47 | } |