Skip to content

Commit d793865

Browse files
authored
Existing output file should be deleted/overwritten (domaindrivendev#2886)
The CLI currently uses `File.OpenWrite(path)` (added in domaindrivendev#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.
1 parent 7deb5f6 commit d793865

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

src/Swashbuckle.AspNetCore.Cli/Program.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ public static int Main(string[] args)
101101
? Path.Combine(Directory.GetCurrentDirectory(), arg1)
102102
: null;
103103

104-
using (Stream stream = outputPath != null ? File.OpenWrite(outputPath) : Console.OpenStandardOutput())
104+
using (Stream stream = outputPath != null ? File.Create(outputPath) : Console.OpenStandardOutput())
105105
using (var streamWriter = new FormattingStreamWriter(stream, CultureInfo.InvariantCulture))
106106
{
107107
IOpenApiWriter writer;

test/Swashbuckle.AspNetCore.Cli.Test/ToolTests.cs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,28 @@ public void Can_Generate_Swagger_Json()
2828
Assert.True(productsPath.TryGetProperty("post", out _));
2929
}
3030

31+
[Fact(Skip = "Disabled because it makes CI unstable")]
32+
public void Overwrites_Existing_File()
33+
{
34+
using var temporaryDirectory = new TemporaryDirectory();
35+
var path = Path.Combine(temporaryDirectory.Path, "swagger.json");
36+
37+
var dummyContent = new string('x', 100_000);
38+
File.WriteAllText(path, dummyContent);
39+
40+
var args = new string[] { "tofile", "--output", path, Path.Combine(Directory.GetCurrentDirectory(), "Basic.dll"), "v1" };
41+
Assert.Equal(0, Program.Main(args));
42+
43+
var readContent = File.ReadAllText(path);
44+
Assert.True(readContent.Length < dummyContent.Length);
45+
using var document = JsonDocument.Parse(readContent);
46+
47+
// verify one of the endpoints
48+
var paths = document.RootElement.GetProperty("paths");
49+
var productsPath = paths.GetProperty("/products");
50+
Assert.True(productsPath.TryGetProperty("post", out _));
51+
}
52+
3153
[Fact]
3254
public void CustomDocumentSerializer_Writes_Custom_V2_Document()
3355
{

0 commit comments

Comments
 (0)