-
Notifications
You must be signed in to change notification settings - Fork 301
/
Copy pathVersionConverterStubGenerator.cs
70 lines (62 loc) · 2.38 KB
/
VersionConverterStubGenerator.cs
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
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using NSwag;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace LibKubernetesGenerator
{
internal class VersionConverterStubGenerator
{
private readonly ClassNameHelper classNameHelper;
public VersionConverterStubGenerator(ClassNameHelper classNameHelper)
{
this.classNameHelper = classNameHelper;
}
public void Generate(OpenApiDocument swagger, IncrementalGeneratorPostInitializationContext context)
{
var allGeneratedModelClassNames = new List<string>();
foreach (var kv in swagger.Definitions)
{
var def = kv.Value;
var clz = classNameHelper.GetClassNameForSchemaDefinition(def);
allGeneratedModelClassNames.Add(clz);
}
var versionRegex = @"(^V|v)[0-9]+((alpha|beta)[0-9]+)?";
var typePairs = allGeneratedModelClassNames
.OrderBy(x => x)
.Select(x => new
{
Version = Regex.Match(x, versionRegex).Value?.ToLower(),
Kinda = Regex.Replace(x, versionRegex, string.Empty),
Type = x,
})
.Where(x => !string.IsNullOrEmpty(x.Version))
.GroupBy(x => x.Kinda)
.Where(x => x.Count() > 1)
.SelectMany(x =>
x.SelectMany((value, index) => x.Skip(index + 1), (first, second) => new { first, second }))
.OrderBy(x => x.first.Kinda)
.ThenBy(x => x.first.Version)
.Select(x => (x.first.Type, x.second.Type))
.ToList();
var sbmodel = new StringBuilder(@"// <auto-generated />
namespace k8s.Models;
");
foreach (var (t0, t1) in typePairs)
{
sbmodel.AppendLine($@"
public partial class {t0}
{{
public static explicit operator {t0}({t1} s) => ModelVersionConverter.Convert<{t1}, {t0}>(s);
}}
public partial class {t1}
{{
public static explicit operator {t1}({t0} s) => ModelVersionConverter.Convert<{t0}, {t1}>(s);
}}");
}
context.AddSource($"ModelOperators.g.cs", SourceText.From(sbmodel.ToString(), Encoding.UTF8));
}
}
}