This commit is contained in:
Thorsten Sommer 2024-02-17 22:35:45 +01:00
parent eff1df2df3
commit c7dda52a49
Signed by: tsommer
GPG Key ID: 371BBA77A02C0108
14 changed files with 284 additions and 93 deletions

45
.gitignore vendored Normal file
View File

@ -0,0 +1,45 @@
### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# Cursive Clojure plugin
.idea/replstate.xml
# Editor-based Rest Client
.idea/httpRequests
### DotnetCore template
# .NET Core build folders
bin/
obj/

View File

@ -0,0 +1,13 @@
# Default ignored files
/shelf/
/workspace.xml
# Rider ignored files
/projectSettingsUpdater.xml
/modules.xml
/contentModel.xml
/.idea.OpenAPI Client Builder.iml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

View File

@ -0,0 +1 @@
OpenAPI Client Builder

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding" addBOMForNewFiles="with BOM under Windows, with no BOM otherwise" />
</project>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="UserContentModel">
<attachedFolders />
<explicitIncludes />
<explicitExcludes />
</component>
</project>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

21
LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2024 Thorsten Sommer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,16 @@

Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Terminal", "Terminal\Terminal.csproj", "{016364D8-CD2C-4919-9FD7-68B7449C1C7C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{016364D8-CD2C-4919-9FD7-68B7449C1C7C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{016364D8-CD2C-4919-9FD7-68B7449C1C7C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{016364D8-CD2C-4919-9FD7-68B7449C1C7C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{016364D8-CD2C-4919-9FD7-68B7449C1C7C}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal

View File

@ -1,93 +0,0 @@
# OpenAPI Client Builder
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://devops.tsommer.org/open-source/dotnet/open-api-client-builder.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://devops.tsommer.org/open-source/dotnet/open-api-client-builder/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.

View File

@ -0,0 +1,57 @@
using System.Diagnostics.CodeAnalysis;
using System.Text;
using Cocona;
using NJsonSchema.CodeGeneration.CSharp;
using NSwag;
using NSwag.CodeGeneration.CSharp;
using Terminal.Validation;
namespace Terminal.Commands;
[SuppressMessage("ReSharper", "ClassNeverInstantiated.Global")]
public class GenerateCommands
{
[Command(Aliases = ["generate"], Description = "Generate a client from an OpenAPI document")]
public async Task Gen(
[Option(shortName: 'a', Description = "The address of the OpenAPI document, e.g. 'https://petstore.swagger.io/v2/swagger.json'")]
Uri address,
[Option(shortName: 'd', Description = "The destination file, e.g. 'PetStoreClient.cs'. You can use a relative or absolute path and use any environment variables.")]
[ValidPath]
string destinationFile,
[Option(shortName: 'n', Description = "The namespace of the generated client, e.g. 'MyApp.API.PetStoreClient'")]
string nameSpace = "API_Client",
[Option(shortName: 'c', Description = "The class name of the generated client, e.g. 'PetStoreClient'. You might want to use '{controller}' as a placeholder for the controller name.")]
string className = "{controller}Client",
[Option(shortName: 'b', Description = "Expose the base URL as a property in the generated client? (Default: false)")]
bool exposeBaseUrl = false,
[Option(shortName: 'i', Description = "The base interface of the generated client(s), e.g. 'IPetStoreClient'")]
string? baseInterface = null)
{
using var httpClient = new HttpClient();
var result = await httpClient.GetAsync(address);
var openAPI = await OpenApiDocument.FromJsonAsync(await result.Content.ReadAsStringAsync());
var generator = new CSharpClientGenerator(openAPI, new CSharpClientGeneratorSettings
{
UseBaseUrl = exposeBaseUrl,
ClientBaseInterface = baseInterface,
GenerateClientInterfaces = baseInterface is not null,
ClassName = className,
CSharpGeneratorSettings =
{
Namespace = nameSpace,
JsonLibrary = CSharpJsonLibrary.SystemTextJson,
}
});
var apiClientCode = generator.GenerateFile();
destinationFile = Environment.ExpandEnvironmentVariables(destinationFile);
await File.WriteAllTextAsync(destinationFile, apiClientCode, Encoding.UTF8);
Console.WriteLine($"Generated client(s) for '{address}' and saved it to '{destinationFile}'");
}
}

View File

@ -0,0 +1,16 @@
using System.Diagnostics.CodeAnalysis;
using Cocona;
namespace Terminal.Commands;
[SuppressMessage("ReSharper", "ClassNeverInstantiated.Global")]
public class VersionCommands
{
[Command(Aliases = ["ver"], Description = "Show the version of the OpenAPI Client Builder")]
public void Version() => ShowVersion();
public static void ShowVersion()
{
Console.WriteLine($"OpenAPI Client Builder v1.0.0, built using .NET {Environment.Version}.");
}
}

42
Terminal/Program.cs Normal file
View File

@ -0,0 +1,42 @@
using Cocona;
using Cocona.Application;
using Cocona.Command;
using Cocona.Command.Features;
using Cocona.Help;
using Terminal.Commands;
var builder = CoconaApp.CreateBuilder(args, options =>
{
options.TreatPublicMethodsAsCommands = false;
options.EnableShellCompletionSupport = true;
});
var app = builder.Build();
app.AddCommands<GenerateCommands>();
app.AddCommands<VersionCommands>();
app.AddCommand(PrimaryCommand);
await app.RunAsync();
return;
//
// We define the primary command here, to show our own version information when
// the `--version` option is used, and to show the help index when no option is
// specified.
//
void PrimaryCommand(
bool version,
[FromService] ICoconaAppContextAccessor appContext,
[FromService] ICoconaCommandProvider commandProvider,
[FromService] ICoconaHelpRenderer helpRenderer,
[FromService] ICoconaCommandHelpProvider commandHelpProvider)
{
if (version)
{
VersionCommands.ShowVersion();
return;
}
var commandStack = appContext.Current!.Features.Get<ICoconaCommandFeature>().CommandStack;
Console.Write(helpRenderer.Render(commandHelpProvider.CreateCommandsIndexHelp(commandProvider.GetCommandCollection(), commandStack)));
}

23
Terminal/Terminal.csproj Normal file
View File

@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<AssemblyName>openClientBuilder</AssemblyName>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>latest</LangVersion>
<PublishSingleFile>true</PublishSingleFile>
<SelfContained>true</SelfContained>
<PublishReadyToRun>true</PublishReadyToRun>
<PublishTrimmed>true</PublishTrimmed>
<TrimMode>partial</TrimMode>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Cocona" Version="2.2.0" />
<PackageReference Include="NSwag.CodeGeneration.CSharp" Version="14.0.3" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,32 @@
using System.ComponentModel.DataAnnotations;
namespace Terminal.Validation;
public class ValidPathAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object? value, ValidationContext validationContext)
{
if (value is string path)
{
try
{
path = Environment.ExpandEnvironmentVariables(path);
var info = new FileInfo(path);
if (info.Exists)
return ValidationResult.Success!;
using (var stream = info.Create())
stream.Close();
info.Delete();
return ValidationResult.Success!;
}
catch
{
return new ValidationResult($"The path '{path}' is not valid.");
}
}
return new ValidationResult($"The path '{value}' is not valid.");
}
}