SPB Git

Repository Public

ShellSupport.swift 9.6 KB 189 lines swift

1import Darwin2import Foundation3import PTYProcess45/// A shell installed on this Mac.6public struct ShellInfo: Sendable, Hashable, Identifiable {7    public var path: String8    public var id: String { path }9    /// `zsh`, `bash`, `fish`…10    public var name: String { (path as NSString).lastPathComponent }11}1213public enum ShellCatalog {14    /// Places where shells installed outside `/etc/shells` usually live.15    static let extraCandidates = ["/opt/homebrew/bin/fish", "/usr/local/bin/fish", "/opt/homebrew/bin/bash", "/usr/local/bin/bash",16                                  "/opt/homebrew/bin/zsh", "/opt/homebrew/bin/nu", "/usr/local/bin/nu",17                                  "/opt/homebrew/bin/pwsh", "/usr/local/bin/pwsh", "/opt/homebrew/bin/elvish", "/opt/homebrew/bin/xonsh"]1819    /// The account's login shell from the user database (not `$SHELL`, which can be stale).20    public static func defaultShell() -> String {21        if let entry = getpwuid(getuid()), let shell = entry.pointee.pw_shell {22            let path = String(cString: shell)23            if FileManager.default.isExecutableFile(atPath: path) { return path }24        }25        return "/bin/zsh"26    }2728    /// Parses the content of `/etc/shells`.29    public static func parseShellsFile(_ text: String) -> [String] {30        text.split(whereSeparator: \.isNewline)31            .map { $0.split(separator: "#", maxSplits: 1, omittingEmptySubsequences: false).first.map(String.init) ?? "" }32            .map { $0.trimmingCharacters(in: .whitespaces) }33            .filter { $0.hasPrefix("/") }34    }3536    /// Shells that exist and are executable: `/etc/shells`, common Homebrew locations and the37    /// account's default shell, without duplicates (symlinks resolved for comparison).38    public static func installedShells(shellsFile: String = "/etc/shells",39                                       isExecutable: (String) -> Bool = { FileManager.default.isExecutableFile(atPath: $0) }) -> [ShellInfo] {40        let listed = (try? String(contentsOfFile: shellsFile, encoding: .utf8)).map(parseShellsFile) ?? []41        var seen = Set<String>()42        var result: [ShellInfo] = []43        for path in [defaultShell()] + listed + extraCandidates where isExecutable(path) {44            let resolved = URL(fileURLWithPath: path).resolvingSymlinksInPath().path45            if seen.insert(resolved).inserted { result.append(ShellInfo(path: path)) }46        }47        return result48    }49}5051/// What to run in a new session.52public enum LaunchRequest: Sendable, Hashable {53    /// Interactive shell (`nil` = default shell), optionally as a login shell.54    case shell(path: String?, login: Bool)55    /// A command line run by the user's shell as `shell -l -i -c line`, so it sees the same56    /// PATH and configuration as if typed at a prompt.57    case commandLine(String, shell: String?)58    /// A program started directly with an explicit argv (no shell involved, nothing to escape).59    case program(executable: String, arguments: [String])60}6162public enum LaunchPlanner {63    /// Variables never inherited from the app's own environment.64    static let strippedPrefixes = ["XPC_", "DYLD_", "__XPC", "OS_ACTIVITY", "MallocStackLogging", "NSUnbufferedIO", "SWIFT_", "CA_", "XCTest", "__XCODE", "LLVM_"]65    static let strippedNames: Set<String> = ["TERM", "COLORTERM", "TERM_PROGRAM", "TERM_PROGRAM_VERSION", "TERM_SESSION_ID",66                                             "COLUMNS", "LINES", "OLDPWD", "PWD", "SHLVL", "_", "TERMCAP"]6768    /// Environment for a child: the app's environment minus debugging/terminal leftovers, plus69    /// the variables every terminal is expected to set.70    public static func environment(base: [String: String] = ProcessInfo.processInfo.environment, shell: String,71                                   appVersion: String, extra: [String: String] = [:]) -> [String: String] {72        var env = base.filter { key, _ in73            !strippedNames.contains(key) && !strippedPrefixes.contains { key.hasPrefix($0) }74        }75        env["TERM"] = "xterm-256color"76        env["COLORTERM"] = "truecolor"77        env["TERM_PROGRAM"] = "SPTerm"78        env["TERM_PROGRAM_VERSION"] = appVersion79        env["SHELL"] = shell80        if env["HOME"] == nil { env["HOME"] = NSHomeDirectory() }81        if env["USER"] == nil { env["USER"] = NSUserName() }82        if env["LOGNAME"] == nil { env["LOGNAME"] = NSUserName() }83        if env["PATH"] == nil { env["PATH"] = "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" }84        if env["LANG"] == nil, env["LC_ALL"] == nil, env["LC_CTYPE"] == nil { env["LANG"] = defaultLang() }85        for (key, value) in extra { env[key] = value }86        return env87    }8889    /// `fr_CA.UTF-8` style value from the user's locale, falling back to `en_US.UTF-8`.90    static func defaultLang(locale: Locale = .current) -> String {91        if let language = locale.language.languageCode?.identifier, let region = locale.region?.identifier,92           language.count == 2, region.count == 2 {93            return "\(language)_\(region).UTF-8"94        }95        return "en_US.UTF-8"96    }9798    /// Turns a request into the exact process to spawn.99    public static func plan(_ request: LaunchRequest, workingDirectory: String?, columns: Int, rows: Int,100                            appVersion: String, baseEnvironment: [String: String] = ProcessInfo.processInfo.environment,101                            extraEnvironment: [String: String] = [:],102                            directoryExists: (String) -> Bool = { path in103                                var isDir: ObjCBool = false104                                return FileManager.default.fileExists(atPath: path, isDirectory: &isDir) && isDir.boolValue105                            }) -> PTYLaunchConfiguration {106        let defaultShell = ShellCatalog.defaultShell()107        let executable: String108        let arguments: [String]109        let shellForEnvironment: String110        switch request {111        case .shell(let path, let login):112            executable = path ?? defaultShell113            shellForEnvironment = executable114            let name = (executable as NSString).lastPathComponent115            // A leading "-" in argv[0] is the portable way to ask for a login shell.116            arguments = [login ? "-" + name : name]117        case .commandLine(let line, let shell):118            executable = shell ?? defaultShell119            shellForEnvironment = executable120            arguments = [(executable as NSString).lastPathComponent, "-l", "-i", "-c", line]121        case .program(let path, let args):122            executable = path123            shellForEnvironment = defaultShell124            arguments = [(path as NSString).lastPathComponent] + args125        }126        // A directory that no longer exists (restored workspace, unmounted volume) must not127        // prevent the session from starting.128        let home = baseEnvironment["HOME"] ?? NSHomeDirectory()129        let cwd = workingDirectory.flatMap { directoryExists($0) ? $0 : nil } ?? home130        return PTYLaunchConfiguration(131            executable: executable, arguments: arguments,132            environment: environment(base: baseEnvironment, shell: shellForEnvironment, appVersion: appVersion, extra: extraEnvironment),133            workingDirectory: cwd, columns: UInt16(clamping: max(columns, 2)), rows: UInt16(clamping: max(rows, 1)))134    }135}136137public enum ShellEscaping {138    /// Escapes a file path the way Terminal does when a file is dropped: every character that is139    /// special to a POSIX shell is backslash-escaped, so the result works at a prompt and inside140    /// most programs. Newlines cannot be backslash-escaped and switch to `$'…'` quoting.141    public static func escapePath(_ path: String) -> String {142        if path.isEmpty { return "''" }143        if path.unicodeScalars.contains(where: { $0.value < 0x20 || $0.value == 0x7f }) {144            var quoted = "$'"145            for scalar in path.unicodeScalars {146                switch scalar {147                case "\n": quoted += "\\n"148                case "\r": quoted += "\\r"149                case "\t": quoted += "\\t"150                case "'": quoted += "\\'"151                case "\\": quoted += "\\\\"152                default:153                    if scalar.value < 0x20 || scalar.value == 0x7f { quoted += String(format: "\\x%02x", scalar.value) }154                    else { quoted.unicodeScalars.append(scalar) }155                }156            }157            return quoted + "'"158        }159        let special = Set(" \t!\"#$&'()*;<>?[\\]^`{|}~=%")160        var result = ""161        for character in path {162            if special.contains(character) { result.append("\\") }163            result.append(character)164        }165        return result166    }167168    /// Several dropped files → one space-separated, escaped string with a trailing space.169    public static func escapePaths(_ paths: [String]) -> String {170        paths.map(escapePath).joined(separator: " ") + (paths.isEmpty ? "" : " ")171    }172}173174/// Extracts the path from an OSC 7 working-directory report (`file://host/path`).175public enum WorkingDirectoryReport {176    public static func path(from report: String) -> String? {177        if report.hasPrefix("/") { return report }178        guard let url = URL(string: report), url.scheme == "file" else { return nil }179        let path = url.path(percentEncoded: false)180        return path.isEmpty ? nil : path181    }182183    /// Host named in the report, when it is not this machine.184    public static func remoteHost(from report: String, localHostNames: Set<String>) -> String? {185        guard let url = URL(string: report), url.scheme == "file", let host = url.host(), !host.isEmpty else { return nil }186        return localHostNames.contains(host.lowercased()) || host == "localhost" ? nil : host187    }188}189
Files main
Menu

Theme