fuzzyworld

template / windows / files / name_pattern.go

Branch windows · default branch · all branches

name_pattern.go

1.5 KB · history · blame

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