Skip to content

Commit

Permalink
Use sprig instead of custom go template functions
Browse files Browse the repository at this point in the history
- Remove all except formatSubdomain and unquote
- Improve curly template encodings like base64, first, etc.
- Improve utils Keys and SortedKeys
  • Loading branch information
TheRealSpaceShip committed Apr 4, 2024
1 parent 6f86e66 commit e46000f
Show file tree
Hide file tree
Showing 12 changed files with 458 additions and 502 deletions.
2 changes: 1 addition & 1 deletion cmd/hub/compose/elaborate.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ func Elaborate(manifestFilename string,
// at least there will be a warning for mismatched values
setValuesFromState(stackManifest.Parameters, st, useStateStackParameters)
stackManifest.Requires = connectStateProvides(stackManifest.Requires, st.Provides)
platformProvides = util.MergeUnique(platformProvides, util.SortedKeys2(st.Provides))
platformProvides = util.MergeUnique(platformProvides, util.SortedKeys(st.Provides))
}
if len(platformProvides) > 0 {
stackManifest.Platform.Provides = util.MergeUnique(stackManifest.Platform.Provides, platformProvides)
Expand Down
2 changes: 1 addition & 1 deletion cmd/hub/lifecycle/deploy.go
Original file line number Diff line number Diff line change
Expand Up @@ -639,7 +639,7 @@ func addLockedParameter2(params []parameters.LockedParameter, name, env, value s
}

func addHubProvides(params []parameters.LockedParameter, provides map[string][]string) []parameters.LockedParameter {
return addLockedParameter2(params, "hub.provides", "HUB_PROVIDES", strings.Join(util.SortedKeys2(provides), " "))
return addLockedParameter2(params, "hub.provides", "HUB_PROVIDES", strings.Join(util.SortedKeys(provides), " "))
}

func maybeTestVerb(verb string, test bool) string {
Expand Down
84 changes: 84 additions & 0 deletions cmd/hub/lifecycle/go_template_functions.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package lifecycle

import (
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
)

// Converts the string into kubernetes acceptable name
// which consist of kebab lower case with alphanumeric characters.
// '.' is not allowed
//
// Arguments:
//
// First argument is a text to convert
// Second optional argument is a size of the name (default is 63)
// Third optional argument is a delimiter (default is '-')
func formatSubdomain(args ...interface{}) (string, error) {
if len(args) == 0 {
return "", fmt.Errorf("hostname expects at least one argument")
}
arg0 := reflect.ValueOf(args[0])
if arg0.Kind() != reflect.String {
return "", fmt.Errorf("hostname expects string as first argument")
}
text := strings.TrimSpace(arg0.String())
if text == "" {
return "", nil
}

size := 63
if len(args) > 1 {
arg1 := reflect.ValueOf(args[1])
if arg1.Kind() == reflect.Int {
size = int(reflect.ValueOf(args[1]).Int())
} else if arg1.Kind() == reflect.String {
size, _ = strconv.Atoi(arg1.String())
} else {
return "", fmt.Errorf("Argument type %T not yet supported", args[1])
}
}

var del = "-"
if len(args) > 2 {
del = fmt.Sprintf("%v", args[2])
}

var matchAllCap = regexp.MustCompile("([a-z0-9])([A-Z])")
var matchNonAlphanumericEnd = regexp.MustCompile("[^a-zA-Z0-9]+$")
var matchNonLetterStart = regexp.MustCompile("^[^a-zA-Z]+")
var matchNonAnumericOrDash = regexp.MustCompile("[^a-zA-Z0-9-]+")
var matchTwoOrMoreDashes = regexp.MustCompile("-{2,}")

text = matchNonLetterStart.ReplaceAllString(text, "")
text = matchAllCap.ReplaceAllString(text, "${1}-${2}")
text = matchNonAnumericOrDash.ReplaceAllString(text, "-")
text = matchTwoOrMoreDashes.ReplaceAllString(text, "-")
text = strings.ToLower(text)
if len(text) > size {
text = text[:size]
}
text = matchNonAlphanumericEnd.ReplaceAllString(text, "")
if del != "-" {
text = strings.ReplaceAll(text, "-", del)
}
return text, nil
}

// Removes single or double or back quotes from the string
func unquote(str string) (string, error) {
result, err := strconv.Unquote(str)
if err != nil && err.Error() == "invalid syntax" {
return str, err
}
return result, err
}

var hubGoTemplateFuncMap = map[string]interface{}{
"formatSubdomain": formatSubdomain,
"unquote": unquote,
"uquote": unquote,
}
82 changes: 82 additions & 0 deletions cmd/hub/lifecycle/go_template_functions_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
// Copyright (c) 2022 EPAM Systems, Inc.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

package lifecycle

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestFormatSubdomain(t *testing.T) {
result, _ := formatSubdomain("")
assert.Equal(t, "", result)

result, _ = formatSubdomain("a")
assert.Equal(t, "a", result)

result, _ = formatSubdomain("a b")
assert.Equal(t, "a-b", result)

// dashes cannot repeat
result, _ = formatSubdomain("A B c")
assert.Equal(t, "a-b-c", result)

// cannot start and finish with dash
result, _ = formatSubdomain("--a b c--")
assert.Equal(t, "a-b-c", result)

// cannot start but can finish with digit
result, _ = formatSubdomain("12a3 b c4")
assert.Equal(t, "a3-b-c4", result)

// max length
result, _ = formatSubdomain("a b c", 3)
assert.Equal(t, "a-b", result)

// second param may be string
result, _ = formatSubdomain("a b c", "3")
assert.Equal(t, "a-b", result)

// max length and delimiter
result, _ = formatSubdomain("a b c", 3, "_")
assert.Equal(t, "a_b", result)
}

func TestUnquote(t *testing.T) {
result, _ := unquote("")
assert.Equal(t, "", result)

result, _ = unquote("a")
assert.Equal(t, "a", result)

result, _ = unquote("'a'")
assert.Equal(t, "a", result)

result, _ = unquote("\"a\"")
assert.Equal(t, "a", result)

result, _ = unquote("\"a")
assert.Equal(t, "\"a", result)

result, _ = unquote("a\"")
assert.Equal(t, "a\"", result)

result, err := unquote("'a")
assert.Equal(t, "'a", result)
assert.EqualError(t, err, "invalid syntax")

result, err = unquote("a'")
assert.Equal(t, "a'", result)
assert.EqualError(t, err, "invalid syntax")

result, _ = unquote("\"a'b\"")
assert.Equal(t, "a'b", result)

_, err = unquote("'a\"b'")
assert.EqualError(t, err, "invalid syntax")
}
Loading

0 comments on commit e46000f

Please sign in to comment.