-
Notifications
You must be signed in to change notification settings - Fork 0
/
expand.go
60 lines (57 loc) · 1.19 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
// expand variable
// https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html#Shell-Parameter-Expansion
// currently only supports ${parameter%word} and ${parameter:-word}, you can implement others here
package main
import (
"fmt"
"bytes"
"os"
)
func expandVar(b []byte, args map[string]string) []byte {
b = b[2:len(b)-1]
var param []byte
for i, v := range b {
switch v {
case ':':
switch b[i+1] {
case '-':
word := b[i+2:]
if args == nil {
return word
}
if val, ok := args[string(param)]; !ok {
return word
} else {
return []byte(val)
}
case '=','?','+':
fmt.Printf("not implemented yet %s\n", b)
os.Exit(1)
default:
// offset:length
fmt.Printf("not implemented %s\n", b)
os.Exit(1)
}
case '%':
if b[i+1] == '%' {
fmt.Printf("not implemented %s\n", b)
os.Exit(1)
}
// %%
word := b[i+2:]
val := args[string(param)]
j := bytes.Index([]byte(val), word)
if j < 0 {
return []byte(val)
} else {
return []byte(val[:j])
}
case '#','/','^',',','@':
fmt.Printf("not implemented %s\n", b)
os.Exit(1)
default:
param = append(param, v)
}
}
return b
}