Improve shell escaping heuristics #402

Signed-off-by: Alex Mazanov <alexandr.mazanov@gmail.com>
This commit is contained in:
Alex Mazanov 2024-01-04 14:08:56 -05:00
parent 28ef89ff82
commit d81efbc3dc
No known key found for this signature in database
GPG Key ID: FD35C3C7C1D34AB4

View File

@ -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: "'\\''"))\'"
}
}