Skip to content

Commit 0e7dbd7

Browse files
committed
Parse speech marks when splitting
Signed-off-by: Adam Fowler <adamfowler71@gmail.com>
1 parent b2ce4cd commit 0e7dbd7

File tree

1 file changed

+46
-1
lines changed

1 file changed

+46
-1
lines changed

Sources/ValkeyCLI/ValkeyCLI.swift

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,13 +33,15 @@ struct App {
3333
print("Connecting to \(host):\(port)")
3434
let valkeyClient = ValkeyClient(.hostname(host, port: port), logger: Logger(label: "ValkeyCLI"))
3535
async let _ = valkeyClient.run()
36+
3637
while true {
3738
print("> ", terminator: "")
3839
guard let input = readLine() else {
3940
print("")
4041
return
4142
}
42-
let split = input.split(separator: " ")
43+
let split = input.splitWithSpeechMarks(separator: " ")
44+
print(split)
4345
guard let commandName = split.first else { continue }
4446
let command = ValkeyRawCommand(String(commandName), parameters: split.dropFirst().map { String($0) })
4547
do {
@@ -70,6 +72,49 @@ struct App {
7072
}
7173
}
7274

75+
extension StringProtocol {
76+
func splitWithSpeechMarks(separator: Character, speechMarks: Character = "\"") -> [Self.SubSequence] {
77+
var split: [Self.SubSequence] = []
78+
var position = self.startIndex
79+
var prevPosition = position
80+
var insideSpeechMarks = false
81+
while position != self.endIndex {
82+
if self[position] == separator, insideSpeechMarks == false {
83+
if prevPosition != position {
84+
split.append(self[prevPosition..<position])
85+
}
86+
position = self.index(after: position)
87+
prevPosition = position
88+
continue
89+
}
90+
if self[position] == speechMarks {
91+
if !insideSpeechMarks {
92+
insideSpeechMarks = true
93+
// we also consider speech marks as a separator
94+
if position != prevPosition {
95+
split.append(self[prevPosition..<position])
96+
}
97+
position = self.index(after: position)
98+
prevPosition = position
99+
continue
100+
} else {
101+
insideSpeechMarks = false
102+
// we also consider speech marks as a separator
103+
split.append(self[prevPosition..<position])
104+
position = self.index(after: position)
105+
prevPosition = position
106+
continue
107+
}
108+
}
109+
position = self.index(after: position)
110+
}
111+
if prevPosition != position {
112+
split.append(self[prevPosition..<position])
113+
}
114+
return split
115+
}
116+
}
117+
73118
/// Wrapper for Valkey command that returns the response as a `RESPToken`
74119
@usableFromInline
75120
struct ValkeyRawCommand: ValkeyCommand {

0 commit comments

Comments
 (0)