Skip to content

Commit

Permalink
cli: Added simplify command.
Browse files Browse the repository at this point in the history
  • Loading branch information
HavenDV committed Sep 7, 2024
1 parent 09a4a71 commit 185df50
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 1 deletion.
55 changes: 55 additions & 0 deletions src/libs/OpenApiGenerator.Cli/Commands/SimplifyCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
using System.CommandLine;
using Microsoft.OpenApi;
using Microsoft.OpenApi.Extensions;
using OpenApiGenerator.Core.Extensions;

namespace OpenApiGenerator.Cli.Commands;

public class SimplifyCommand : Command
{
public SimplifyCommand() : base(name: "simplify", description: "Simplifies OpenAPI spec.")
{
var inputOption = new Argument<string>(
name: "input",
getDefaultValue: () => string.Empty,
description: "Input file path");
var outputOption = new Option<string>(
aliases: ["--output", "-o"],
getDefaultValue: () => "simplified.yaml",
description: "Output file path");
AddArgument(inputOption);
AddOption(outputOption);

this.SetHandler(
HandleAsync,
inputOption,
outputOption);
}

private static async Task HandleAsync(
string inputPath,
string outputPath)
{
Console.WriteLine($"Loading {inputPath}...");

using var client = new HttpClient();
var yamlOrJson = inputPath.StartsWith("http", StringComparison.OrdinalIgnoreCase)
? await client.GetStringAsync(new Uri(inputPath)).ConfigureAwait(false)
: await File.ReadAllTextAsync(inputPath).ConfigureAwait(false);
var openApiDocument = yamlOrJson.GetOpenApiDocument();

Console.WriteLine("Simplifying...");

openApiDocument = openApiDocument.Simplify();

var text = Path.GetExtension(outputPath).ToUpperInvariant() switch
{
".JSON" => openApiDocument.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0),
_ => openApiDocument.SerializeAsYaml(OpenApiSpecVersion.OpenApi3_0),
};

await File.WriteAllTextAsync(outputPath, text).ConfigureAwait(false);

Console.WriteLine("Done.");
}
}
1 change: 1 addition & 0 deletions src/libs/OpenApiGenerator.Cli/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@
var rootCommand = new RootCommand(
description: "CLI tool to use OpenApiGenerator");
rootCommand.AddCommand(new GenerateCommand());
rootCommand.AddCommand(new SimplifyCommand());

return await rootCommand.InvokeAsync(args).ConfigureAwait(false);
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public class CliTests
[DataRow("twitch.json")]
[DataRow("https://dedoose-rest-api.onrender.com/swagger/v1/swagger.json")]
[DataRow("together.yaml")]
public async Task Run(string spec)
public async Task Generate(string spec)
{
var tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
try
Expand Down

0 comments on commit 185df50

Please sign in to comment.