-
Notifications
You must be signed in to change notification settings - Fork 41
/
expand.go
257 lines (217 loc) · 6.55 KB
/
expand.go
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
// Copyright (c) 2017-2018 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package config
import (
"bytes"
"fmt"
"io/ioutil"
"strings"
"golang.org/x/text/transform"
)
const (
_envSeparator = ":"
_emptyDefault = `""`
)
// A LookupFunc behaves like os.LookupEnv: it uses the supplied string as a
// key into some key-value store and returns the value and whether the key was
// present.
type LookupFunc = func(string) (string, bool)
func expandVariables(f LookupFunc, buf *bytes.Buffer) (*bytes.Buffer, error) {
if f == nil {
return buf, nil
}
exp, err := ioutil.ReadAll(transform.NewReader(buf, newExpandTransformer(f)))
if err != nil {
return nil, fmt.Errorf("couldn't expand environment: %v", err)
}
return bytes.NewBuffer(exp), nil
}
// Given a function with the same signature as os.LookupEnv, return a function
// that expands expressions of the form ${ENV_VAR:default_value}.
func replace(lookUp LookupFunc) func(in string) (string, error) {
return func(in string) (string, error) {
sep := strings.Index(in, _envSeparator)
var key string
var def string
if sep == -1 {
// separator missing - everything is the key ${KEY}
key = in
} else {
// ${KEY:DEFAULT}
key = in[:sep]
def = in[sep+1:]
}
if envVal, ok := lookUp(key); ok {
return envVal, nil
}
if def == "" {
return "", fmt.Errorf(`default is empty for %q (use "" for empty string)`, key)
} else if def == _emptyDefault {
return "", nil
}
return def, nil
}
}
// expandTransformer implements transform.Transformer
type expandTransformer struct {
transform.NopResetter
expand func(string) (string, error)
}
func newExpandTransformer(lookup LookupFunc) *expandTransformer {
return &expandTransformer{expand: replace(lookup)}
}
// First char of shell variable may be [a-zA-Z_]
func isShellNameFirstChar(c byte) bool {
return c == '_' ||
(c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z')
}
// Char's after the first of shell variable may be [a-zA-Z0-9_]
func isShellNameChar(c byte) bool {
return c == '_' ||
(c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9')
}
// bytesIndexCFunc returns the index of the byte for which the
// complement of the supplied function is true
func bytesIndexCFunc(buf []byte, f func(b byte) bool) int {
for i, b := range buf {
if !f(b) {
return i
}
}
return -1
}
// Transform expands shell-like sequences like $foo and ${foo} using
// the configured expand function. The sequence '$$' is replaced with
// a literal '$'.
func (e *expandTransformer) Transform(dst, src []byte, atEOF bool) (int, int, error) {
var srcPos int
var dstPos int
for srcPos < len(src) {
if dstPos == len(dst) {
return dstPos, srcPos, transform.ErrShortDst
}
end := bytes.IndexByte(src[srcPos:], '$')
if end == -1 {
// src does not contain '$', copy into dst
cnt := copy(dst[dstPos:], src[srcPos:])
srcPos += cnt
dstPos += cnt
continue
} else if end > 0 {
// copy chars preceding '$' from src to dst
cnt := copy(dst[dstPos:], src[srcPos:srcPos+end])
srcPos += cnt
dstPos += cnt
if dstPos == len(dst) {
return dstPos, srcPos, transform.ErrShortDst
}
}
// src[srcPos] now points to '$', dstPos < len(dst)
// If we're at the end of src, but we found a starting
// token, return ErrShortSrc, unless we're also at EOF,
// in which case just copy it dst.
if srcPos+1 == len(src) {
if atEOF {
dst[dstPos] = src[srcPos]
srcPos++
dstPos++
continue
}
return dstPos, srcPos, transform.ErrShortSrc
}
// At this point we know that src[srcPos+1] is populated.
// If this token sequence represents the special '$$'
// sequence, emit a '$' into dst.
if src[srcPos+1] == '$' {
dst[dstPos] = src[srcPos]
srcPos += 2
dstPos++
continue
}
var token []byte
var tokenEnd int
// Start of bracketed token ${foo}
if src[srcPos+1] == '{' {
end := bytes.IndexByte(src[srcPos+2:], '}')
if end == -1 {
if atEOF {
// No closing bracket and we're at
// EOF, so it's not a valid bracket
// expression.
if len(dst[dstPos:]) <
len(src[srcPos:]) {
return dstPos, srcPos,
transform.ErrShortDst
}
cnt := copy(dst[dstPos:], src[srcPos:])
srcPos += cnt
dstPos += cnt
continue
}
// Otherwise, we need more bytes in src
return dstPos, srcPos, transform.ErrShortSrc
}
// Set tokenEnd so it points to the byte
// immediately after the closing '}'
tokenEnd = end + srcPos + 3
token = src[srcPos+2 : tokenEnd-1]
} else { // Else start of non-bracketed token $foo
if !isShellNameFirstChar(src[srcPos+1]) {
// If it doesn't conform to the naming
// rules for shell variables, do not
// try to expand, just copy to dst.
dst[dstPos] = src[srcPos]
srcPos++
dstPos++
continue
}
end := bytesIndexCFunc(src[srcPos+2:], isShellNameChar)
if end == -1 {
// Reached the end of src without finding
// end of shell variable
if !atEOF {
// We need more bytes in src
return dstPos, srcPos,
transform.ErrShortSrc
}
tokenEnd = len(src)
} else {
// Set tokenEnd so it points to the byte
// immediately after the token
tokenEnd = end + srcPos + 2
}
token = src[srcPos+1 : tokenEnd]
}
replacement, err := e.expand(string(token))
if err != nil {
return dstPos, srcPos, err
}
if len(dst[dstPos:]) < len(replacement) {
return dstPos, srcPos, transform.ErrShortDst
}
cnt := copy(dst[dstPos:], replacement)
srcPos = tokenEnd
dstPos += cnt
}
return dstPos, srcPos, nil
}