1+ using System . CommandLine ;
2+ using Microsoft . OpenApi ;
3+ using Microsoft . OpenApi . Extensions ;
4+ using OpenApiGenerator . Core . Extensions ;
5+
6+ namespace OpenApiGenerator . Cli . Commands ;
7+
8+ public class SimplifyCommand : Command
9+ {
10+ public SimplifyCommand ( ) : base ( name : "simplify" , description : "Simplifies OpenAPI spec." )
11+ {
12+ var inputOption = new Argument < string > (
13+ name : "input" ,
14+ getDefaultValue : ( ) => string . Empty ,
15+ description : "Input file path" ) ;
16+ var outputOption = new Option < string > (
17+ aliases : [ "--output" , "-o" ] ,
18+ getDefaultValue : ( ) => "simplified.yaml" ,
19+ description : "Output file path" ) ;
20+ AddArgument ( inputOption ) ;
21+ AddOption ( outputOption ) ;
22+
23+ this . SetHandler (
24+ HandleAsync ,
25+ inputOption ,
26+ outputOption ) ;
27+ }
28+
29+ private static async Task HandleAsync (
30+ string inputPath ,
31+ string outputPath )
32+ {
33+ Console . WriteLine ( $ "Loading { inputPath } ...") ;
34+
35+ using var client = new HttpClient ( ) ;
36+ var yamlOrJson = inputPath . StartsWith ( "http" , StringComparison . OrdinalIgnoreCase )
37+ ? await client . GetStringAsync ( new Uri ( inputPath ) ) . ConfigureAwait ( false )
38+ : await File . ReadAllTextAsync ( inputPath ) . ConfigureAwait ( false ) ;
39+ var openApiDocument = yamlOrJson . GetOpenApiDocument ( ) ;
40+
41+ Console . WriteLine ( "Simplifying..." ) ;
42+
43+ openApiDocument = openApiDocument . Simplify ( ) ;
44+
45+ var text = Path . GetExtension ( outputPath ) . ToUpperInvariant ( ) switch
46+ {
47+ ".JSON" => openApiDocument . SerializeAsJson ( OpenApiSpecVersion . OpenApi3_0 ) ,
48+ _ => openApiDocument . SerializeAsYaml ( OpenApiSpecVersion . OpenApi3_0 ) ,
49+ } ;
50+
51+ await File . WriteAllTextAsync ( outputPath , text ) . ConfigureAwait ( false ) ;
52+
53+ Console . WriteLine ( "Done." ) ;
54+ }
55+ }
0 commit comments