fuzzyworld

template / windows / files / name_pattern.go

Branch windows · default branch · all branches

name_pattern.go

Blame: the commit that last changed each line · file · history

c62570e2 2022-09-23 Pavel Safronov1package main
2
71bdf574 2022-09-23 Pavel Safronov3import (
4 "errors"
05f9e8ef 2022-10-06 Pavel Safronov5 "fmt"
71bdf574 2022-09-23 Pavel Safronov6 "strings"
7 "text/template"
8 "time"
9)
c62570e2 2022-09-23 Pavel Safronov10
687d5626 2022-10-28 Pavel Safronov11func createNewNameForPatterns(
12 now time.Time,
8c15a714 2022-11-04 Pavel Safronov13 patternData PrePatternData,
687d5626 2022-10-28 Pavel Safronov14 projectName string,
15 namePatterns []ParameterizedText,
10676da3 2022-11-06 Pavel Safronov16 extras map[string]string,
17 validator func(newName string) bool) (string, error) {
5e7795dc 2022-10-21 Pavel Safronov18 for index, namePattern := range namePatterns {
71bdf574 2022-09-23 Pavel Safronov19
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
1a02ef4e 2022-10-21 Pavel Safronov32 template, err := template.Parse(string(namePattern))
71bdf574 2022-09-23 Pavel Safronov33 if err != nil {
8c15a714 2022-11-04 Pavel Safronov34 return "", fmt.Errorf("error parsing name pattern %d: %w", index, err)
71bdf574 2022-09-23 Pavel Safronov35 }
36
37 sb := new(strings.Builder)
38 err = template.Execute(sb, patternData)
39 if err != nil {
8c15a714 2022-11-04 Pavel Safronov40 return "", fmt.Errorf("error executing name pattern %d: %w", index, err)
71bdf574 2022-09-23 Pavel Safronov41 }
42
43 newName := sb.String()
10676da3 2022-11-06 Pavel Safronov44 isValid := validator(newName)
71bdf574 2022-09-23 Pavel Safronov45 useIndex := invokeCount > 0
5e7795dc 2022-10-21 Pavel Safronov46 isLastPattern := index == len(namePatterns)-1
71bdf574 2022-09-23 Pavel Safronov47
10676da3 2022-11-06 Pavel Safronov48 // if new name is valid, use this name
49 if isValid {
8c15a714 2022-11-04 Pavel Safronov50 return newName, nil
71bdf574 2022-09-23 Pavel Safronov51 }
10676da3 2022-11-06 Pavel Safronov52
71bdf574 2022-09-23 Pavel Safronov53 // 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 {
8c15a714 2022-11-04 Pavel Safronov61 return "", errors.New("cannot use function getVersion in a pattern that is not the last pattern")
71bdf574 2022-09-23 Pavel Safronov62 }
63
64 startingVersion++
65 }
66 }
8c15a714 2022-11-04 Pavel Safronov67 return "", errors.New("couldn't find a new name")
71bdf574 2022-09-23 Pavel Safronov68}