fix(common): Improve formatting

This commit is contained in:
Myzel394 2024-09-21 15:30:34 +02:00
parent 91dff8a7a0
commit dbd82e4939
No known key found for this signature in database
GPG Key ID: DEC4AAB876F73185
2 changed files with 78 additions and 0 deletions

View File

@ -32,6 +32,8 @@ func (f FormatTemplate) Format(
value = strings.TrimRight(value, "\t")
}
value = surroundWithQuotes(value)
return value
}
@ -57,6 +59,45 @@ func (f FormatTemplate) replace(format string, replacement string) FormatTemplat
return FormatTemplate(value)
}
func surroundWithQuotes(s string) string {
value := s
currentIndex := 0
for {
startPosition := strings.Index(value[currentIndex:], "/!'")
if startPosition == -1 {
break
}
startPosition = startPosition + currentIndex + 3
currentIndex = startPosition
endPosition := strings.Index(value[startPosition:], "/!'")
if endPosition == -1 {
break
}
endPosition = endPosition + startPosition
currentIndex = endPosition
innerValue := value[startPosition:endPosition]
if strings.Contains(innerValue, " ") {
value = value[:startPosition-3] + "\"" + innerValue + "\"" + value[endPosition+3:]
} else {
value = value[:startPosition-3] + innerValue + value[endPosition+3:]
}
if endPosition+3 >= len(value) {
break
}
}
return value
}
func getTab(options protocol.FormattingOptions) string {
tabSize := options["tabSize"].(float64)
insertSpace := options["insertSpaces"].(bool)

View File

@ -79,3 +79,40 @@ func TestSimpleExampleWhiteSpaceAtEndShouldNOTTrim(
t.Errorf("Expected %q but got %q", expected, result)
}
}
func TestSurroundWithQuotesExample(
t *testing.T,
) {
template := FormatTemplate("%s /!'%s/!'")
options := protocol.FormattingOptions{
"tabSize": float64(4),
"insertSpaces": false,
"trimTrailingWhitespace": true,
}
result := template.Format(options, "PermitRootLogin", "this is okay")
expected := `PermitRootLogin "this is okay"`
if result != expected {
t.Errorf("Expected %q but got %q", expected, result)
}
}
func TestSurroundWithQuotesButNoSpaceExample(
t *testing.T,
) {
template := FormatTemplate("%s /!'%s/!'")
options := protocol.FormattingOptions{
"tabSize": float64(4),
"insertSpaces": false,
"trimTrailingWhitespace": true,
}
result := template.Format(options, "PermitRootLogin", "yes")
expected := `PermitRootLogin yes`
if result != expected {
t.Errorf("Expected %q but got %q", expected, result)
}
}