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

Add Powershell script parameters #2

Merged
merged 3 commits into from
Dec 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
46 changes: 35 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,31 +104,55 @@ Which will produce the following files:

In this example, the contents of `PostAddPet.ps1` looks like this:

```pwsh
curl -X 'POST' 'https://petstore3.swagger.io/api/v3/pet' \
-H 'Accept: application/json' \
-H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9' \
-H 'Content-Type: application/json' \
```powershell
<#
Request: POST /pet
Summary: Add a new pet to the store
Description: Add a new pet to the store
#>

curl -X POST https://petstore3.swagger.io/api/v3/pet `
-H 'Accept: application/json' `
-H 'Content-Type: application/json' `
-d '{
"id": 10,
"name": "doggie",
"id": 0,
"name": "name",
"category": {
"id": 1,
"name": "Dogs"
"id": 0,
"name": "name"
},
"photoUrls": [
"string"
""
],
"tags": [
{
"id": 0,
"name": "string"
"name": "name"
}
],
"status": "available"
}'
```

The generated script will contain mandatory parameters for operations where the path contains parameters, it will look something like this:

```powershell
<#
Request: GET /pet/{petId}
Summary: Find pet by ID
Description: Returns a single pet
#>
param(
<# ID of pet to return #>
[Parameter(Mandatory=$True)]
[String] $petId
)

curl -X GET https://petstore3.swagger.io/api/v3/pet/$petId `
-H 'Accept: application/json' `
-H 'Content-Type: application/json'
```

Here's an advanced example of generating cURL requests for a REST API hosted on Microsoft Azure that uses the Microsoft Entra ID service as an STS. For this example, I use PowerShell and Azure CLI to retrieve an access token for the user I'm currently logged in with.

```powershell
Expand Down
72 changes: 47 additions & 25 deletions src/CurlGenerator.Core/ScriptFileGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,11 @@ private static string GenerateRequest(
{
var code = new StringBuilder();
AppendSummary(verb, kv, operation, code);
code.AppendLine($"curl -X {verb.ToUpperInvariant()} {baseUrl}{kv.Key} `");
AppendParameters(verb, kv, operation, code);

var route = kv.Key.Replace("{", "$").Replace("}", null);
code.AppendLine($"curl -X {verb.ToUpperInvariant()} {baseUrl}{route} `");

code.AppendLine($" -H 'Accept: {settings.ContentType}' `");
code.AppendLine($" -H 'Content-Type: {settings.ContentType}' `");

Expand All @@ -112,47 +116,65 @@ private static string GenerateRequest(
return code.ToString();
}

private static void AppendSummary(
private static void AppendParameters(
string verb,
KeyValuePair<string, OpenApiPathItem> kv,
OpenApiOperation operation,
StringBuilder code)
{
const int padding = 2;
const string summary = "### Summary: ";
const string description = "### Description: ";

var request = $"### Request: {verb.ToUpperInvariant()} {kv.Key}";
var length = request.Length + padding;
length = Math.Max(
length,
Math.Max(
(operation.Summary?.Length ?? 0) + summary.Length + padding,
(operation.Description?.Length ?? 0) + description.Length + padding));

for (var i = 0; i < length; i++)
var parameters = operation
.Parameters
.Where(c => c.Kind is OpenApiParameterKind.Path or OpenApiParameterKind.Query)
.ToArray();

if (parameters.Length == 0)
{
code.Insert(0, "#");
code.AppendLine();
return;
}

code.AppendLine("param(");

foreach (var parameter in parameters)
{
code.AppendLine(
parameter.Description is null
? $"""
[Parameter(Mandatory=$True)]
[String] ${parameter.Name},
"""
: $"""
<# {parameter.Description} #>
[Parameter(Mandatory=$True)]
[String] ${parameter.Name},
""");
code.AppendLine();
}
code.Remove(code.Length - 5, 3);

code.AppendLine(")");
code.AppendLine();
code.AppendLine(request);
}

private static void AppendSummary(
string verb,
KeyValuePair<string, OpenApiPathItem> kv,
OpenApiOperation operation,
StringBuilder code)
{
code.AppendLine("<#");
code.AppendLine($" Request: {verb.ToUpperInvariant()} {kv.Key}");

if (!string.IsNullOrWhiteSpace(operation.Summary))
{
code.AppendLine($"{summary}{operation.Summary}");
code.AppendLine($" Summary: {operation.Summary}");
}

if (!string.IsNullOrWhiteSpace(operation.Description))
{
code.AppendLine($"{description}{operation.Description}");
}

for (var i = 0; i < length; i++)
{
code.Insert(code.Length, "#");
code.AppendLine($" Description: {operation.Description}");
}

code.AppendLine(Environment.NewLine);
code.AppendLine("#>");
}
}
4 changes: 2 additions & 2 deletions src/CurlGenerator.Tests/SwaggerPetstoreTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public async Task Can_Generate_Code(Samples version, string filename, OutputType
generateCode.Should().NotBeNull();
generateCode.Files.Should().NotBeNullOrEmpty();
generateCode.Files
.All(file => file.Content.Count(c => c == '#') >= 6)
.All(file => file.Content.Count(c => c == '#') >= 2)
.Should()
.BeTrue();
}
Expand Down Expand Up @@ -69,7 +69,7 @@ public async Task Can_Generate_Code_From_Url(string url, OutputType outputType)
generateCode.Should().NotBeNull();
generateCode.Files.Should().NotBeNullOrEmpty();
generateCode.Files
.All(file => file.Content.Count(c => c == '#') >= 6)
.All(file => file.Content.Count(c => c == '#') >= 2)
.Should()
.BeTrue();
}
Expand Down
46 changes: 35 additions & 11 deletions src/CurlGenerator/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,31 +87,55 @@ Which will produce the following files:

In this example, the contents of `PostAddPet.ps1` looks like this:

```pwsh
curl -X 'POST' 'https://petstore3.swagger.io/api/v3/pet' \
-H 'Accept: application/json' \
-H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9' \
-H 'Content-Type: application/json' \
```powershell
<#
Request: POST /pet
Summary: Add a new pet to the store
Description: Add a new pet to the store
#>

curl -X POST https://petstore3.swagger.io/api/v3/pet `
-H 'Accept: application/json' `
-H 'Content-Type: application/json' `
-d '{
"id": 10,
"name": "doggie",
"id": 0,
"name": "name",
"category": {
"id": 1,
"name": "Dogs"
"id": 0,
"name": "name"
},
"photoUrls": [
"string"
""
],
"tags": [
{
"id": 0,
"name": "string"
"name": "name"
}
],
"status": "available"
}'
```

The generated script will contain mandatory parameters for operations where the path contains parameters, it will look something like this:

```powershell
<#
Request: GET /pet/{petId}
Summary: Find pet by ID
Description: Returns a single pet
#>
param(
<# ID of pet to return #>
[Parameter(Mandatory=$True)]
[String] $petId
)

curl -X GET https://petstore3.swagger.io/api/v3/pet/$petId `
-H 'Accept: application/json' `
-H 'Content-Type: application/json'
```

Here's an advanced example of generating `.ps1` files for a REST API hosted on Microsoft Azure that uses the Microsoft Entra ID service as an STS. For this example, I use PowerShell and Azure CLI to retrieve an access token for the user I'm currently logged in with.

```powershell
Expand Down
Loading