Skip to content

Commit

Permalink
Existing output file should be deleted/overwritten (#2886)
Browse files Browse the repository at this point in the history
The CLI currently uses `File.OpenWrite(path)` (added in #2677) to create an output stream for the resulting swagger document. This does not delete the existing contents, but instead starts writing from position 0, causing issues if the output is smaller than the previous file content.

Changed to `File.Create(path)` to make sure any previous content is discarded.
  • Loading branch information
patrikwlund committed May 15, 2024
1 parent 7deb5f6 commit d793865
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Swashbuckle.AspNetCore.Cli/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ public static int Main(string[] args)
? Path.Combine(Directory.GetCurrentDirectory(), arg1)
: null;
using (Stream stream = outputPath != null ? File.OpenWrite(outputPath) : Console.OpenStandardOutput())
using (Stream stream = outputPath != null ? File.Create(outputPath) : Console.OpenStandardOutput())
using (var streamWriter = new FormattingStreamWriter(stream, CultureInfo.InvariantCulture))
{
IOpenApiWriter writer;
Expand Down
22 changes: 22 additions & 0 deletions test/Swashbuckle.AspNetCore.Cli.Test/ToolTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,28 @@ public void Can_Generate_Swagger_Json()
Assert.True(productsPath.TryGetProperty("post", out _));
}

[Fact(Skip = "Disabled because it makes CI unstable")]
public void Overwrites_Existing_File()
{
using var temporaryDirectory = new TemporaryDirectory();
var path = Path.Combine(temporaryDirectory.Path, "swagger.json");

var dummyContent = new string('x', 100_000);
File.WriteAllText(path, dummyContent);

var args = new string[] { "tofile", "--output", path, Path.Combine(Directory.GetCurrentDirectory(), "Basic.dll"), "v1" };
Assert.Equal(0, Program.Main(args));

var readContent = File.ReadAllText(path);
Assert.True(readContent.Length < dummyContent.Length);
using var document = JsonDocument.Parse(readContent);

// verify one of the endpoints
var paths = document.RootElement.GetProperty("paths");
var productsPath = paths.GetProperty("/products");
Assert.True(productsPath.TryGetProperty("post", out _));
}

[Fact]
public void CustomDocumentSerializer_Writes_Custom_V2_Document()
{
Expand Down

0 comments on commit d793865

Please sign in to comment.