// Code Custodian File ID: 8F3A7B2C-9E4D-4A1B-8C6D-5E7F9A0B1C2D // // ScriptExecution.swift // StreamlineFoundation // // Created by David Higgins on 11/7/26. // import Foundation // MARK: - Swift Script Execution Engine /// Executes a Swift script string and returns the merged output and exit code. /// - Parameters: /// - script: The unescaped Swift script source code. /// - arguments: CLI parameters passed to the script. /// - workingDirectory: Optional working directory for execution. /// - autoLinkSharedBinaries: If true, automatically injects framework search paths from SHARED_BINARIES/FACTORY_HOME. /// - Returns: A tuple containing the merged stdout/stderr output and the process exit code. @discardableResult public func runSwift( script: String, arguments: [String] = [], workingDirectory: String? = nil, autoLinkSharedBinaries: Bool = true ) -> (output: String, exitCode: Int32) { // Create a unique temporary file for the script let tempDir = FileManager.default.temporaryDirectory let scriptFileName = "\(UUID().uuidString).swift" let scriptURL = tempDir.appendingPathComponent(scriptFileName) // Ensure cleanup via defer defer { try? FileManager.default.removeItem(at: scriptURL) } // Write script atomically do { try script.write(to: scriptURL, atomically: true, encoding: .utf8) } catch { return ("Failed to write Swift script to temporary file: \(error.localizedDescription)", -1) } // Build the command arguments for swift var swiftArgs: [String] = [] // Add framework search paths if autoLinkSharedBinaries is enabled if autoLinkSharedBinaries { let sharedBinariesPath = resolveSharedBinariesPath() swiftArgs.append("-F") swiftArgs.append(sharedBinariesPath) swiftArgs.append("-Xlinker") swiftArgs.append("-rpath") swiftArgs.append("-Xlinker") swiftArgs.append(sharedBinariesPath) } // Add the script path swiftArgs.append(scriptURL.path) // Add user arguments (safely quoted for shell) swiftArgs.append(contentsOf: arguments) // Build the full command for zsh login shell let command = buildShellCommand(executable: "/usr/bin/swift", arguments: swiftArgs) // Execute via Process with merged stdout/stderr return executeWithMergedOutput(command: command, workingDirectory: workingDirectory) } /// Executes a Python script string and returns the merged output and exit code. /// - Parameters: /// - script: The unescaped Python script source code. /// - arguments: CLI parameters passed to the script. /// - workingDirectory: Optional working directory for execution. /// - Returns: A tuple containing the merged stdout/stderr output and the process exit code. @discardableResult public func runPython( script: String, arguments: [String] = [], workingDirectory: String? = nil ) -> (output: String, exitCode: Int32) { // Create a unique temporary file for the script let tempDir = FileManager.default.temporaryDirectory let scriptFileName = "\(UUID().uuidString).py" let scriptURL = tempDir.appendingPathComponent(scriptFileName) // Ensure cleanup via defer defer { try? FileManager.default.removeItem(at: scriptURL) } // Write script atomically do { try script.write(to: scriptURL, atomically: true, encoding: .utf8) } catch { return ("Failed to write Python script to temporary file: \(error.localizedDescription)", -1) } // Build the command: source ~/.factory_init.zsh if it exists, then run python3 let factoryInitPath = (FileManager.default.homeDirectoryForCurrentUser.path as NSString).appendingPathComponent(".factory_init.zsh") let sourceInit = FileManager.default.fileExists(atPath: factoryInitPath) ? "source \"\(factoryInitPath)\" && " : "" let pythonCommand = "\(sourceInit)python3 \"\(scriptURL.path)\"" // Add arguments safely quoted let quotedArgs = arguments.map { "\"\($0.replacingOccurrences(of: "\"", with: "\\\""))\"" }.joined(separator: " ") let fullCommand = quotedArgs.isEmpty ? pythonCommand : "\(pythonCommand) \(quotedArgs)" // Execute via zsh login shell with merged stdout/stderr return executeWithMergedOutput(command: fullCommand, workingDirectory: workingDirectory) } // MARK: - Private Helpers /// Resolves the shared binaries path from environment variables with fallbacks. private func resolveSharedBinariesPath() -> String { // 1. Check SHARED_BINARIES env var if let sharedBinaries = ProcessInfo.processInfo.environment["SHARED_BINARIES"], !sharedBinaries.isEmpty { return sharedBinaries } // 2. Check FACTORY_HOME + /xcode/SharedBinaries if let factoryHome = ProcessInfo.processInfo.environment["FACTORY_HOME"], !factoryHome.isEmpty { return (factoryHome as NSString).appendingPathComponent("xcode/SharedBinaries") } // 3. Fallback to ~/warezfactory/xcode/SharedBinaries let homeDir = FileManager.default.homeDirectoryForCurrentUser.path return (homeDir as NSString).appendingPathComponent("warezfactory/xcode/SharedBinaries") } /// Builds a shell command string for execution via zsh -l -c. private func buildShellCommand(executable: String, arguments: [String]) -> String { let quotedArgs = arguments.map { arg -> String in // Escape double quotes and wrap in double quotes let escaped = arg.replacingOccurrences(of: "\"", with: "\\\"") return "\"\(escaped)\"" }.joined(separator: " ") return "\(executable) \(quotedArgs)" } /// Executes a command string via /bin/zsh -l -c with merged stdout/stderr. private func executeWithMergedOutput(command: String, workingDirectory: String?) -> (output: String, exitCode: Int32) { let task = Process() task.executableURL = URL(filePath: "/bin/zsh") task.arguments = ["-l", "-c", command] if let workingDirectory = workingDirectory { task.currentDirectoryURL = URL(filePath: workingDirectory) } let pipe = Pipe() task.standardOutput = pipe task.standardError = pipe // Merge stderr into stdout for chronological interleaving do { try task.run() let data = pipe.fileHandleForReading.readDataToEndOfFile() task.waitUntilExit() let output = String(data: data, encoding: .utf8) ?? "" return (output, task.terminationStatus) } catch { return ("Failed to launch process: \(error.localizedDescription)", -1) } }