template / ci-testing / files / name_pattern.go
Branch ci-testing · default branch · all branches
name_pattern.go
| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "fmt" |
| 6 | "strings" |
| 7 | "text/template" |
| 8 | "time" |
| 9 | |
| 10 | "github.com/Masterminds/sprig/v3" |
| 11 | ) |
| 12 | |
| 13 | func createNewNameForPatterns( |
| 14 | now time.Time, |
| 15 | patternData PrePatternData, |
| 16 | projectName string, |
| 17 | namePatterns []ParameterizedText, |
| 18 | extras map[string]string, |
| 19 | validator func(newName string) bool) (string, error) { |
| 20 | for index, namePattern := range namePatterns { |
| 21 | |
| 22 | startingVersion := 1 |
| 23 | invokeCount := 0 |
| 24 | funcMap := template.FuncMap{ |
| 25 | "getVersion": func() int { |
| 26 | invokeCount++ |
| 27 | return startingVersion |
| 28 | }, |
| 29 | } |
| 30 | template := template.New("template-name").Funcs(funcMap) |
| 31 | template = template.Funcs(sprig.FuncMap()) |
| 32 | |
| 33 | for { |
| 34 | |
| 35 | template, err := template.Parse(string(namePattern)) |
| 36 | if err != nil { |
| 37 | return "", fmt.Errorf("error parsing name pattern %d: %w", index, err) |
| 38 | } |
| 39 | |
| 40 | sb := new(strings.Builder) |
| 41 | err = template.Execute(sb, patternData) |
| 42 | if err != nil { |
| 43 | return "", fmt.Errorf("error executing name pattern %d: %w", index, err) |
| 44 | } |
| 45 | |
| 46 | newName := sb.String() |
| 47 | isValid := validator(newName) |
| 48 | useIndex := invokeCount > 0 |
| 49 | isLastPattern := index == len(namePatterns)-1 |
| 50 | |
| 51 | // if new name is valid, use this name |
| 52 | if isValid { |
| 53 | return newName, nil |
| 54 | } |
| 55 | |
| 56 | // if index is not being used (template did not invoke getVersion) |
| 57 | // then we're done |
| 58 | if !useIndex { |
| 59 | break |
| 60 | } |
| 61 | |
| 62 | // if getVersion was used, but this isn't the last pattern, report an error |
| 63 | if useIndex && !isLastPattern { |
| 64 | return "", errors.New("cannot use function getVersion in a pattern that is not the last pattern") |
| 65 | } |
| 66 | |
| 67 | startingVersion++ |
| 68 | } |
| 69 | } |
| 70 | return "", errors.New("couldn't find a new name") |
| 71 | } |