* Get or create a Go enum type, deduplicating by type name (not by value set). * Two enums with the same values but different names are distinct types.
(
enumName: string,
values: string[],
ctx: GoCodegenCtx,
description?: string,
enumValueDescriptions?: EnumValueDescriptions,
deprecated?: boolean,
experimental?: boolean
)
| 723 | * Two enums with the same values but different names are distinct types. |
| 724 | */ |
| 725 | function getOrCreateGoEnum( |
| 726 | enumName: string, |
| 727 | values: string[], |
| 728 | ctx: GoCodegenCtx, |
| 729 | description?: string, |
| 730 | enumValueDescriptions?: EnumValueDescriptions, |
| 731 | deprecated?: boolean, |
| 732 | experimental?: boolean |
| 733 | ): string { |
| 734 | const existing = ctx.enumsByName.get(enumName); |
| 735 | if (existing) return existing; |
| 736 | |
| 737 | const lines: string[] = []; |
| 738 | if (description) { |
| 739 | pushGoCommentForContext(lines, description, ctx); |
| 740 | } |
| 741 | if (experimental) { |
| 742 | pushGoExperimentalTypeComment(lines, enumName, ctx); |
| 743 | } |
| 744 | if (deprecated) { |
| 745 | pushGoCommentForContext(lines, `Deprecated: ${enumName} is deprecated and will be removed in a future version.`, ctx); |
| 746 | } |
| 747 | lines.push(`type ${enumName} string`); |
| 748 | lines.push(``); |
| 749 | lines.push(`const (`); |
| 750 | const consts = values |
| 751 | .map((value) => ({ value, constSuffix: goEnumConstSuffix(value) })) |
| 752 | .sort((left, right) => `${enumName}${left.constSuffix}`.localeCompare(`${enumName}${right.constSuffix}`)); |
| 753 | const usedConstNames = new Map<string, string>(); |
| 754 | for (const { value, constSuffix } of consts) { |
| 755 | const constName = `${enumName}${constSuffix}`; |
| 756 | const existingValue = usedConstNames.get(constName); |
| 757 | if (existingValue !== undefined) { |
| 758 | throw new Error( |
| 759 | `Generated Go enum const identifier "${constName}" is not unique for values "${existingValue}" and "${value}". Add an explicit naming rule instead of stabilizing an arbitrary public const name.` |
| 760 | ); |
| 761 | } |
| 762 | usedConstNames.set(constName, value); |
| 763 | const valueDescription = enumValueDescriptions?.[value]; |
| 764 | if (valueDescription) { |
| 765 | pushGoCommentForContext(lines, valueDescription, ctx, "\t"); |
| 766 | } |
| 767 | lines.push(`\t${constName} ${enumName} = "${value}"`); |
| 768 | } |
| 769 | lines.push(`)`); |
| 770 | |
| 771 | ctx.enumsByName.set(enumName, enumName); |
| 772 | ctx.enums.push(lines.join("\n")); |
| 773 | return enumName; |
| 774 | } |
| 775 | |
| 776 | function goEnumConstSuffix(value: string): string { |
| 777 | const suffix = splitGoIdentifierWords(value) |
no test coverage detected
searching dependent graphs…