Smarter shell quoting #366

Signed-off-by: Alex Mazanov <alexandr.mazanov@gmail.com>
This commit is contained in:
Alex Mazanov 2024-01-01 09:15:19 -05:00
parent 10e6e8eed0
commit 18b1400c65
No known key found for this signature in database
GPG Key ID: FD35C3C7C1D34AB4
2 changed files with 18 additions and 1 deletions

View File

@ -149,7 +149,7 @@ struct MenuLineParameters: Codable {
guard let param = params[key] else { continue }
out.append(param.escaped())
}
return out.map { "'\($0)'" }
return out.map { $0.quoteIfNeeded() }
}
var terminal: Bool {

View File

@ -31,3 +31,20 @@ extension String {
return encodedString
}
}
extension String {
var isEnclosedInQuotes: Bool {
let regex = #"^(?:'.*'|".*")$"#
return range(of: regex, options: .regularExpression) != nil
}
var needsShellQuoting: Bool {
let specialCharacters = " \t\n\"'`$\\|&;()<>[]*?{}!^~#%"
return rangeOfCharacter(from: CharacterSet(charactersIn: specialCharacters)) != nil
}
func quoteIfNeeded() -> String {
guard needsShellQuoting else { return self }
return isEnclosedInQuotes ? self : "\'\(self)\'"
}
}