Files
ghostty/macos/Sources/Helpers/Extensions/String+Extension.swift
Jon Parise 1ff0dd821f macos: quote input strings used for shell commands
When we're building an input string that's explicitly meant to be used
as a shell command, quote (escape) it using the same logic as Python's
shlex.quote function.

This specifically addresses issues we've seen when open(1)'ing Ghostty
with filename arguments that contain spaces.
2026-02-05 09:21:37 -05:00

38 lines
1.3 KiB
Swift

extension String {
func truncate(length: Int, trailing: String = "") -> String {
let maxLength = length - trailing.count
guard maxLength > 0, !self.isEmpty, self.count > length else {
return self
}
return self.prefix(maxLength) + trailing
}
#if canImport(AppKit)
func temporaryFile(_ filename: String = "temp") -> URL {
let url = FileManager.default.temporaryDirectory
.appendingPathComponent(filename)
.appendingPathExtension("txt")
let string = self
try? string.write(to: url, atomically: true, encoding: .utf8)
return url
}
/// Returns the path with the home directory abbreviated as ~.
var abbreviatedPath: String {
let home = FileManager.default.homeDirectoryForCurrentUser.path
if hasPrefix(home) {
return "~" + dropFirst(home.count)
}
return self
}
#endif
private static let shellUnsafe = /[^\w@%+=:,.\/-]/
/// Returns a shell-escaped version of the string, like Python's shlex.quote.
func shellQuoted() -> String {
guard self.isEmpty || self.contains(Self.shellUnsafe) else { return self };
return "'" + self.replacingOccurrences(of: "'", with: #"'"'"'"#) + "'"
}
}