Debian Codegraph @

strings.go

raw
1 // This file is part of go-properties-orderedmap library.
2 //
3 // SPDX-FileCopyrightText: Arduino s.r.l. and/or its affiliated companies
4 // SPDX-License-Identifier: GPL-2.0-or-later
5
6 package properties
7
8 import (
9 "fmt"
10 "strings"
11 "unicode/utf8"
12 )
13
14 // SplitQuotedString splits a string by spaces and at the same time allows
15 // to use spaces in a single element of the split using quote characters.
16 //
17 // For example the call:
18 //
19 // SplitQuotedString(`This 'is an' "Hello World!" example`, `'"`, false)
20 //
21 // returns the following array:
22 //
23 // []string{"This", "is an", "Hello World!", "example"}
24 //
25 // The quoteChars parameter is a string containing all the characters that
26 // are considered as quote characters. If a quote character is found, the
27 // function will consider the text between the quote character and the next
28 // quote character as a single element of the split.
29 //
30 // The acceptEmptyArguments parameter is a boolean that indicates if the
31 // function should consider empty arguments as valid elements of the split.
32 // If set to false, the function will ignore empty arguments.
33 //
34 // If the function finds an opening quote character and does not find the
35 // closing quote character, it will return an error. In any case, the function
36 // will return the split array up to the point where the error occurred.
37 //
38 // The function does not support escaping of quote characters.
39 //
40 // The function is UTF-8 safe.
41 func SplitQuotedString(src string, quoteChars string, acceptEmptyArguments bool) ([]string, error) {
42 // Make a map of valid quote runes
43 isQuote := map[rune]bool{}
44 for _, c := range quoteChars {
45 isQuote[c] = true
46 }
47
48 result := []string{}
49
50 var escapingChar rune
51 escapedArg := ""
52
53 for current := range strings.SplitSeq(src, " ") {
54 if escapingChar == 0 {
55 first, size := firstRune(current)
56 if !isQuote[first] {
57 if acceptEmptyArguments || len(strings.TrimSpace(current)) > 0 {
58 result = append(result, current)
59 }
60 continue
61 }
62
63 escapingChar = first
64 current = current[size:]
65 escapedArg = ""
66 }
67
68 last, size := lastRune(current)
69 if last != escapingChar {
70 escapedArg += current + " "
71 continue
72 }
73
74 escapedArg += current[:len(current)-size]
75 if acceptEmptyArguments || len(strings.TrimSpace(escapedArg)) > 0 {
76 result = append(result, escapedArg)
77 }
78 escapingChar = 0
79 }
80
81 if escapingChar != 0 {
82 return result, fmt.Errorf("invalid quoting, no closing `%c` char found", escapingChar)
83 }
84
85 return result, nil
86 }
87
88 func firstRune(s string) (rune, int) {
89 if len(s) == 0 || !utf8.ValidString(s) {
90 return 0, 0
91 }
92 return utf8.DecodeRuneInString(s)
93 }
94
95 func lastRune(s string) (rune, int) {
96 if len(s) == 0 || !utf8.ValidString(s) {
97 return 0, 0
98 }
99 return utf8.DecodeLastRuneInString(s)
100 }