aboutsummaryrefslogtreecommitdiffstats
path: root/client/go/internal/util/shell_quote.go
blob: f4ee01ea6b82e8b87f0bdfd765f10f35eddd6af4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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()
}