diff options
author | Arne Juul <arnej@yahooinc.com> | 2023-03-02 20:00:11 +0000 |
---|---|---|
committer | Arne Juul <arnej@yahooinc.com> | 2023-03-02 20:05:43 +0000 |
commit | 66d685830373c716fdf740c3373706056b93ad65 (patch) | |
tree | 159ea158fd641aeb19d97f1010d2af4278ba34c0 /client/go/internal/util/shell_quote.go | |
parent | e8843502782cf63a490fe9cd45c43329d509b0f5 (diff) |
use common shell quoting utilityarnej/use-our-shell-quote
* only suited for printable ascii
* always single-quotes if quoting needed
* may quote more than strictly necessary
Diffstat (limited to 'client/go/internal/util/shell_quote.go')
-rw-r--r-- | client/go/internal/util/shell_quote.go | 68 |
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() +} |