From d81efbc3dc7d24df6c4a2c83e827571375796ff5 Mon Sep 17 00:00:00 2001 From: Alex Mazanov Date: Thu, 4 Jan 2024 14:08:56 -0500 Subject: [PATCH] Improve shell escaping heuristics #402 Signed-off-by: Alex Mazanov --- SwiftBar/Utility/String+Escaped.swift | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/SwiftBar/Utility/String+Escaped.swift b/SwiftBar/Utility/String+Escaped.swift index e0b2463..2ffc371 100644 --- a/SwiftBar/Utility/String+Escaped.swift +++ b/SwiftBar/Utility/String+Escaped.swift @@ -34,17 +34,23 @@ extension String { extension String { var isEnclosedInQuotes: Bool { - let regex = #"^(?:'.*'|".*")$"# - return range(of: regex, options: .regularExpression) != nil + hasPrefix("'") && hasSuffix("'") } var needsShellQuoting: Bool { let specialCharacters = " \t\n\"'`$\\|&;()<>[]*?{}!^~#%" + let shellOperators = ["&&", "||", ";", "|", "<", ">"] + + // Check if the string is exactly a logical operator + if shellOperators.contains(self) { + return false + } + return rangeOfCharacter(from: CharacterSet(charactersIn: specialCharacters)) != nil } func quoteIfNeeded() -> String { guard needsShellQuoting else { return self } - return isEnclosedInQuotes ? self : "\'\(self)\'" + return isEnclosedInQuotes ? self : "\'\(replacingOccurrences(of: "'", with: "'\\''"))\'" } }