|
6 | 6 | using System.IO; |
7 | 7 | using System.Linq; |
8 | 8 | using CodeGen.Exceptions; |
9 | | -using CodeGen.Helpers; |
| 9 | +using CodeGen.Helpers.PrefixBuilder; |
10 | 10 | using CodeGen.JsonTypes; |
11 | 11 | using Newtonsoft.Json; |
| 12 | +using static CodeGen.Helpers.PrefixBuilder.BaseUnitPrefixes; |
12 | 13 |
|
13 | | -namespace CodeGen.Generators |
| 14 | +namespace CodeGen.Generators; |
| 15 | + |
| 16 | +/// <summary> |
| 17 | +/// Parses JSON files that define quantities and their units. |
| 18 | +/// This will later be used to generate source code and can be reused for different targets such as .NET framework, |
| 19 | +/// .NET Core, .NET nanoFramework and even other programming languages. |
| 20 | +/// </summary> |
| 21 | +internal static class QuantityJsonFilesParser |
14 | 22 | { |
| 23 | + private static readonly JsonSerializerSettings JsonSerializerSettings = new() |
| 24 | + { |
| 25 | + // Don't override the C# default assigned values if no value is set in JSON |
| 26 | + NullValueHandling = NullValueHandling.Ignore |
| 27 | + }; |
| 28 | + |
| 29 | + private static readonly string[] BaseQuantityFileNames = |
| 30 | + ["Length", "Mass", "Duration", "ElectricCurrent", "Temperature", "AmountOfSubstance", "LuminousIntensity"]; |
| 31 | + |
15 | 32 | /// <summary> |
16 | 33 | /// Parses JSON files that define quantities and their units. |
17 | | - /// This will later be used to generate source code and can be reused for different targets such as .NET framework, |
18 | | - /// .NET Core, .NET nanoFramework and even other programming languages. |
19 | 34 | /// </summary> |
20 | | - internal static class QuantityJsonFilesParser |
| 35 | + /// <param name="rootDir">Repository root directory, where you cloned the repo to such as "c:\dev\UnitsNet".</param> |
| 36 | + /// <returns>The parsed quantities and their units.</returns> |
| 37 | + public static Quantity[] ParseQuantities(string rootDir) |
21 | 38 | { |
22 | | - private static readonly JsonSerializerSettings JsonSerializerSettings = new JsonSerializerSettings |
23 | | - { |
24 | | - // Don't override the C# default assigned values if no value is set in JSON |
25 | | - NullValueHandling = NullValueHandling.Ignore |
26 | | - }; |
| 39 | + var jsonDir = Path.Combine(rootDir, "Common/UnitDefinitions"); |
| 40 | + var baseQuantityFiles = BaseQuantityFileNames.Select(baseQuantityName => Path.Combine(jsonDir, baseQuantityName + ".json")).ToArray(); |
27 | 41 |
|
28 | | - /// <summary> |
29 | | - /// Parses JSON files that define quantities and their units. |
30 | | - /// </summary> |
31 | | - /// <param name="rootDir">Repository root directory, where you cloned the repo to such as "c:\dev\UnitsNet".</param> |
32 | | - /// <returns>The parsed quantities and their units.</returns> |
33 | | - public static Quantity[] ParseQuantities(string rootDir) |
34 | | - { |
35 | | - var jsonDir = Path.Combine(rootDir, "Common/UnitDefinitions"); |
36 | | - var jsonFileNames = Directory.GetFiles(jsonDir, "*.json"); |
37 | | - return jsonFileNames |
38 | | - .OrderBy(fn => fn, StringComparer.InvariantCultureIgnoreCase) |
39 | | - .Select(ParseQuantityFile) |
40 | | - .ToArray(); |
41 | | - } |
| 42 | + Quantity[] baseQuantities = ParseQuantities(baseQuantityFiles); |
| 43 | + Quantity[] derivedQuantities = ParseQuantities(Directory.GetFiles(jsonDir, "*.json").Except(baseQuantityFiles)); |
42 | 44 |
|
43 | | - private static Quantity ParseQuantityFile(string jsonFileName) |
44 | | - { |
45 | | - try |
46 | | - { |
47 | | - var quantity = JsonConvert.DeserializeObject<Quantity>(File.ReadAllText(jsonFileName), JsonSerializerSettings) |
48 | | - ?? throw new UnitsNetCodeGenException($"Unable to parse quantity from JSON file: {jsonFileName}"); |
| 45 | + return BuildQuantities(baseQuantities, derivedQuantities); |
| 46 | + } |
49 | 47 |
|
50 | | - AddPrefixUnits(quantity); |
51 | | - OrderUnitsByName(quantity); |
52 | | - return quantity; |
53 | | - } |
54 | | - catch (Exception e) |
55 | | - { |
56 | | - throw new Exception($"Error parsing quantity JSON file: {jsonFileName}", e); |
57 | | - } |
58 | | - } |
| 48 | + private static Quantity[] ParseQuantities(IEnumerable<string> jsonFiles) |
| 49 | + { |
| 50 | + return jsonFiles.Select(ParseQuantity).ToArray(); |
| 51 | + } |
59 | 52 |
|
60 | | - private static void OrderUnitsByName(Quantity quantity) |
| 53 | + private static Quantity ParseQuantity(string jsonFileName) |
| 54 | + { |
| 55 | + try |
61 | 56 | { |
62 | | - quantity.Units = quantity.Units.OrderBy(u => u.SingularName, StringComparer.OrdinalIgnoreCase).ToArray(); |
| 57 | + return JsonConvert.DeserializeObject<Quantity>(File.ReadAllText(jsonFileName), JsonSerializerSettings) |
| 58 | + ?? throw new UnitsNetCodeGenException($"Unable to parse quantity from JSON file: {jsonFileName}"); |
63 | 59 | } |
64 | | - |
65 | | - private static void AddPrefixUnits(Quantity quantity) |
| 60 | + catch (Exception e) |
66 | 61 | { |
67 | | - var unitsToAdd = new List<Unit>(); |
68 | | - foreach (Unit unit in quantity.Units) |
69 | | - foreach (Prefix prefix in unit.Prefixes) |
70 | | - { |
71 | | - try |
72 | | - { |
73 | | - var prefixInfo = PrefixInfo.Entries[prefix]; |
74 | | - |
75 | | - unitsToAdd.Add(new Unit |
76 | | - { |
77 | | - SingularName = $"{prefix}{unit.SingularName.ToCamelCase()}", // "Kilo" + "NewtonPerMeter" => "KilonewtonPerMeter" |
78 | | - PluralName = $"{prefix}{unit.PluralName.ToCamelCase()}", // "Kilo" + "NewtonsPerMeter" => "KilonewtonsPerMeter" |
79 | | - BaseUnits = null, // Can we determine this somehow? |
80 | | - FromBaseToUnitFunc = $"({unit.FromBaseToUnitFunc}) / {prefixInfo.Factor}", |
81 | | - FromUnitToBaseFunc = $"({unit.FromUnitToBaseFunc}) * {prefixInfo.Factor}", |
82 | | - Localization = GetLocalizationForPrefixUnit(unit.Localization, prefixInfo), |
83 | | - ObsoleteText = unit.ObsoleteText, |
84 | | - SkipConversionGeneration = unit.SkipConversionGeneration, |
85 | | - AllowAbbreviationLookup = unit.AllowAbbreviationLookup |
86 | | - } ); |
87 | | - } |
88 | | - catch (Exception e) |
89 | | - { |
90 | | - throw new Exception($"Error parsing prefix {prefix} for unit {quantity.Name}.{unit.SingularName}.", e); |
91 | | - } |
92 | | - } |
93 | | - |
94 | | - quantity.Units = quantity.Units.Concat(unitsToAdd).ToArray(); |
| 62 | + throw new Exception($"Error parsing quantity JSON file: {jsonFileName}", e); |
95 | 63 | } |
| 64 | + } |
96 | 65 |
|
97 | | - /// <summary> |
98 | | - /// Create unit abbreviations for a prefix unit, given a unit and the prefix. |
99 | | - /// The unit abbreviations are either prefixed with the SI prefix or an explicitly configured abbreviation via |
100 | | - /// <see cref="Localization.AbbreviationsForPrefixes" />. |
101 | | - /// </summary> |
102 | | - private static Localization[] GetLocalizationForPrefixUnit(IEnumerable<Localization> localizations, PrefixInfo prefixInfo) |
| 66 | + /// <summary> |
| 67 | + /// Combines base quantities and derived quantities into a single collection, |
| 68 | + /// while generating prefixed units for each quantity. |
| 69 | + /// </summary> |
| 70 | + /// <param name="baseQuantities"> |
| 71 | + /// The array of base quantities, each containing its respective units. |
| 72 | + /// </param> |
| 73 | + /// <param name="derivedQuantities"> |
| 74 | + /// The array of derived quantities, each containing its respective units. |
| 75 | + /// </param> |
| 76 | + /// <returns> |
| 77 | + /// An ordered array of all quantities, including both base and derived quantities, |
| 78 | + /// with prefixed units generated and added to their respective unit collections. |
| 79 | + /// </returns> |
| 80 | + /// <remarks> |
| 81 | + /// This method utilizes the <see cref="UnitPrefixBuilder" /> to generate prefixed units |
| 82 | + /// for each quantity. The resulting quantities are sorted alphabetically by their names. |
| 83 | + /// </remarks> |
| 84 | + private static Quantity[] BuildQuantities(Quantity[] baseQuantities, Quantity[] derivedQuantities) |
| 85 | + { |
| 86 | + var prefixBuilder = new UnitPrefixBuilder(FromBaseUnits(baseQuantities.SelectMany(x => x.Units))); |
| 87 | + return baseQuantities.Concat(derivedQuantities).Select(quantity => |
103 | 88 | { |
104 | | - return localizations.Select(loc => |
105 | | - { |
106 | | - if (loc.TryGetAbbreviationsForPrefix(prefixInfo.Prefix, out string[]? unitAbbreviationsForPrefix)) |
107 | | - { |
108 | | - return new Localization |
109 | | - { |
110 | | - Culture = loc.Culture, |
111 | | - Abbreviations = unitAbbreviationsForPrefix |
112 | | - }; |
113 | | - } |
114 | | - |
115 | | - // No prefix unit abbreviations are specified, so fall back to prepending the default SI prefix to each unit abbreviation: |
116 | | - // kilo ("k") + meter ("m") => kilometer ("km") |
117 | | - var prefix = prefixInfo.GetPrefixForCultureOrSiPrefix(loc.Culture); |
118 | | - unitAbbreviationsForPrefix = loc.Abbreviations.Select(unitAbbreviation => $"{prefix}{unitAbbreviation}").ToArray(); |
119 | | - |
120 | | - return new Localization |
121 | | - { |
122 | | - Culture = loc.Culture, |
123 | | - Abbreviations = unitAbbreviationsForPrefix |
124 | | - }; |
125 | | - }).ToArray(); |
126 | | - } |
| 89 | + List<Unit> prefixedUnits = prefixBuilder.GeneratePrefixUnits(quantity); |
| 90 | + quantity.Units = quantity.Units.Concat(prefixedUnits).OrderBy(unit => unit.SingularName, StringComparer.OrdinalIgnoreCase).ToArray(); |
| 91 | + return quantity; |
| 92 | + }).OrderBy(quantity => quantity.Name, StringComparer.InvariantCultureIgnoreCase).ToArray(); |
127 | 93 | } |
128 | 94 | } |
0 commit comments