Skip to content

Commit c019ddb

Browse files
committed
Implement compilation transforms
1 parent 1e4326c commit c019ddb

File tree

2 files changed

+96
-0
lines changed

2 files changed

+96
-0
lines changed

installer/transforms.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package installer
2+
3+
import (
4+
"bytes"
5+
"os"
6+
"regexp"
7+
)
8+
9+
var shebangRegex = regexp.MustCompile("^#!.*\n")
10+
11+
// trimShebang removes leading shebangs from a byte slice.
12+
func trimShebang(d []byte) []byte {
13+
return shebangRegex.ReplaceAll(d, []byte{})
14+
}
15+
16+
// trimWhitespace removes whitespace before and after a byte slice.
17+
func trimWhitespace(d []byte) []byte {
18+
return bytes.Trim(d, "\n\t ")
19+
}
20+
21+
var envGetter = os.Getenv
22+
23+
// expandEnvironment replaces environment variables.
24+
func expandEnvironment(d []byte) []byte {
25+
return []byte(os.Expand(string(d), envGetter))
26+
}

installer/transforms_test.go

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package installer
2+
3+
import (
4+
"testing"
5+
)
6+
7+
func TestTrimWhitespace(t *testing.T) {
8+
testCases := []struct {
9+
input string
10+
expected string
11+
}{
12+
{"Nothing to trim", "Nothing to trim"},
13+
{" \n\nOne Two \n ", "One Two"},
14+
}
15+
16+
for _, testCase := range testCases {
17+
actual := trimWhitespace([]byte(testCase.input))
18+
19+
if string(actual) != testCase.expected {
20+
t.Errorf("Expected string = %s; got string = %s", testCase.expected, actual)
21+
}
22+
}
23+
}
24+
25+
func TestTrimShebang(t *testing.T) {
26+
testCases := []struct {
27+
input string
28+
expected string
29+
}{
30+
{"#!/bin/bash\ncode", "code"},
31+
{"code\n#!/bin/bash\ncode", "code\n#!/bin/bash\ncode"},
32+
}
33+
34+
for _, testCase := range testCases {
35+
actual := trimShebang([]byte(testCase.input))
36+
37+
if string(actual) != testCase.expected {
38+
t.Errorf("Expected string = %s; got string = %s", testCase.expected, actual)
39+
}
40+
}
41+
}
42+
43+
func TestExpandEnvironment(t *testing.T) {
44+
envMap := map[string]string{
45+
"VARIABLE": "myVariable",
46+
}
47+
48+
testCases := []struct {
49+
input string
50+
expected string
51+
}{
52+
{"Testing ${VARIABLE}", "Testing myVariable"},
53+
{"testing ${INVALID}", "testing "},
54+
}
55+
56+
origEnvGetter := envGetter
57+
defer func() { envGetter = origEnvGetter }()
58+
59+
envGetter = func(key string) string {
60+
return envMap[key]
61+
}
62+
63+
for _, testCase := range testCases {
64+
actual := expandEnvironment([]byte(testCase.input))
65+
66+
if string(actual) != testCase.expected {
67+
t.Errorf("Expected string = %s; got string = %s", testCase.expected, actual)
68+
}
69+
}
70+
}

0 commit comments

Comments
 (0)