From b7120f3a58b362aba2212695a269c0753de03bb6 Mon Sep 17 00:00:00 2001 From: Myzel394 <50424412+Myzel394@users.noreply.github.com> Date: Tue, 8 Oct 2024 16:13:26 +0200 Subject: [PATCH] feat(common): Improve string parser --- server/common/parser/strings.go | 21 +++++++++++++++++++++ server/common/parser/strings_test.go | 22 ++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/server/common/parser/strings.go b/server/common/parser/strings.go index 931983f..17aaee0 100644 --- a/server/common/parser/strings.go +++ b/server/common/parser/strings.go @@ -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, diff --git a/server/common/parser/strings_test.go b/server/common/parser/strings_test.go index e82352f..0a05916 100644 --- a/server/common/parser/strings_test.go +++ b/server/common/parser/strings_test.go @@ -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) + } +}