template / files / internal / core / name_pattern.go
name_pattern.go
37160b89 2026-05-01 Pavel Safronov | 1 | package core |
fd0a4446 2023-04-03 Pavel Safronov | 2 | |
| 3 | import ( | |
| 4 | "errors" | |
| 5 | "fmt" | |
| 6 | "text/template" | |
| 7 | "time" | |
| 8 | ) | |
| 9 | ||
| 10 | func createNewNameForPatterns( | |
| 11 | now time.Time, | |
| 12 | patternData PrePatternData, | |
| 13 | projectName string, | |
| 14 | namePatterns []ParameterizedText, | |
| 15 | extras map[string]string, | |
| 16 | validator func(newName string) bool) (string, error) { | |
| 17 | for index, namePattern := range namePatterns { | |
| 18 | ||
| 19 | startingVersion := 1 | |
| 20 | invokeCount := 0 | |
| 21 | funcMap := template.FuncMap{ | |
| 22 | "getVersion": func() int { | |
| 23 | invokeCount++ | |
| 24 | return startingVersion | |
| 25 | }, | |
| 26 | } | |
| 27 | t := newTemplate() | |
| 28 | t = t.Funcs(funcMap) | |
| 29 | ||
| 30 | for { | |
| 31 | ||
| 32 | newName, err := parseAndExecTemplate(t, namePattern, patternData) | |
| 33 | if err != nil { | |
| 34 | return "", fmt.Errorf("error templating name pattern %d: %w", index, err) | |
| 35 | } | |
| 36 | ||
| 37 | isValid := validator(newName) | |
| 38 | useIndex := invokeCount > 0 | |
| 39 | isLastPattern := index == len(namePatterns)-1 | |
| 40 | ||
| 41 | // if new name is valid, use this name | |
| 42 | if isValid { | |
| 43 | return newName, nil | |
| 44 | } | |
| 45 | ||
| 46 | // if index is not being used (template did not invoke getVersion) | |
| 47 | // then we're done | |
| 48 | if !useIndex { | |
| 49 | break | |
| 50 | } | |
| 51 | ||
| 52 | // if getVersion was used, but this isn't the last pattern, report an error | |
| 53 | if useIndex && !isLastPattern { | |
| 54 | return "", errors.New("cannot use function getVersion in a pattern that is not the last pattern") | |
| 55 | } | |
| 56 | ||
| 57 | startingVersion++ | |
| 58 | } | |
| 59 | } | |
| 60 | return "", errors.New("couldn't find a new name") | |
| 61 | } |