-
Notifications
You must be signed in to change notification settings - Fork 407
Expand file tree
/
Copy pathNumberExtensionsGenerator.cs
More file actions
73 lines (59 loc) · 2.31 KB
/
NumberExtensionsGenerator.cs
File metadata and controls
73 lines (59 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System;
using CodeGen.JsonTypes;
namespace CodeGen.Generators.UnitsNetGen
{
internal class NumberExtensionsGenerator(Quantity quantity) : GeneratorBase
{
private readonly Quantity _quantity = quantity ?? throw new ArgumentNullException(nameof(quantity));
private readonly Unit[] _units = quantity.Units;
private readonly string _quantityName = quantity.Name;
public string Generate()
{
Writer.WL(GeneratedFileHeader);
Writer.WL(
$@"
using System;
#if NET7_0_OR_GREATER
using System.Numerics;
#endif
#nullable enable
namespace UnitsNet.NumberExtensions.NumberTo{_quantityName}
{{
/// <summary>
/// A number to {_quantityName} Extensions
/// </summary>");
Writer.WLIfText(1, GetObsoleteAttributeOrNull(_quantity));
Writer.WL(@$"
public static class NumberTo{_quantityName}Extensions
{{");
foreach (var unit in _units)
{
if (unit.SkipConversionGeneration)
continue;
Writer.WL(2, $@"
/// <inheritdoc cref=""{_quantityName}.From{unit.PluralName}(QuantityValue)"" />");
// Include obsolete text from the quantity per extension method, to make it visible when the class is not explicitly referenced in code.
Writer.WLIfText(2, GetObsoleteAttributeOrNull(unit.ObsoleteText ?? _quantity.ObsoleteText));
Writer.WL(2, $@"public static {_quantityName} {unit.PluralName}<T>(this T value)
where T : notnull
#if NET7_0_OR_GREATER
, INumber<T>
=> {_quantityName}.From{unit.PluralName}(QuantityValue.CreateChecked(value));
#else
, IConvertible
=> {_quantityName}.From{unit.PluralName}(value.ToQuantityValue());
#endif
");
}
Writer.WL(1, @"}
}");
return Writer.ToString();
}
/// <inheritdoc cref="GetObsoleteAttributeOrNull(string)"/>
private static string? GetObsoleteAttributeOrNull(Quantity quantity) => GetObsoleteAttributeOrNull(quantity.ObsoleteText);
private static string? GetObsoleteAttributeOrNull(string? obsoleteText) =>
string.IsNullOrWhiteSpace(obsoleteText) ?
null :
$"[Obsolete(\"{obsoleteText}\")]";
}
}