feat(common): Improve string parser

This commit is contained in:
Myzel394 2024-10-08 16:13:26 +02:00
parent 41239654c8
commit b7120f3a58
No known key found for this signature in database
GPG Key ID: ED20A1D1D423AF3F
2 changed files with 43 additions and 0 deletions

View File

@ -1,13 +1,17 @@
package parser
import "strings"
type ParseFeatures struct {
ParseDoubleQuotes bool
ParseEscapedCharacters bool
Replacements *map[string]string
}
var FullFeatures = ParseFeatures{
ParseDoubleQuotes: true,
ParseEscapedCharacters: true,
Replacements: &map[string]string{},
}
type ParsedString struct {
@ -21,6 +25,10 @@ func ParseRawString(
) ParsedString {
value := raw
if len(*features.Replacements) > 0 {
value = ParseReplacements(value, *features.Replacements)
}
// Parse double quotes
if features.ParseDoubleQuotes {
value = ParseDoubleQuotes(value)
@ -85,6 +93,19 @@ func ParseEscapedCharacters(
return value
}
func ParseReplacements(
raw string,
replacements map[string]string,
) string {
value := raw
for key, replacement := range replacements {
value = strings.ReplaceAll(value, key, replacement)
}
return value
}
func modifyString(
input string,
start int,

View File

@ -165,3 +165,25 @@ func TestStringsIncompleteQuotes3FullFeatures(
t.Errorf("Expected %v, got %v", expected, actual)
}
}
func TestStringsReplacements(
t *testing.T,
) {
input := `Hello\\040World`
expected := ParsedString{
Raw: input,
Value: `Hello World`,
}
actual := ParseRawString(input, ParseFeatures{
ParseDoubleQuotes: true,
ParseEscapedCharacters: true,
Replacements: &map[string]string{
`\\040`: " ",
},
})
if !(cmp.Equal(expected, actual)) {
t.Errorf("Expected %v, got %v", expected, actual)
}
}