Browse Source

feat: Adding CLI arg quoting

Matthias Ladkau 2 years ago
parent
commit
c0eeb12f60
2 changed files with 34 additions and 0 deletions
  1. 16 0
      stringutil/stringutil.go
  2. 18 0
      stringutil/stringutil_test.go

+ 16 - 0
stringutil/stringutil.go

@@ -636,6 +636,22 @@ func GenerateRollingString(seq string, size int) string {
 	return buf.String()
 }
 
+var quoteCLIPattern = regexp.MustCompile(`[^\w@%+=:,./-]`)
+
+func QuoteCLIArgs(args []string) string {
+	l := make([]string, len(args))
+
+	for i, a := range args {
+		if quoteCLIPattern.MatchString(a) {
+			l[i] = "'" + strings.ReplaceAll(a, "'", "'\"'\"'") + "'"
+		} else {
+			l[i] = a
+		}
+	}
+
+	return strings.Join(l, " ")
+}
+
 /*
 ConvertToString tries to convert a given object into a stable string. This
 function can be used to display nested maps.

+ 18 - 0
stringutil/stringutil_test.go

@@ -315,6 +315,24 @@ func TestGenerateRollingString(t *testing.T) {
 	}
 }
 
+func TestQuoteCLIArgs(t *testing.T) {
+
+	if res := QuoteCLIArgs([]string{"-i"}); res != "-i" {
+		t.Error("Unexpected result:", res)
+		return
+	}
+
+	if res := QuoteCLIArgs([]string{"-i test"}); res != "'-i test'" {
+		t.Error("Unexpected result:", res)
+		return
+	}
+
+	if res := QuoteCLIArgs([]string{"-i", "--TEST&test"}); res != "-i '--TEST&test'" {
+		t.Error("Unexpected result:", res)
+		return
+	}
+}
+
 func TestConvertToString(t *testing.T) {
 
 	if res := ConvertToString(""); res != "" {