mirror of
https://github.com/ghostty-org/ghostty.git
synced 2026-04-14 11:35:48 +00:00
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.
38 lines
1.3 KiB
Swift
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: #"'"'"'"#) + "'"
|
|
}
|
|
}
|