Skip to content

Support customizing filename in M.E.ApiDescription.Server tool #56974

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

Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ internal sealed class GetDocumentCommand : ProjectCommandBase
private CommandOption _output;
private CommandOption _openApiVersion;
private CommandOption _documentName;
private CommandOption _fileName;

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

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

return new GetDocumentCommandWorker(context).Process();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,13 @@ public class GetDocumentCommandContext
// Generates all documents if not provided.
public string DocumentName { get; set; }

/// <summary>
/// The name of the generated OpenAPI document.
/// When the default document (v1) is generated, this maps
/// to {FileName}.json. For custom file names, this maps to
/// {FileName}_{DocumentName}.json.
/// </summary>
public string FileName { get; set; }

public IReporter Reporter { get; set; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
Expand Down Expand Up @@ -267,6 +267,12 @@ private bool GetDocuments(IServiceProvider services)
return false;
}

if (!string.IsNullOrWhiteSpace(_context.FileName) && !Regex.IsMatch(_context.FileName, "^([A-Za-z0-9-_]+)$"))
{
_reporter.WriteError(Resources.FileNameFormatInvalid);
return false;
}

// Write out the documents.
var found = false;
Directory.CreateDirectory(_context.OutputDirectory);
Expand All @@ -279,7 +285,8 @@ private bool GetDocuments(IServiceProvider services)
_context.OutputDirectory,
generateMethod,
service,
generateWithVersionMethod);
generateWithVersionMethod,
_context.FileName);
if (filePath == null)
{
return false;
Expand Down Expand Up @@ -308,7 +315,8 @@ private string GetDocument(
string outputDirectory,
MethodInfo generateMethod,
object service,
MethodInfo? generateWithVersionMethod)
MethodInfo? generateWithVersionMethod,
string fileName)
{
_reporter.WriteInformation(Resources.FormatGeneratingDocument(documentName));

Expand Down Expand Up @@ -352,7 +360,9 @@ private string GetDocument(
return null;
}

var filePath = GetDocumentPath(documentName, projectName, outputDirectory);
fileName = !string.IsNullOrWhiteSpace(fileName) ? fileName : projectName;

var filePath = GetDocumentPath(documentName, fileName, outputDirectory);
_reporter.WriteInformation(Resources.FormatWritingDocument(documentName, filePath));
try
{
Expand All @@ -371,13 +381,14 @@ private string GetDocument(
return filePath;
}

private static string GetDocumentPath(string documentName, string projectName, string outputDirectory)
private static string GetDocumentPath(string documentName, string fileName, string outputDirectory)
{
string path;

if (string.Equals(DefaultDocumentName, documentName, StringComparison.Ordinal))
{
// Leave default document name out of the filename.
path = projectName + JsonExtension;
path = fileName + JsonExtension;
}
else
{
Expand All @@ -392,7 +403,7 @@ private static string GetDocumentPath(string documentName, string projectName, s
sanitizedDocumentName = sanitizedDocumentName.Replace(InvalidFilenameString, DotString);
}

path = $"{projectName}_{documentName}{JsonExtension}";
path = $"{fileName}_{documentName}{JsonExtension}";
}

if (!string.IsNullOrEmpty(outputDirectory))
Expand Down
64 changes: 35 additions & 29 deletions src/Tools/GetDocumentInsider/src/Resources.resx
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema

<!--
Microsoft ResX Schema
Version 2.0

The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.

Example:

... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
Expand All @@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>

There are any number of "resheader" rows that contain simple
There are any number of "resheader" rows that contain simple
name/value pairs.

Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.

The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:

Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.

mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.

mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.

mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
Expand Down Expand Up @@ -209,4 +209,10 @@
<data name="VersionedGenerateMethod" xml:space="preserve">
<value>Using discovered `GenerateAsync` overload with version parameter.</value>
</data>
</root>
<data name="FileNameDescription" xml:space="preserve">
<value>The name of the generated OpenAPI document. When the default document (v1) is generated, this maps to {FileName}.json. For custom file names, this maps to {FileName}_{DocumentName}.json.</value>
</data>
<data name="FileNameFormatInvalid" xml:space="preserve">
<value>FileName format invalid, only Alphanumeric and "_ -" authorized</value>
</data>
</root>
82 changes: 82 additions & 0 deletions src/Tools/GetDocumentInsider/tests/GetDocumentTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -144,4 +144,86 @@ public void GetDocument_WithInvalidDocumentName_Errors()
Assert.False(File.Exists(Path.Combine(outputPath.FullName, "Sample_internal.json")));
Assert.False(File.Exists(Path.Combine(outputPath.FullName, "Sample_invalid.json")));
}

[Theory]
[InlineData("customFileName")]
[InlineData("custom-File_Name")]
[InlineData("custom_File-Name")]
[InlineData("custom1File2Name")]
public void GetDocument_WithValidFileName_Works(string fileName)
{
// 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"),
"--file-name", fileName
], new GetDocumentCommand(_console), throwOnUnexpectedArg: false);

// Assert
Assert.True(File.Exists(Path.Combine(outputPath.FullName, $"{fileName}.json")));
Assert.True(File.Exists(Path.Combine(outputPath.FullName, $"{fileName}_internal.json")));
Assert.False(File.Exists(Path.Combine(outputPath.FullName, "Sample.json")));
Assert.False(File.Exists(Path.Combine(outputPath.FullName, "Sample_internal.json")));
}

[Theory]
[InlineData("customFile=ù^*Name")]
[InlineData("&$*")]
public void GetDocument_WithInvalideFileName_Errors(string fileName)
{
// 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"),
"--file-name", fileName
], new GetDocumentCommand(_console), throwOnUnexpectedArg: false);

// Assert

Assert.Contains("FileName format invalid, only Alphanumeric and \"_ -\" authorized", _console.GetOutput());
Assert.False(File.Exists(Path.Combine(outputPath.FullName, $"{fileName}.json")));
Assert.False(File.Exists(Path.Combine(outputPath.FullName, "Sample.json")));
Assert.False(File.Exists(Path.Combine(outputPath.FullName, "Sample_internal.json")));
}

[Fact]
public void GetDocument_WithEmptyFileName_Works()
{
// 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"),
"--file-name", ""
], new GetDocumentCommand(_console), throwOnUnexpectedArg: false);

// Assert
Assert.False(File.Exists(Path.Combine(outputPath.FullName, ".json")));
Assert.False(File.Exists(Path.Combine(outputPath.FullName, "_internal.json")));
Assert.True(File.Exists(Path.Combine(outputPath.FullName, "Sample.json")));
Assert.True(File.Exists(Path.Combine(outputPath.FullName, "Sample_internal.json")));
}
}
Loading