Add clean_ami_name for gcp

This commit is contained in:
Atsushi Ishibashi 2017-10-16 00:53:18 +09:00
parent 201b9a21e0
commit caa6c9bf22
2 changed files with 78 additions and 0 deletions

View File

@ -0,0 +1,44 @@
package googlecompute
import (
"regexp"
"strings"
"text/template"
)
func isalphanumeric(b byte) bool {
if '0' <= b && b <= '9' {
return true
}
if 'a' <= b && b <= 'z' {
return true
}
return false
}
// Clean up image name by replacing invalid characters with "-"
// truncate up to 63 length, convert to a lower case
func templateCleanAMIName(s string) string {
re := regexp.MustCompile(`^[a-z][-a-z0-9]{0,61}[a-z0-9]$`)
if re.MatchString(s) {
return s
}
b := []byte(strings.ToLower(s))
l := 63
if len(b) < 63 {
l = len(b)
}
newb := make([]byte, l)
for i := range newb {
if isalphanumeric(b[i]) {
newb[i] = b[i]
} else {
newb[i] = '-'
}
}
return string(newb)
}
var TemplateFuncs = template.FuncMap{
"clean_ami_name": templateCleanAMIName,
}

View File

@ -0,0 +1,34 @@
package googlecompute
import "testing"
func Test_templateCleanAMIName(t *testing.T) {
vals := []struct {
origName string
expected string
}{
{
origName: "abcde-012345xyz",
expected: "abcde-012345xyz",
},
{
origName: "ABCDE-012345xyz",
expected: "abcde-012345xyz",
},
{
origName: "abcde-012345v1.0.0",
expected: "abcde-012345v1-0-0",
},
{
origName: "0123456789012345678901234567890123456789012345678901234567890123456789",
expected: "012345678901234567890123456789012345678901234567890123456789012",
},
}
for _, v := range vals {
name := templateCleanAMIName(v.origName)
if name != v.expected {
t.Fatalf("template names do not match: expected %s got %s\n", v.expected, name)
}
}
}