Repository Public
1import Foundation23public struct PythonPackageInfo: Sendable, Hashable, Codable, Identifiable {4 public enum Provenance: String, Sendable, Codable { case homebrew, system, userSite, venv, managedVenv, pythonOrg, other }5 public var id: String { name.lowercased() }6 public var name: String7 public var version: String8 /// The site-packages directory the distribution is installed in.9 public var location: String10 /// Content of the distribution's INSTALLER file ("pip", "brew", "uv", "conda"…), when present.11 public var installer: String12 public var summary: String13 public var provenance: Provenance14}1516public enum PythonEnvironmentError: Error, LocalizedError, Sendable, Equatable {17 case invalidPackageName(String)18 case noManagedEnvironment19 case failed(String)20 public var errorDescription: String? {21 switch self {22 case .invalidPackageName(let n): "“\(n)” is not a valid package requirement. Use a name such as “pandas” or “pandas==2.2.3”."23 case .noManagedEnvironment: "Create the ORIX Sheet environment first."24 case .failed(let why): why25 }26 }27}2829/// Read-only view of an interpreter's packages, plus the optional managed virtual environment.30/// Listing packages reads installed metadata only. `install` is the ONLY operation of the Python integration that31/// uses the network (pip downloads from PyPI and runs the package's build/installation code): the app must obtain32/// an explicit confirmation from the user before calling it.33public struct PythonEnvironmentManager: Sendable {34 public var interpreter: PythonInterpreter35 public init(interpreter: PythonInterpreter) { self.interpreter = interpreter }3637 public static var managedVenvURL: URL { PythonPaths.managedVenv }38 public static var managedPython: URL { PythonPaths.managedVenv.appendingPathComponent("bin/python3") }39 public static var managedVenvExists: Bool { FileManager.default.isExecutableFile(atPath: managedPython.path) }4041 public func listPackages() async throws -> [PythonPackageInfo] {42 let script = try PythonPaths.resource("packages.py")43 let out = try await CapturedProcess.run(executable: interpreter.executable, arguments: ["-I", "-B", script.path], environment: PythonDiscovery.cleanEnvironment, timeout: 30)44 guard out.status == 0, let line = out.stdout.split(separator: "\n").last,45 let raw = try? JSONSerialization.jsonObject(with: Data(line.utf8)) as? [[String: Any]] else {46 throw PythonEnvironmentError.failed("The package list could not be read: \(out.stderr.suffix(300))")47 }48 return raw.map {49 let location = ($0["location"] as? String) ?? "", installer = ($0["installer"] as? String) ?? ""50 return PythonPackageInfo(name: ($0["name"] as? String) ?? "", version: ($0["version"] as? String) ?? "", location: location, installer: installer,51 summary: ($0["summary"] as? String) ?? "", provenance: Self.provenance(location: location, installer: installer, interpreter: interpreter))52 }53 }5455 static func provenance(location: String, installer: String, interpreter: PythonInterpreter) -> PythonPackageInfo.Provenance {56 let managed = PythonSandbox.canonical(PythonPaths.managedVenv.path)57 if location.hasPrefix(managed + "/") { return .managedVenv }58 if interpreter.isVirtualEnv, !interpreter.prefix.isEmpty, location.hasPrefix(interpreter.prefix + "/") { return .venv }59 if let user = interpreter.userSite, location == PythonSandbox.canonical(user) || location.contains("/Library/Python/") && location.hasPrefix(NSHomeDirectory()) { return .userSite }60 if location.hasPrefix("/opt/homebrew/") || location.contains("/Cellar/") || location.hasPrefix("/usr/local/lib/python") || installer == "brew" { return .homebrew }61 if location.contains("/Xcode") || location.hasPrefix("/Library/Developer/") || location.hasPrefix("/System/") { return .system }62 if location.hasPrefix("/Library/Frameworks/Python.framework") { return .pythonOrg }63 return .other64 }6566 /// Creates ~/Library/Application Support/ORIX Sheet/python/venv with `--system-site-packages` (the base67 /// interpreter's packages stay visible). Works offline: pip comes from the interpreter's bundled ensurepip.68 @discardableResult69 public func createVenv(onOutput: (@Sendable (PythonStream, String) -> Void)? = nil) async throws -> PythonInterpreter {70 let target = PythonPaths.managedVenv71 try PythonPaths.ensureDirectory(target.deletingLastPathComponent())72 if FileManager.default.fileExists(atPath: target.path) { try FileManager.default.removeItem(at: target) }73 let out = try await CapturedProcess.run(executable: interpreter.executable, arguments: ["-I", "-B", "-m", "venv", "--system-site-packages", target.path],74 environment: PythonDiscovery.cleanEnvironment, timeout: 180, onOutput: onOutput)75 guard out.status == 0 else {76 try? FileManager.default.removeItem(at: target)77 throw PythonEnvironmentError.failed("The environment could not be created (exit \(out.status)). \((out.stderr + out.stdout).suffix(400))")78 }79 guard let venv = await PythonDiscovery.probe(path: Self.managedPython.path) else { throw PythonEnvironmentError.failed("The new environment does not start.") }80 return venv81 }8283 public static func removeVenv() throws {84 if FileManager.default.fileExists(atPath: PythonPaths.managedVenv.path) { try FileManager.default.removeItem(at: PythonPaths.managedVenv) }85 }8687 /// A requirement the app is willing to hand to pip: a project name, optional extras and an optional version88 /// constraint. No options, URLs, paths or shell syntax.89 public static func isValidRequirement(_ text: String) -> Bool {90 text.count <= 120 && text.range(of: #"^[A-Za-z0-9]([A-Za-z0-9._-]*[A-Za-z0-9])?(\[[A-Za-z0-9._,-]+\])?((==|>=|<=|~=|!=|>|<)[A-Za-z0-9.*+!_-]+(,(==|>=|<=|~=|!=|>|<)[A-Za-z0-9.*+!_-]+)*)?$"#, options: .regularExpression) != nil91 }9293 /// The exact command `install(package:)` runs, for display in the confirmation dialog.94 public static func installCommand(package: String) -> [String] {95 [managedPython.path, "-I", "-m", "pip", "install", "--disable-pip-version-check", "--no-input", "--", package]96 }9798 /// Installs into the managed environment with pip. USES THE NETWORK and runs third-party installation code,99 /// outside any sandbox. Call only after the user confirmed this exact package.100 public static func install(package: String, timeout: TimeInterval = 900, onOutput: (@Sendable (PythonStream, String) -> Void)? = nil) async throws {101 let name = package.trimmingCharacters(in: .whitespaces)102 guard isValidRequirement(name) else { throw PythonEnvironmentError.invalidPackageName(package) }103 guard managedVenvExists else { throw PythonEnvironmentError.noManagedEnvironment }104 let cmd = installCommand(package: name)105 var env = PythonDiscovery.cleanEnvironment106 env["HOME"] = NSHomeDirectory()107 env["PATH"] = "/usr/bin:/bin:/usr/sbin:/sbin"108 let out = try await CapturedProcess.run(executable: cmd[0], arguments: Array(cmd.dropFirst()), environment: env, workingDirectory: NSTemporaryDirectory(), timeout: timeout, onOutput: onOutput)109 if out.timedOut { throw PythonEnvironmentError.failed("pip did not finish within \(Int(timeout)) s and was stopped.") }110 guard out.status == 0 else { throw PythonEnvironmentError.failed("pip exited with status \(out.status).") }111 }112}113