Files
2025-10-31 18:33:22 +01:00

63 lines
1.7 KiB
Go

package generator
import (
"fmt"
"strings"
"unicode"
"github.com/entity-maker/entity-maker/internal/naming"
)
// sanitizePythonIdentifier ensures the identifier is valid Python syntax
func sanitizePythonIdentifier(identifier string) string {
// If identifier starts with a digit, prefix with underscore
if len(identifier) > 0 && unicode.IsDigit(rune(identifier[0])) {
return "_" + identifier
}
return identifier
}
// GenerateEnum generates the enum types file
func GenerateEnum(ctx *Context) (string, error) {
var b strings.Builder
// Imports
b.WriteString("from enum import StrEnum\n\n")
b.WriteString("from televend_core.databases.enum import EnumMixin\n\n\n")
// Generate each enum type
for _, enumType := range ctx.TableInfo.EnumTypes {
enumName := naming.ToPascalCase(enumType.TypeName)
b.WriteString(fmt.Sprintf("class %s(EnumMixin, StrEnum):\n", enumName))
if len(enumType.Values) == 0 {
b.WriteString(" pass\n")
} else {
// Track seen identifiers to avoid duplicates
seenIdentifiers := make(map[string]bool)
for _, value := range enumType.Values {
// Convert value to valid Python identifier
// Usually enum values are already uppercase like "OPEN", "IN_PROGRESS"
identifier := strings.ToUpper(strings.ReplaceAll(value, " ", "_"))
identifier = strings.ReplaceAll(identifier, "-", "_")
// Ensure identifier doesn't start with a digit
identifier = sanitizePythonIdentifier(identifier)
// Skip if we've already seen this identifier
if seenIdentifiers[identifier] {
continue
}
seenIdentifiers[identifier] = true
b.WriteString(fmt.Sprintf(" %s = \"%s\"\n", identifier, value))
}
}
b.WriteString("\n")
}
return b.String(), nil
}