aboutsummaryrefslogtreecommitdiffstats
path: root/client/go/internal/util/shell_quote.go
diff options
context:
space:
mode:
Diffstat (limited to 'client/go/internal/util/shell_quote.go')
-rw-r--r--client/go/internal/util/shell_quote.go68
1 files changed, 68 insertions, 0 deletions
diff --git a/client/go/internal/util/shell_quote.go b/client/go/internal/util/shell_quote.go
new file mode 100644
index 00000000000..f4ee01ea6b8
--- /dev/null
+++ b/client/go/internal/util/shell_quote.go
@@ -0,0 +1,68 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+// load default environment variables (from $VESPA_HOME/conf/vespa/default-env.txt)
+// Author: arnej
+
+package util
+
+import (
+ "bytes"
+)
+
+func needQuoting(s string) bool {
+ for _, ch := range s {
+ switch {
+ case (ch >= 'A' && ch <= 'Z'):
+ case (ch >= 'a' && ch <= 'z'):
+ case (ch >= '0' && ch <= '9'):
+ case ch == '-':
+ case ch == '_':
+ case ch == '.':
+ case ch == ':':
+ case ch == '/':
+ // all above: nop
+ default:
+ return true
+ }
+ }
+ return false
+}
+
+func quote(s string, t *bytes.Buffer) {
+ const singleQuote = '\''
+ if !needQuoting(s) {
+ t.WriteString(s)
+ return
+ }
+ t.WriteByte(singleQuote)
+ for _, ch := range s {
+ switch {
+ case ch == '\'' || ch == '\\':
+ t.WriteByte(singleQuote)
+ t.WriteByte('\\')
+ t.WriteByte(byte(ch))
+ t.WriteByte(singleQuote)
+ case ch < 32 || ch > 127:
+ t.WriteByte('?')
+ default:
+ t.WriteByte(byte(ch))
+ }
+ }
+ t.WriteByte(singleQuote)
+}
+
+func ShellQuoteArgs(args ...string) string {
+ var buf bytes.Buffer
+ for idx, s := range args {
+ if idx > 0 {
+ buf.WriteByte(' ')
+ }
+ quote(s, &buf)
+ }
+ return buf.String()
+}
+
+func ShellQuote(s string) string {
+ var buf bytes.Buffer
+ quote(s, &buf)
+ return buf.String()
+}