Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds support for generating Mermaid diagrams from APIs #1113

Merged
merged 36 commits into from
Jan 17, 2023
Merged
Show file tree
Hide file tree
Changes from 25 commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
e517053
Added show command
darrelmiller Dec 23, 2022
49a12f3
Moved mermaid writer into OpenApiUrlTreeNode and fixed more sanitizat…
darrelmiller Dec 23, 2022
8781884
Added shapes for better accessibility
darrelmiller Dec 24, 2022
0bc1726
Update to do a unnecessary using
darrelmiller Dec 25, 2022
e8061ac
Update src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs
darrelmiller Dec 25, 2022
5a7146c
Update src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs
darrelmiller Dec 25, 2022
fc3ba5e
Added a bunch of usings and removed an unnecessary flush to address c…
darrelmiller Dec 25, 2022
6c57e8d
Fixed broken order method
darrelmiller Dec 25, 2022
9e2ff51
Update src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs
darrelmiller Dec 28, 2022
efeeca7
Update src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs
darrelmiller Dec 28, 2022
5d87820
Update src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs
darrelmiller Dec 28, 2022
674fe14
Changed mermaid styles to make them readonly
darrelmiller Jan 3, 2023
931270f
Fixed data in broken test
darrelmiller Jan 4, 2023
079da0f
Updated public API
darrelmiller Jan 4, 2023
3f59784
Refactored OpenAPIService to remove duplicate code
darrelmiller Jan 5, 2023
e0d08f8
Added tests for mermaid diagrams
darrelmiller Jan 8, 2023
b61edcf
Updated diagram test to cover more scenarios
darrelmiller Jan 9, 2023
6a53f24
Merge remote-tracking branch 'origin/vnext' into dm/show
darrelmiller Jan 11, 2023
8a9305b
Added test for show command
darrelmiller Jan 11, 2023
b0af526
Refactored to improve test coverage
darrelmiller Jan 12, 2023
776e98f
Change test to call sync invoke
darrelmiller Jan 12, 2023
5bc0bd4
Added back missing parameter config options in parseopenapi
darrelmiller Jan 12, 2023
5ee6095
Updated SanitizeMermaidNode to handle cases found in Microsoft Graph …
darrelmiller Jan 15, 2023
a7c4983
Removed Task.Delay as no longer necessary. #1127
darrelmiller Jan 15, 2023
7aac03f
Updated commands to enable reading from CSDL url for both transform a…
darrelmiller Jan 15, 2023
8e2d470
Used random file in a hidi folder to address security concerns.
darrelmiller Jan 15, 2023
c23694c
Fixed code smell relating to LogError
darrelmiller Jan 15, 2023
6a3dd01
Added test to call Transform command directly so that code coverage w…
darrelmiller Jan 15, 2023
8ff70a1
Removed unnecessary test that was breaking
darrelmiller Jan 16, 2023
b95cda3
This time I included the change
darrelmiller Jan 16, 2023
230af2f
Added missing comments for public APIs
darrelmiller Jan 16, 2023
2b82a74
Added more tests to meet the coverage gods
darrelmiller Jan 16, 2023
4537239
More sacrifices made
darrelmiller Jan 16, 2023
96fae88
Will these be the tests that achieve the magical goal?
darrelmiller Jan 16, 2023
7638805
I am confidence I have enough tests now
darrelmiller Jan 16, 2023
a8a693d
Added a using to dispose a StreamReader
darrelmiller Jan 16, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions src/Microsoft.OpenApi.Hidi/Handlers/ShowCommandHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.

