Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,11 @@
-->
<OpenApiDocumentsDirectory
Condition=" '$(OpenApiDocumentsDirectory)' == '' ">$(BaseIntermediateOutputPath)</OpenApiDocumentsDirectory>

<!--
The environment name to use when generating OpenAPI documents. This sets the ASPNETCORE_ENVIRONMENT
environment variable when executing the application to generate documents.
-->
<OpenApiGenerateEnvironment Condition=" '$(OpenApiGenerateEnvironment)' == '' " />
</PropertyGroup>
</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
<_DotNetGetDocumentCommand Condition=" '$(PlatformTarget)' != '' ">$(_DotNetGetDocumentCommand) --platform "$(PlatformTarget)"</_DotNetGetDocumentCommand>
<_DotNetGetDocumentCommand Condition=" '$(PlatformTarget)' == '' AND '$(Platform)' != '' ">$(_DotNetGetDocumentCommand) --platform "$(Platform)"</_DotNetGetDocumentCommand>
<_DotNetGetDocumentCommand Condition=" '$(RuntimeIdentifier)' != '' ">$(_DotNetGetDocumentCommand) --runtime "$(RuntimeIdentifier) --self-contained"</_DotNetGetDocumentCommand>
<_DotNetGetDocumentCommand Condition=" '$(OpenApiGenerateEnvironment)' != '' ">$(_DotNetGetDocumentCommand) --environment "$(OpenApiGenerateEnvironment)"</_DotNetGetDocumentCommand>
<_DotNetGetDocumentCommand>$(_DotNetGetDocumentCommand) $(OpenApiGenerateDocumentsOptions)</_DotNetGetDocumentCommand>
</PropertyGroup>

Expand Down
29 changes: 27 additions & 2 deletions src/Tools/GetDocumentInsider/sample/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,21 @@ private static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOpenApi();
builder.Services.AddOpenApi("internal");
builder.Services.AddOpenApi(options =>
{
options.AddDocumentTransformer((document, context, cancellationToken) =>
{
return TransformDocument(document, builder);
});
});

builder.Services.AddOpenApi("internal", options =>
{
options.AddDocumentTransformer((document, context, cancellationToken) =>
{
return TransformDocument(document, builder);
});
});

var app = builder.Build();

Expand All @@ -22,4 +35,16 @@ private static void Main(string[] args)

app.Run();
}

private static Task TransformDocument(
Microsoft.OpenApi.OpenApiDocument document,
WebApplicationBuilder builder)
{
var env = builder.Environment.EnvironmentName;
if (!string.IsNullOrEmpty(env))
{
document.Info.Summary += $"Running in '{env}' environment";
}
return Task.CompletedTask;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ internal sealed class GetDocumentCommand : ProjectCommandBase
private CommandOption _openApiVersion;
private CommandOption _documentName;
private CommandOption _fileName;
private CommandOption _environment;

public GetDocumentCommand(IConsole console) : base(console)
{
Expand All @@ -34,6 +35,7 @@ public override void Configure(CommandLineApplication command)
_openApiVersion = command.Option("--openapi-version <Version>", Resources.OpenApiVersionDescription);
_documentName = command.Option("--document-name <Name>", Resources.DocumentNameDescription);
_fileName = command.Option("--file-name <Name>", Resources.FileNameDescription);
_environment = command.Option("--environment <Name>", Resources.EnvironmentDescription);
}

protected override void Validate()
Expand Down Expand Up @@ -144,7 +146,8 @@ protected override int Execute()
DocumentName = _documentName.Value(),
ProjectName = ProjectName.Value(),
Reporter = Reporter,
FileName = _fileName.Value()
FileName = _fileName.Value(),
Environment = _environment.Value()
};

return new GetDocumentCommandWorker(context).Process();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,11 @@ public class GetDocumentCommandContext
/// </summary>
public string FileName { get; set; }

/// <summary>
/// The environment name to use when executing the application.
/// Sets the ASPNETCORE_ENVIRONMENT environment variable.
/// </summary>
public string Environment { get; set; }

