Skip to content

Commit

Permalink
Implement compilation transforms
Browse files Browse the repository at this point in the history
  • Loading branch information
evanpurkhiser committed Jul 12, 2019
1 parent 1e4326c commit c019ddb
Show file tree
Hide file tree
Showing 2 changed files with 96 additions and 0 deletions.
26 changes: 26 additions & 0 deletions installer/transforms.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package installer

import (
"bytes"
"os"
"regexp"
)

var shebangRegex = regexp.MustCompile("^#!.*\n")

// trimShebang removes leading shebangs from a byte slice.
func trimShebang(d []byte) []byte {
return shebangRegex.ReplaceAll(d, []byte{})
}

// trimWhitespace removes whitespace before and after a byte slice.
func trimWhitespace(d []byte) []byte {
return bytes.Trim(d, "\n\t ")
}

var envGetter = os.Getenv

// expandEnvironment replaces environment variables.
func expandEnvironment(d []byte) []byte {
return []byte(os.Expand(string(d), envGetter))
}
70 changes: 70 additions & 0 deletions installer/transforms_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package installer

import (
"testing"
)

func TestTrimWhitespace(t *testing.T) {
testCases := []struct {
input string
expected string
}{
{"Nothing to trim", "Nothing to trim"},
{" \n\nOne Two \n ", "One Two"},
}

for _, testCase := range testCases {
actual := trimWhitespace([]byte(testCase.input))

if string(actual) != testCase.expected {
t.Errorf("Expected string = %s; got string = %s", testCase.expected, actual)
}
}
}

func TestTrimShebang(t *testing.T) {
testCases := []struct {
input string
expected string
}{
{"#!/bin/bash\ncode", "code"},
{"code\n#!/bin/bash\ncode", "code\n#!/bin/bash\ncode"},
}

for _, testCase := range testCases {
actual := trimShebang([]byte(testCase.input))

if string(actual) != testCase.expected {
t.Errorf("Expected string = %s; got string = %s", testCase.expected, actual)
}
}
}

func TestExpandEnvironment(t *testing.T) {
envMap := map[string]string{
"VARIABLE": "myVariable",
}

testCases := []struct {
input string
expected string
}{
{"Testing ${VARIABLE}", "Testing myVariable"},
{"testing ${INVALID}", "testing "},
}

origEnvGetter := envGetter
defer func() { envGetter = origEnvGetter }()

envGetter = func(key string) string {
return envMap[key]
}

for _, testCase := range testCases {
actual := expandEnvironment([]byte(testCase.input))

if string(actual) != testCase.expected {
t.Errorf("Expected string = %s; got string = %s", testCase.expected, actual)
}
}
}

0 comments on commit c019ddb

Please sign in to comment.