|
| 1 | +// Licensed under MIT No Attribution, see LICENSE file at the root. |
| 2 | +// Copyright 2013 Andreas Gullberg Larsen ([email protected]). Maintained at https://github.com/angularsen/UnitsNet. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Collections.Generic; |
| 6 | +using System.IO; |
| 7 | +using System.Linq; |
| 8 | +using System.Text; |
| 9 | +using System.Text.Json; |
| 10 | +using CodeGen.Exceptions; |
| 11 | +using CodeGen.JsonTypes; |
| 12 | +using Serilog; |
| 13 | + |
| 14 | +namespace CodeGen.Helpers.UnitEnumValueAllocation |
| 15 | +{ |
| 16 | + /// <summary> |
| 17 | + /// Allocates unique enum values per quantity and persists the mapping to a JSON file to ensure the values do not |
| 18 | + /// change when adding new units. |
| 19 | + /// <br/><br/> |
| 20 | + /// Updating transitive UnitsNet dependency cause wrong unit · Issue #1068 · angularsen/UnitsNet |
| 21 | + /// https://github.com/angularsen/UnitsNet/issues/1068 |
| 22 | + /// </summary> |
| 23 | + internal class UnitEnumValueAllocator |
| 24 | + { |
| 25 | + private static readonly JsonSerializerOptions JsonOptions = new() |
| 26 | + { |
| 27 | + AllowTrailingCommas = true, ReadCommentHandling = JsonCommentHandling.Skip, WriteIndented = true |
| 28 | + }; |
| 29 | + |
| 30 | + private readonly string _jsonFile; |
| 31 | + private readonly QuantityNameToUnitEnumValues _quantityNameToUnitEnumValues; |
| 32 | + |
| 33 | + /// <summary> |
| 34 | + /// Creates an instance for the given JSON file path. |
| 35 | + /// </summary> |
| 36 | + /// <param name="jsonFile">Path to the JSON file that describes the currently allocated enum values.</param> |
| 37 | + private UnitEnumValueAllocator(string jsonFile) |
| 38 | + { |
| 39 | + _jsonFile = jsonFile; |
| 40 | + _quantityNameToUnitEnumValues = ReadFromFile(jsonFile); |
| 41 | + } |
| 42 | + |
| 43 | + /// <summary> |
| 44 | + /// Ensure that all units have a unique unit enum value per quantity. |
| 45 | + /// The values are persisted to a JSON file to ensure the values do not change as new units are added later. |
| 46 | + /// </summary> |
| 47 | + /// <remarks> |
| 48 | + /// If the same value is found for two or more units, then an exception is thrown that effectively breaks the build |
| 49 | + /// with instructions on how |
| 50 | + /// to manually resolve the conflict by assigning unique values. This typically happens by merging two pull requests |
| 51 | + /// that both add units to the same |
| 52 | + /// quantity, which competes for the next available unit enum value. |
| 53 | + /// </remarks> |
| 54 | + /// <param name="jsonFile">The JSON file for storing the enum value allocations.</param> |
| 55 | + /// <param name="quantities">The list of quantities to ensure have unique unit enum values per quantity.</param> |
| 56 | + /// <returns></returns> |
| 57 | + internal static QuantityNameToUnitEnumValues AllocateNewUnitEnumValues(string jsonFile, Quantity[] quantities) |
| 58 | + { |
| 59 | + var unitEnumValueAllocator = new UnitEnumValueAllocator(jsonFile); |
| 60 | + |
| 61 | + foreach (Quantity quantity in quantities) |
| 62 | + { |
| 63 | + unitEnumValueAllocator.AllocateNewUnitEnumValues(quantity); |
| 64 | + } |
| 65 | + |
| 66 | + unitEnumValueAllocator.EnsureUniqueUnitEnumValuesPerQuantity(); |
| 67 | + unitEnumValueAllocator.SaveToFile(); |
| 68 | + |
| 69 | + return unitEnumValueAllocator._quantityNameToUnitEnumValues; |
| 70 | + } |
| 71 | + |
| 72 | + private void EnsureUniqueUnitEnumValuesPerQuantity() |
| 73 | + { |
| 74 | + List<string> duplicateErrorMessages = new(); |
| 75 | + foreach ((var quantityName, UnitEnumNameToValue? unitEnumValues) in _quantityNameToUnitEnumValues) |
| 76 | + { |
| 77 | + // Minor optimization for the common case where there are no duplicates, to skip the more heavy LINQ of grouping and filtering. |
| 78 | + if (unitEnumValues.Values.Count != unitEnumValues.Values.ToHashSet().Count) |
| 79 | + { |
| 80 | + duplicateErrorMessages.AddRange(unitEnumValues |
| 81 | + .GroupBy(x => x.Value, x => x.Key) // Group unit names on enum value. |
| 82 | + .Where(g => g.Count() > 1) // More than one unit name is mapped to the same enum value. |
| 83 | + .Select(unitNames => $"{quantityName} has duplicate unit enum value {unitNames.Key} for units {string.Join(", ", unitNames)}.")); |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + if (duplicateErrorMessages.Any()) |
| 88 | + { |
| 89 | + throw new UnitsNetCodeGenException( |
| 90 | + @$"One or more units have the same unit enum value. This typically happens when merging multiple pull requests adding units to the same quantity. |
| 91 | +Resolve this by manually editing the JSON file to assign unique unit enum values per quantity. |
| 92 | +
|
| 93 | +JSON file: |
| 94 | +{_jsonFile} |
| 95 | +
|
| 96 | +Conflicts: |
| 97 | +{string.Join("\n", duplicateErrorMessages)}"); |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + /// <summary> |
| 102 | + /// Allocates a unique enum value for all units of the given quantity that don't already have one stored in the JSON |
| 103 | + /// file. |
| 104 | + /// </summary> |
| 105 | + /// <param name="quantity">The quantity info.</param> |
| 106 | + private void AllocateNewUnitEnumValues(Quantity quantity) |
| 107 | + { |
| 108 | + foreach (Unit unit in quantity.Units) |
| 109 | + { |
| 110 | + EnsureUnitEnumValueIsAllocated(quantity, unit); |
| 111 | + } |
| 112 | + } |
| 113 | + |
| 114 | + /// <summary> |
| 115 | + /// Allocates a unique enum value for the given unit, if not already allocated. |
| 116 | + /// </summary> |
| 117 | + /// <param name="quantity">The quantity info.</param> |
| 118 | + /// <param name="unit">The unit info.</param> |
| 119 | + private void EnsureUnitEnumValueIsAllocated(Quantity quantity, Unit unit) |
| 120 | + { |
| 121 | + // Get or create new list of enum values for quantity. |
| 122 | + if (!_quantityNameToUnitEnumValues.TryGetValue(quantity.Name, out UnitEnumNameToValue? enumValues)) |
| 123 | + { |
| 124 | + enumValues = _quantityNameToUnitEnumValues[quantity.Name] = new UnitEnumNameToValue(); |
| 125 | + } |
| 126 | + |
| 127 | + // Already allocated enum value for this unit? |
| 128 | + if (enumValues.ContainsKey(unit.SingularName)) |
| 129 | + { |
| 130 | + return; |
| 131 | + } |
| 132 | + |
| 133 | + int value = enumValues.AssignUniqueValue(unit.SingularName); |
| 134 | + |
| 135 | + Log.Information("Allocated new value {Value} for {Quantity}.{Unit}", value, quantity.Name, unit.SingularName); |
| 136 | + } |
| 137 | + |
| 138 | + private void SaveToFile() |
| 139 | + { |
| 140 | + var fileContentStringBuilder = new StringBuilder(); |
| 141 | + fileContentStringBuilder.Append(@"//------------------------------------------------------------------------------ |
| 142 | +// <auto-generated> |
| 143 | +// This file is updated by \generate-code.bat and represents the unique unit enum values allocated when adding new units. |
| 144 | +// Do not modify this file manually unless you know what you are doing, as it may cause breaking changes for consumers relying on consistent enum values. |
| 145 | +// </auto-generated> |
| 146 | +//------------------------------------------------------------------------------ |
| 147 | +// |
| 148 | +// Licensed under MIT No Attribution, see LICENSE file at the root. |
| 149 | +// Copyright 2013 Andreas Gullberg Larsen ([email protected]). Maintained at https://github.com/angularsen/UnitsNet. |
| 150 | +"); |
| 151 | + |
| 152 | + fileContentStringBuilder.AppendLine(JsonSerializer.Serialize(_quantityNameToUnitEnumValues, JsonOptions)); |
| 153 | + File.WriteAllText(_jsonFile, fileContentStringBuilder.ToString()); |
| 154 | + } |
| 155 | + |
| 156 | + /// <summary> |
| 157 | + /// Loads the stored allocations from the JSON file. |
| 158 | + /// </summary> |
| 159 | + /// <param name="jsonFile"></param> |
| 160 | + /// <exception cref="InvalidOperationException">Failed to deserialize.</exception> |
| 161 | + private static QuantityNameToUnitEnumValues ReadFromFile(string jsonFile) |
| 162 | + { |
| 163 | + if (File.Exists(jsonFile)) |
| 164 | + { |
| 165 | + return JsonSerializer.Deserialize<QuantityNameToUnitEnumValues>(File.ReadAllText(jsonFile), JsonOptions) |
| 166 | + ?? throw new InvalidOperationException($"Failed to deserialize file: {jsonFile}"); |
| 167 | + } |
| 168 | + |
| 169 | + return new QuantityNameToUnitEnumValues(); |
| 170 | + } |
| 171 | + } |
| 172 | +} |
0 commit comments