public IReporter Reporter { get; set; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,15 @@ void OnEntryPointExit(Exception exception)

try
{
// Build the arguments array for the host factory
var hostArgs = new List<string> { $"--{HostDefaults.ApplicationKey}={assemblyName}" };
if (!string.IsNullOrEmpty(_context.Environment))
{
hostArgs.Add($"--environment={_context.Environment}");
}

// Retrieve the service provider from the target host.
var services = ((IHost)factory([$"--{HostDefaults.ApplicationKey}={assemblyName}"])).Services;
var services = ((IHost)factory(hostArgs.ToArray())).Services;
if (services == null)
{
_reporter.WriteError(Resources.FormatServiceProviderNotFound(
Expand Down Expand Up @@ -159,7 +166,14 @@ void OnEntryPointExit(Exception exception)
return 4;
}

var services = serviceFactory(Array.Empty<string>());
// Build the arguments array for the service factory
var hostArgs = new List<string>();
if (!string.IsNullOrEmpty(_context.Environment))
{
hostArgs.Add($"--environment={_context.Environment}");
}

var services = serviceFactory(hostArgs.ToArray());
if (services == null)
{
_reporter.WriteError(Resources.FormatServiceProviderNotFound(
Expand Down
3 changes: 3 additions & 0 deletions src/Tools/GetDocumentInsider/src/Resources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,9 @@
<data name="DocumentNameDescription" xml:space="preserve">
<value>The name of the OpenAPI document to generate. Optional.</value>
</data>
<data name="EnvironmentDescription" xml:space="preserve">
<value>The environment name to use (e.g., Development, Production).</value>
</data>
<data name="InvalidOpenApiVersion" xml:space="preserve">
<value>Invalid OpenAPI spec version '{0}' provided. Falling back to default: v3.0.</value>
</data>
Expand Down
30 changes: 30 additions & 0 deletions src/Tools/GetDocumentInsider/tests/GetDocumentTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -237,4 +237,34 @@ public void GetDocument_WithEmptyFileName_Works()
Assert.True(File.Exists(Path.Combine(outputPath.FullName, "Sample.json")));
Assert.True(File.Exists(Path.Combine(outputPath.FullName, "Sample_internal.json")));
}

[Theory]
[InlineData("Development")]
[InlineData("Staging")]
[InlineData("Production")]
public void GetDocument_WithDifferentEnvironments_Works(string environment)
{
// Arrange
var outputPath = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()));
var app = new Program(_console);

// Act
app.Run([
"--assembly", _testAppAssembly,
"--project", _testAppProject,
"--framework", _testAppFrameworkMoniker,
"--tools-directory", _toolsDirectory,
"--output", outputPath.FullName,
"--file-list", Path.Combine(outputPath.FullName, "file-list.cache"),
"--environment", environment
], new GetDocumentCommand(_console), throwOnUnexpectedArg: false);

// Assert
using var stream = new MemoryStream(File.ReadAllBytes(Path.Combine(outputPath.FullName, "Sample.json")));
var result = OpenApiDocument.Load(stream, "json");
Assert.Equal(OpenApiSpecVersion.OpenApi3_1, result.Diagnostic.SpecificationVersion);

// Verify environment appears in summary - this proves --environment parameter is used
Assert.Equal($"Running in '{environment}' environment", result.Document.Info.Summary);
}
}
7 changes: 7 additions & 0 deletions src/Tools/dotnet-getdocument/src/Commands/InvokeCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,13 @@ protected override int Execute()
args.Add("--tools-directory");
args.Add(toolsDirectory);

var environment = _projectOptions.Environment.Value();
if (!string.IsNullOrEmpty(environment))
{
args.Add("--environment");
args.Add(environment);
}

if (ReporterExtensions.PrefixOutput)
{
args.Add("--prefix-output");
Expand Down
3 changes: 3 additions & 0 deletions src/Tools/dotnet-getdocument/src/ProjectOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ internal sealed class ProjectOptions

public CommandOption TargetFramework { get; private set; }

public CommandOption Environment { get; private set; }

public void Configure(CommandLineApplication command)
{
AssemblyPath = command.Option("--assembly <Path>", Resources.AssemblyDescription);
Expand All @@ -27,6 +29,7 @@ public void Configure(CommandLineApplication command)
Platform = command.Option("--platform <Target>", Resources.PlatformDescription);
ProjectName = command.Option("--project <Name>", Resources.ProjectDescription);
RuntimeFrameworkVersion = command.Option("--runtime <RUNTIME_IDENTIFIER>", Resources.RuntimeDescription);
Environment = command.Option("--environment <Name>", Resources.EnvironmentDescription);
}

public void Validate()
Expand Down
3 changes: 3 additions & 0 deletions src/Tools/dotnet-getdocument/src/Resources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,9 @@
<data name="AssemblyDescription" xml:space="preserve">
<value>The assembly path to use. Required.</value>
</data>
<data name="EnvironmentDescription" xml:space="preserve">
<value>The environment name to use (e.g., Development, Production).</value>
</data>
<data name="QuietAndVerboseSpecified" xml:space="preserve">
<value>Cannot specify both '--quiet' and '--verbose' options.</value>
</data>
Expand Down
Loading