|
| 1 | +using System.CommandLine; |
| 2 | +using System.Text; |
| 3 | +using HotChocolate.Fusion.CommandLine.Helpers; |
| 4 | +using HotChocolate.Language; |
| 5 | +using HotChocolate.Language.Utilities; |
| 6 | +using HotChocolate.Utilities; |
| 7 | + |
| 8 | +namespace HotChocolate.Fusion.CommandLine.Commands; |
| 9 | + |
| 10 | +internal sealed class ExportSchemaCommand : Command |
| 11 | +{ |
| 12 | + public ExportSchemaCommand() : base("schema") |
| 13 | + { |
| 14 | + var fusionPackageFile = new Option<FileInfo?>("--package-file"); |
| 15 | + fusionPackageFile.AddAlias("--package"); |
| 16 | + fusionPackageFile.AddAlias("-p"); |
| 17 | + |
| 18 | + var schemaFile = new Option<FileInfo?>("--file"); |
| 19 | + schemaFile.AddAlias("-f"); |
| 20 | + |
| 21 | + AddOption(fusionPackageFile); |
| 22 | + AddOption(schemaFile); |
| 23 | + |
| 24 | + this.SetHandler( |
| 25 | + ExecuteAsync, |
| 26 | + Bind.FromServiceProvider<IConsole>(), |
| 27 | + fusionPackageFile, |
| 28 | + schemaFile, |
| 29 | + Bind.FromServiceProvider<CancellationToken>()); |
| 30 | + } |
| 31 | + |
| 32 | + private static async Task<int> ExecuteAsync( |
| 33 | + IConsole console, |
| 34 | + FileInfo? packageFile, |
| 35 | + FileInfo? schemaFile, |
| 36 | + CancellationToken cancellationToken) |
| 37 | + { |
| 38 | + packageFile ??= |
| 39 | + new FileInfo(System.IO.Path.Combine(Environment.CurrentDirectory, "gateway" + Extensions.FusionPackage)); |
| 40 | + |
| 41 | + if (!packageFile.Exists) |
| 42 | + { |
| 43 | + if (Directory.Exists(packageFile.FullName)) |
| 44 | + { |
| 45 | + packageFile = |
| 46 | + new FileInfo(System.IO.Path.Combine(packageFile.FullName, "gateway" + Extensions.FusionPackage)); |
| 47 | + } |
| 48 | + else if (!packageFile.Extension.EqualsOrdinal(Extensions.FusionPackage) && |
| 49 | + !packageFile.Extension.EqualsOrdinal(Extensions.ZipPackage)) |
| 50 | + { |
| 51 | + packageFile = new FileInfo(packageFile.FullName + Extensions.FusionPackage); |
| 52 | + } |
| 53 | + |
| 54 | + if (!packageFile.Exists) |
| 55 | + { |
| 56 | + console.WriteLine($"The package file `{packageFile.FullName}` does not exist."); |
| 57 | + return 1; |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + schemaFile ??= new FileInfo(System.IO.Path.Combine(packageFile.DirectoryName!, "schema.graphql")); |
| 62 | + |
| 63 | + await using var package = FusionGraphPackage.Open(packageFile.FullName); |
| 64 | + |
| 65 | + var schema = await package.GetSchemaAsync(cancellationToken); |
| 66 | + var options = new SyntaxSerializerOptions { Indented = true, MaxDirectivesPerLine = 0, }; |
| 67 | + |
| 68 | + await File.WriteAllTextAsync(schemaFile.FullName, schema.ToString(options), |
| 69 | + new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), cancellationToken); |
| 70 | + |
| 71 | + return 0; |
| 72 | + } |
| 73 | +} |
0 commit comments