-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathexportfunctions.go
More file actions
76 lines (64 loc) · 1.6 KB
/
exportfunctions.go
File metadata and controls
76 lines (64 loc) · 1.6 KB
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
package ejson2env
import (
"fmt"
"io"
"os"
"sort"
"strings"
"unicode"
"al.essio.dev/pkg/shellescape"
)
// ExportEnv writes the passed environment values to the passed
// io.Writer.
func ExportEnv(w io.Writer, values map[string]string) {
export(w, "export ", values)
}
// ExportQuiet writes the passed environment values to the passed
// io.Writer in %s=%s format.
func ExportQuiet(w io.Writer, values map[string]string) {
export(w, "", values)
}
func TrimLeadingUnderscoreExportWrapper(exportfunc ExportFunction) ExportFunction {
return func(w io.Writer, values map[string]string) {
newValues := make(map[string]string, len(values))
for key, value := range values {
newValues[strings.TrimLeft(key, "_")] = value
}
exportfunc(w, newValues)
}
}
func export(w io.Writer, prefix string, values map[string]string) {
keys := make([]string, 0, len(values))
for k := range values {
if !validKey(k) {
fmt.Fprintf(os.Stderr, "ejson2env blocked invalid key")
continue
}
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
value := filteredValue(values[k])
fmt.Fprintf(w, "%s%s=%s\n", prefix, k, value)
}
}
func validKey(k string) bool {
for _, r := range k {
if !unicode.IsLetter(r) && !unicode.IsDigit(r) && r != '_' && r != '-' {
return false
}
}
return true
}
func filteredValue(v string) string {
printable := strings.Map(func(r rune) rune {
if unicode.IsControl(r) && r != '\n' {
return -1
}
return r
}, v)
if printable != v {
fmt.Fprintf(os.Stderr, "ejson2env trimmed control characters from value")
}
return shellescape.Quote(printable)
}