|
| 1 | +using System.Collections.Immutable; |
| 2 | +using AutoSDK.Generation; |
| 3 | +using Microsoft.CodeAnalysis; |
| 4 | + |
| 5 | +namespace AutoSDK.SourceGenerators; |
| 6 | + |
| 7 | +[Generator] |
| 8 | +public class CliGenerator : IIncrementalGenerator |
| 9 | +{ |
| 10 | + #region Constants |
| 11 | + |
| 12 | + private const string Id = "CLIG"; |
| 13 | + |
| 14 | + #endregion |
| 15 | + |
| 16 | + #region Methods |
| 17 | + |
| 18 | + public void Initialize(IncrementalGeneratorInitializationContext context) |
| 19 | + { |
| 20 | + var settings = context.DetectSettings(); |
| 21 | + |
| 22 | + var data = context.AdditionalTextsProvider |
| 23 | + .Combine(context.AnalyzerConfigOptionsProvider) |
| 24 | + .Where(static pair => |
| 25 | + pair.Right.GetOption(pair.Left, "OpenApiSpecification", prefix: "AutoSDK")?.ToUpperInvariant() == "TRUE") |
| 26 | + .Select((pair, cancellationToken) => ( |
| 27 | + GetContent(pair.Left, cancellationToken), |
| 28 | + pair.Right.GetSettings(prefix: "AutoSDK", additionalText: pair.Left))) |
| 29 | + .Combine(settings) |
| 30 | + .Where(x => x.Right.GenerateCli) |
| 31 | + .SelectAndReportExceptions(Data.Prepare, context, Id); |
| 32 | + |
| 33 | + data |
| 34 | + .SelectMany(static (x, _) => x.Methods.GroupBy(x => x.Tag)) |
| 35 | + .SelectAndReportExceptions((x, c) => Sources.TagCommand(x.Key, x.ToImmutableArray(), c) |
| 36 | + .AsFileWithName(), context, Id) |
| 37 | + .AddSource(context); |
| 38 | + data |
| 39 | + .SelectMany(static (x, _) => x.Methods) |
| 40 | + .SelectAndReportExceptions((x, c) => Sources.Command(x, c) |
| 41 | + .AsFileWithName(), context, Id) |
| 42 | + .AddSource(context); |
| 43 | + data |
| 44 | + .Select(static (x, _) => x.Tags) |
| 45 | + .SelectAndReportExceptions((x, c) => Sources.MainCommand(x, c) |
| 46 | + .AsFileWithName(), context, Id) |
| 47 | + .AddSource(context); |
| 48 | + data |
| 49 | + .Select(static (x, _) => (x.Methods, x.Tags)) |
| 50 | + .SelectAndReportExceptions((x, c) => Sources.AddCommands(x.Methods, x.Tags, c) |
| 51 | + .AsFileWithName(), context, Id) |
| 52 | + .AddSource(context); |
| 53 | + } |
| 54 | + |
| 55 | + private static string GetContent(AdditionalText additionalText, CancellationToken cancellationToken = default) |
| 56 | + { |
| 57 | + return additionalText.Path.StartsWith("http", StringComparison.OrdinalIgnoreCase) |
| 58 | + ? Task.Run(() => new HttpClient().GetStringAsync(new Uri(additionalText.Path)), cancellationToken).Result |
| 59 | + : additionalText.GetText(cancellationToken)?.ToString() ?? string.Empty; |
| 60 | + } |
| 61 | + |
| 62 | + #endregion |
| 63 | +} |
0 commit comments