package cmd import ( "fmt" "regexp" "strings" "text/template" ) var tplFuncs = template.FuncMap{ "map": tplMap, "cat": tplCat, "split": tplSplit, "join": tplJoin, "under": tplUnder, "varPrefix": tplVarPrefix, "repeat": tplRepeat, "indent": tplIndent, "add": tplAdd, "inc": tplInc, "sub": tplSub, "dec": tplDec, "mult": tplMult, "camel": tplCamel, } func tplMap(vals ...any) (map[string]any, error) { if len(vals)%2 != 0 { return nil, fmt.Errorf("missing value, need one key and one value per kv pair") } m := make(map[string]any) for i := 0; i < len(vals); i += 2 { m[vals[i].(string)] = vals[i+1] } return m, nil } func tplCat(strs ...string) string { return strings.Join(strs, "") } func tplSplit(s string, sep string) []string { return strings.Split(s, sep) } func tplJoin(strs []string, sep string) string { return strings.Join(strs, sep) } func tplUnder(s string) string { // Remove all characters that are not alphanumeric or spaces or underscores s = regexp.MustCompile("[^a-zA-Z0-9_ -]+").ReplaceAllString(s, "") // Replace all spaces with underscores s = strings.ReplaceAll(s, " ", "_") // Replace all dashes with underscores s = strings.ReplaceAll(s, "-", "_") // Convert to lowercase s = strings.ToLower(s) return s } func tplVarPrefix(s string) string { if s == "" { return "" } return tplUnder(s) + "_" } func tplRepeat(s string, n int) string { return strings.Repeat(s, n) } func tplIndent(n int) string { return tplRepeat(" ", n) } func tplAdd(a, b int) int { return a + b } func tplInc(i int) int { return tplAdd(i, 1) } func tplSub(a, b int) int { return a - b } func tplDec(i int) int { return tplSub(i, 1) } func tplMult(a, b int) int { return a * b } func tplCamel(s string) string { // Remove all characters that are not alphanumeric or spaces or underscores s = regexp.MustCompile("[^a-zA-Z0-9_ -]+").ReplaceAllString(s, "") // Replace all underscores with spaces s = strings.ReplaceAll(s, "_", " ") // Replace all dashes with spaces s = strings.ReplaceAll(s, "-", " ") // Title case s words := strings.Split(s, " ") for i, word := range words { words[i] = strings.ToTitle(word) } // Join words s = strings.Join(words, "") return s }