using System;
using System.CommandLine;
using System.CommandLine.Invocation;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace Microsoft.OpenApi.Hidi.Handlers
{
internal class ShowCommandHandler : ICommandHandler
{
public Option<string> DescriptionOption { get; set; }
public Option<FileInfo> OutputOption { get; set; }
public Option<LogLevel> LogLevelOption { get; set; }
public Option<string> CsdlOption { get; set; }
public Option<string> CsdlFilterOption { get; set; }


public int Invoke(InvocationContext context)
{
return InvokeAsync(context).GetAwaiter().GetResult();
}
public async Task<int> InvokeAsync(InvocationContext context)
{
string openapi = context.ParseResult.GetValueForOption(DescriptionOption);
FileInfo output = context.ParseResult.GetValueForOption(OutputOption);
LogLevel logLevel = context.ParseResult.GetValueForOption(LogLevelOption);
string csdlFilter = context.ParseResult.GetValueForOption(CsdlFilterOption);
string csdl = context.ParseResult.GetValueForOption(CsdlOption);
CancellationToken cancellationToken = (CancellationToken)context.BindingContext.GetService(typeof(CancellationToken));

using var loggerFactory = Logger.ConfigureLogger(logLevel);
var logger = loggerFactory.CreateLogger<OpenApiService>();
try
{
await OpenApiService.ShowOpenApiDocument(openapi, csdl, csdlFilter, output, logger, cancellationToken);

return 0;
}
catch (Exception ex)
{
#if DEBUG
logger.LogCritical(ex, ex.Message);
throw; // so debug tools go straight to the source of the exception when attached
#else
logger.LogCritical( ex.Message);
return 1;
#endif
}
Comment on lines +44 to +53

Check notice

Code scanning / CodeQL

Generic catch clause

Generic catch clause.
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public async Task<int> InvokeAsync(InvocationContext context)
var logger = loggerFactory.CreateLogger<OpenApiService>();
try
{
await OpenApiService.TransformOpenApiDocument(openapi, csdl, csdlFilter, output, cleanOutput, version, format, terseOutput, settingsFile, logLevel, inlineLocal, inlineExternal, filterbyoperationids, filterbytags, filterbycollection, cancellationToken);
await OpenApiService.TransformOpenApiDocument(openapi, csdl, csdlFilter, output, cleanOutput, version, format, terseOutput, settingsFile, inlineLocal, inlineExternal, filterbyoperationids, filterbytags, filterbycollection, logger, cancellationToken);

return 0;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public async Task<int> InvokeAsync(InvocationContext context)
var logger = loggerFactory.CreateLogger<OpenApiService>();
try
{
await OpenApiService.ValidateOpenApiDocument(openapi, logLevel, cancellationToken);
await OpenApiService.ValidateOpenApiDocument(openapi, logger, cancellationToken);
return 0;
}
catch (Exception ex)
Expand Down
455 changes: 278 additions & 177 deletions src/Microsoft.OpenApi.Hidi/OpenApiService.cs

Large diffs are not rendered by default.

48 changes: 36 additions & 12 deletions src/Microsoft.OpenApi.Hidi/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,17 @@ namespace Microsoft.OpenApi.Hidi
static class Program
{
static async Task Main(string[] args)
{
var rootCommand = new RootCommand() {};
{
var rootCommand = CreateRootCommand();

// Parse the incoming args and invoke the handler
await rootCommand.InvokeAsync(args);

}

internal static RootCommand CreateRootCommand()
{
var rootCommand = new RootCommand() { };

// command option parameters and aliases
var descriptionOption = new Option<string>("--openapi", "Input OpenAPI description file path or URL");
Expand Down Expand Up @@ -46,7 +55,7 @@ static async Task Main(string[] args)

var settingsFileOption = new Option<string>("--settings-path", "The configuration file with CSDL conversion settings.");
settingsFileOption.AddAlias("--sp");

var logLevelOption = new Option<LogLevel>("--log-level", () => LogLevel.Information, "The log level to use when logging messages to the main output.");
logLevelOption.AddAlias("--ll");

Expand All @@ -71,7 +80,7 @@ static async Task Main(string[] args)
logLevelOption
};

validateCommand.Handler = new ValidateCommandHandler
validateCommand.Handler = new ValidateCommandHandler
{
DescriptionOption = descriptionOption,
LogLevelOption = logLevelOption
Expand All @@ -88,7 +97,7 @@ static async Task Main(string[] args)
formatOption,
terseOutputOption,
settingsFileOption,
logLevelOption,
logLevelOption,
filterByOperationIdsOption,
filterByTagsOption,
filterByCollectionOption,
Expand All @@ -115,14 +124,29 @@ static async Task Main(string[] args)
InlineExternalOption = inlineExternalOption
};

var showCommand = new Command("show")
{
descriptionOption,
csdlOption,
csdlFilterOption,
logLevelOption,
outputOption,
cleanOutputOption
};

showCommand.Handler = new ShowCommandHandler
{
DescriptionOption = descriptionOption,
CsdlOption = csdlOption,
CsdlFilterOption = csdlFilterOption,
OutputOption = outputOption,
LogLevelOption = logLevelOption
};

rootCommand.Add(showCommand);
rootCommand.Add(transformCommand);
rootCommand.Add(validateCommand);

// Parse the incoming args and invoke the handler
await rootCommand.InvokeAsync(args);

//// Wait for logger to write messages to the console before exiting
await Task.Delay(10);
}
return rootCommand;
}
}
}
32 changes: 23 additions & 9 deletions src/Microsoft.OpenApi.Hidi/readme.md
Original file line number Diff line number Diff line change
@@ -1,24 +1,26 @@
# Overview
# Overview

Hidi is a command line tool that makes it easy to work with and transform OpenAPI documents. The tool enables you validate and apply transformations to and from different file formats using various commands to do different actions on the files.

## Capabilities

Hidi has these key capabilities that enable you to build different scenarios off the tool

• Validation of OpenAPI files
• Conversion of OpenAPI files into different file formats: convert files from JSON to YAML, YAML to JSON
• Slice or filter OpenAPI documents to smaller subsets using operationIDs and tags
• Generate a Mermaid diagram of the API from an OpenAPI document


## Installation
## Installation

Install [Microsoft.OpenApi.Hidi](https://www.nuget.org/packages/Microsoft.OpenApi.Hidi/1.0.0-preview4) package from NuGet by running the following command:

### .NET CLI(Global)
### .NET CLI(Global)

1. dotnet tool install --global Microsoft.OpenApi.Hidi --prerelease


### .NET CLI(local)
### .NET CLI(local)

1. dotnet new tool-manifest #if you are setting up the OpenAPI.NET repo
2. dotnet tool install --local Microsoft.OpenApi.Hidi --prerelease
Expand All @@ -27,14 +29,17 @@ Install [Microsoft.OpenApi.Hidi](https://www.nuget.org/packages/Microsoft.OpenAp


## How to use Hidi

Once you've installed the package locally, you can invoke the Hidi by running: hidi [command].
You can access the list of command options we have by running hidi -h
The tool avails the following commands:

• Validate
• Transform
• Show

### Validate
### Validate

This command option accepts an OpenAPI document as an input parameter, visits multiple OpenAPI elements within the document and returns statistics count report on the following elements:

• Path Items
Expand All @@ -54,9 +59,10 @@ It accepts the following command:

**Example:** `hidi.exe validate --openapi C:\OpenApidocs\Mail.yml --loglevel trace`

Run validate -h to see the options available.

### Transform
Run validate -h to see the options available.

### Transform

Used to convert file formats from JSON to YAML and vice versa and performs slicing of OpenAPI documents.

This command accepts the following parameters:
Expand Down Expand Up @@ -90,3 +96,11 @@ This command accepts the following parameters:
hidi transform -cs dataverse.csdl --csdlFilter "appointments,opportunities" -o appointmentsAndOpportunities.yaml -ll trace

Run transform -h to see all the available usage options.

### Show

This command accepts an OpenAPI document as an input parameter and generates a Markdown file that contains a diagram of the API using Mermaid syntax.

**Examples:**

1. hidi show -d files\People.yml -o People.md -ll trace
Loading