From 2388f309d80c360c285224ec92aac3ddb61894c8 Mon Sep 17 00:00:00 2001 From: Lykin <137850705+tiny-craft@users.noreply.github.com> Date: Mon, 2 Sep 2024 18:50:51 +0800 Subject: [PATCH] fix: parse cmd error with single quotes --- backend/utils/string/any_convert.go | 37 ++++++++++++++++++----------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/backend/utils/string/any_convert.go b/backend/utils/string/any_convert.go index 222e33e..e4263ec 100644 --- a/backend/utils/string/any_convert.go +++ b/backend/utils/string/any_convert.go @@ -135,29 +135,38 @@ func SplitCmd(cmd string) []string { var result []string var curStr strings.Builder var preChar int32 - inQuotes := false + var quotesChar int32 - for _, char := range []rune(cmd) { - if char == '"' && preChar != '\\' { - inQuotes = !inQuotes - } else if char == ' ' && !inQuotes { - if curStr.Len() > 0 { - if part, e := strconv.Unquote(`"` + curStr.String() + `"`); e == nil { - result = append(result, part) - } - curStr.Reset() + cmdRune := []rune(cmd) + for _, char := range cmdRune { + if (char == '"' || char == '\'') && preChar != '\\' && (quotesChar == 0 || quotesChar == char) { + if quotesChar != 0 { + quotesChar = 0 + } else { + quotesChar = char } + } else if char == ' ' && quotesChar == 0 { + result = append(result, curStr.String()) + curStr.Reset() } else { curStr.WriteRune(char) } preChar = char } + result = append(result, curStr.String()) - if curStr.Len() > 0 { - if part, e := strconv.Unquote(`"` + curStr.String() + `"`); e == nil { - result = append(result, part) + result = sliceutil.FilterMap(result, func(i int) (string, bool) { + var part = strings.TrimSpace(result[i]) + if len(part) <= 0 { + return "", false } - } + if strings.Contains(part, "\\") { + if unquotePart, e := strconv.Unquote(`"` + part + `"`); e == nil { + return unquotePart, true + } + } + return part, true + }) return result }