package main import ( "fmt" "strconv" "strings" "unicode" "github.com/google/uuid" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/reflect/protoregistry" "google.golang.org/protobuf/types/dynamicpb" ) const ( enumExtensionName = "trogon.uuid.v1.enum" enumValueExtensionName = "trogon.uuid.v1.enum_value" defaultRuntimePath = "::trogon_uuid" ) type recipe struct { marker string namespace uuid.UUID template string } type templatePart struct { literal string field string } func generateFile(file protoreflect.FileDescriptor, files *protoregistry.Files, parameter string) (string, error) { enumExt, err := extension(files, enumExtensionName) if err != nil { return "", err } valueExt, err := extension(files, enumValueExtensionName) if err != nil { return "", err } runtimePath := defaultRuntimePath for _, option := range strings.Split(parameter, ",") { key, value, ok := strings.Cut(option, "=") if ok && key == "runtime_path" && value != "" { runtimePath = value } } if !strings.HasPrefix(runtimePath, "::") || strings.ContainsAny(runtimePath, " ;\t\r\n") { return "", fmt.Errorf("invalid runtime_path %q", runtimePath) } var recipes []recipe for i := 0; i < file.Enums().Len(); i++ { enum := file.Enums().Get(i) enumNamespace, hasNamespace, err := namespaceFromOptions(enum.Options(), enumExt) if err != nil { return "", fmt.Errorf("enum %s: %w", enum.FullName(), err) } for j := 0; j < enum.Values().Len(); j++ { value := enum.Values().Get(j) format, configured, err := formatFromOptions(value.Options(), valueExt) if err != nil { return "", fmt.Errorf("enum value %s: %w", value.FullName(), err) } if !configured { continue } namespace := format.namespace if namespace == uuid.Nil && !format.hasNamespace { if !hasNamespace { return "", fmt.Errorf("enum value %s has no namespace", value.FullName()) } namespace = enumNamespace } versionNamespace := uuid.NewSHA1(namespace, []byte(value.Name())) recipes = append(recipes, recipe{ marker: rustTypeName(string(value.Name())), namespace: versionNamespace, template: format.template, }) } } if len(recipes) == 0 { return "", nil } var out strings.Builder fmt.Fprintf(&out, "// Code generated by protoc-gen-trogon-uuid. DO NOT EDIT.\n// Source: %s\n\n", file.Path()) for _, recipe := range recipes { if err := emitRecipe(&out, recipe, runtimePath); err != nil { return "", err } } return out.String(), nil } type formatValue struct { template string namespace uuid.UUID hasNamespace bool } func extension(files *protoregistry.Files, name string) (protoreflect.ExtensionType, error) { descriptor, err := files.FindDescriptorByName(protoreflect.FullName(name)) if err != nil { return nil, fmt.Errorf("required extension %s is missing: %w", name, err) } extension, ok := descriptor.(protoreflect.ExtensionDescriptor) if !ok { return nil, fmt.Errorf("descriptor %s is not an extension", name) } return dynamicpb.NewExtensionType(extension), nil } func namespaceFromOptions(options protoreflect.ProtoMessage, ext protoreflect.ExtensionType) (uuid.UUID, bool, error) { message, present, err := extensionMessage(options, ext) if err != nil || !present { return uuid.Nil, false, err } namespace, ok, err := messageField(message, "namespace") if err != nil || !ok { return uuid.Nil, false, err } return parseNamespace(namespace) } func formatFromOptions(options protoreflect.ProtoMessage, ext protoreflect.ExtensionType) (formatValue, bool, error) { message, present, err := extensionMessage(options, ext) if err != nil || !present { return formatValue{}, false, err } format, hasFormat, err := messageField(message, "format") if err != nil { return formatValue{}, false, err } if !hasFormat { return formatValue{}, false, fmt.Errorf("format option is absent") } template, err := stringField(format, "template") if err != nil { return formatValue{}, false, err } namespace, hasNamespace, err := messageField(format, "namespace") if err != nil { return formatValue{}, false, err } parsedNamespace := uuid.Nil if hasNamespace { parsedNamespace, _, err = parseNamespace(namespace) if err != nil { return formatValue{}, false, err } } return formatValue{template: template, namespace: parsedNamespace, hasNamespace: hasNamespace}, true, nil } func extensionMessage(options protoreflect.ProtoMessage, ext protoreflect.ExtensionType) (protoreflect.Message, bool, error) { encoded, err := proto.Marshal(options) if err != nil { return nil, false, fmt.Errorf("marshal options: %w", err) } resolver := new(protoregistry.Types) if err := resolver.RegisterExtension(ext); err != nil { return nil, false, fmt.Errorf("register extension %s: %w", ext.TypeDescriptor().FullName(), err) } message := dynamicpb.NewMessage(ext.TypeDescriptor().ContainingMessage()) if err := (proto.UnmarshalOptions{Resolver: resolver}).Unmarshal(encoded, message); err != nil { return nil, false, fmt.Errorf("decode options: %w", err) } if !proto.HasExtension(message, ext) { return nil, false, nil } value := proto.GetExtension(message, ext) extensionMessage, ok := value.(protoreflect.Message) if !ok { return nil, false, fmt.Errorf("extension is not a message") } return extensionMessage, true, nil } func messageField(message protoreflect.Message, name string) (protoreflect.Message, bool, error) { field := message.Descriptor().Fields().ByName(protoreflect.Name(name)) if field == nil || field.Kind() != protoreflect.MessageKind || field.IsList() { return nil, false, fmt.Errorf("field %s is not an optional message", name) } if !message.Has(field) { return nil, false, nil } return message.Get(field).Message(), true, nil } func stringField(message protoreflect.Message, name string) (string, error) { field := message.Descriptor().Fields().ByName(protoreflect.Name(name)) if field == nil || field.Kind() != protoreflect.StringKind || field.IsList() { return "", fmt.Errorf("field %s is not a string", name) } return message.Get(field).String(), nil } func parseNamespace(message protoreflect.Message) (uuid.UUID, bool, error) { oneof := message.Descriptor().Oneofs().ByName("value") if oneof == nil { return uuid.Nil, false, fmt.Errorf("namespace has no value oneof") } var selected protoreflect.FieldDescriptor for i := 0; i < oneof.Fields().Len(); i++ { field := oneof.Fields().Get(i) if message.Has(field) { if selected != nil { return uuid.Nil, false, fmt.Errorf("namespace selects multiple values") } selected = field } } if selected == nil { return uuid.Nil, false, fmt.Errorf("namespace selects no value") } name := selected.Name() value := message.Get(selected).String() switch name { case "uuid": parsed, err := uuid.Parse(value) return parsed, true, err case "dns": return uuid.NewSHA1(uuid.NameSpaceDNS, []byte(value)), true, nil case "url": return uuid.NewSHA1(uuid.NameSpaceURL, []byte(value)), true, nil default: return uuid.Nil, false, fmt.Errorf("unsupported namespace %s", name) } } func emitRecipe(out *strings.Builder, recipe recipe, runtimePath string) error { parts, fields, err := parseTemplate(recipe.template) if err != nil { return err } marker := recipe.marker fmt.Fprintf(out, "#[derive(Debug, Clone, Copy)]\npub struct %s;\n", marker) fmt.Fprintf(out, "impl %s {\n", marker) fmt.Fprintf(out, " pub const NAMESPACE: %s::Uuid = %s::Uuid::from_bytes(%s);\n", runtimePath, runtimePath, uuidBytes(recipe.namespace)) if len(fields) == 0 { value := uuid.NewSHA1(recipe.namespace, []byte(recipe.template)) fmt.Fprintf(out, " pub const VALUE: %s::Uuid = %s::Uuid::from_bytes(%s);\n", runtimePath, runtimePath, uuidBytes(value)) fmt.Fprintf(out, " pub fn uuid5(input: ()) -> %s::Uuid { ::uuid5(input) }\n", runtimePath, runtimePath) } else { fmt.Fprintf(out, " pub fn uuid5(input: %sInput<'_>) -> %s::Uuid { ::uuid5(input) }\n", marker, runtimePath, runtimePath) } fmt.Fprintln(out, "}") if len(fields) == 0 { fmt.Fprintf(out, "impl %s::UuidTemplate for %s {\n type Input<'a> = ();\n const NAMESPACE: %s::Uuid = Self::NAMESPACE;\n fn uuid5(_input: ()) -> %s::Uuid { Self::VALUE }\n}\n\n", runtimePath, marker, runtimePath, runtimePath) return nil } fmt.Fprintf(out, "#[derive(Debug, Clone, Copy)]\npub struct %sInput<'a> {\n", marker) for _, field := range fields { fmt.Fprintf(out, " pub %s: &'a str,\n", rustIdent(field)) } fmt.Fprintln(out, "}") fmt.Fprintf(out, "impl %s::UuidTemplate for %s {\n type Input<'a> = %sInput<'a>;\n const NAMESPACE: %s::Uuid = Self::NAMESPACE;\n fn uuid5(input: %sInput<'_>) -> %s::Uuid {\n %s::uuid5_parts(&Self::NAMESPACE, [", runtimePath, marker, marker, runtimePath, marker, runtimePath, runtimePath) for i, part := range parts { if i > 0 { fmt.Fprint(out, ", ") } if part.field != "" { fmt.Fprintf(out, "input.%s.as_bytes()", rustIdent(part.field)) } else { fmt.Fprintf(out, "%s.as_bytes()", strconv.Quote(part.literal)) } } fmt.Fprint(out, "])\n }\n}\n\n") return nil } func parseTemplate(text string) ([]templatePart, []string, error) { var parts []templatePart var fields []string seen := map[string]bool{} start := 0 for i := 0; i < len(text); i++ { switch text[i] { case '{': if start < i { parts = append(parts, templatePart{literal: text[start:i]}) } end := strings.IndexByte(text[i+1:], '}') if end < 0 { return nil, nil, fmt.Errorf("template has an unclosed placeholder") } end += i + 1 name := text[i+1 : end] if !validField(name) { return nil, nil, fmt.Errorf("template placeholder %q is not an identifier", name) } parts = append(parts, templatePart{field: name}) if !seen[name] { seen[name] = true fields = append(fields, name) } i = end start = end + 1 case '}': return nil, nil, fmt.Errorf("template has an unmatched closing brace") } } if start < len(text) { parts = append(parts, templatePart{literal: text[start:]}) } return parts, fields, nil } func validField(name string) bool { if name == "" || name[0] >= '0' && name[0] <= '9' { return false } for _, r := range name { if !unicode.IsLetter(r) && !unicode.IsDigit(r) && r != '_' { return false } } return true } func rustTypeName(name string) string { var out strings.Builder upper := true for _, r := range name { if r == '_' || r == '-' { upper = true continue } if upper { out.WriteRune(unicode.ToUpper(r)) upper = false } else { out.WriteRune(unicode.ToLower(r)) } } return out.String() } func rustIdent(name string) string { switch name { case "as", "break", "const", "continue", "crate", "else", "enum", "extern", "false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return", "self", "Self", "static", "struct", "super", "trait", "true", "type", "unsafe", "use", "where", "while", "async", "await", "dyn": return "r#" + name default: return name } } func uuidBytes(value uuid.UUID) string { parts := make([]string, len(value)) for i, b := range value { parts[i] = fmt.Sprintf("0x%02x", b) } return "[" + strings.Join(parts, ", ") + "]" }