Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
7f9c828
feat: add IOutputPlanner and IFileWriter interfaces
christianhelle Jun 20, 2026
2b284a6
feat: add OutputPlannerAdapter implementing IOutputPlanner
christianhelle Jun 20, 2026
4144715
feat: add CliFileWriter implementing IFileWriter
christianhelle Jun 20, 2026
d91c710
feat: add MsBuildFileWriter implementing IFileWriter
christianhelle Jun 20, 2026
1d43365
feat: add SourceGeneratorFileWriter implementing IFileWriter
christianhelle Jun 20, 2026
23ce51a
refactor: GenerationOrchestrator uses IOutputPlanner and IFileWriter
christianhelle Jun 20, 2026
398bd84
refactor: RefitterGenerateTask uses IOutputPlanner and IFileWriter
christianhelle Jun 20, 2026
4330ec0
refactor: source generator uses IFileWriter for file writing
christianhelle Jun 20, 2026
4bd4c14
chore: remove unused imports from source generator
christianhelle Jun 20, 2026
5e5abb5
feat: add IDocumentLoadingStrategy interface for strategy pattern
christianhelle Jun 20, 2026
d3563dc
feat: add PathUtilities helper (IsHttp, IsYaml)
christianhelle Jun 20, 2026
244e337
feat: add FileDocumentStrategy for loading local OpenAPI specs
christianhelle Jun 20, 2026
1838e74
feat: add HttpDocumentStrategy for loading remote OpenAPI specs
christianhelle Jun 20, 2026
9d10924
feat: add OpenApiReaderDocumentStrategy for external resolution
christianhelle Jun 20, 2026
62348f0
refactor: DocumentLoader becomes compositor using strategy pattern
christianhelle Jun 20, 2026
bef7b76
fix: apply CodeRabbit auto-fixes
coderabbitai[bot] Jun 20, 2026
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
20 changes: 20 additions & 0 deletions src/Refitter.Core/Abstractions/IFileWriter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using System.Threading;
using System.Threading.Tasks;

namespace Refitter.Core;

/// <summary>
/// Writes a <see cref="PlannedFile"/> to disk, creating directories as needed.
/// Each distribution form (CLI, MSBuild, Source Generator) provides its own adapter
/// that integrates with its own reporting/progress pipeline.
/// </summary>
public interface IFileWriter
{
/// <summary>
/// Writes the planned file to disk, creating directories as necessary.
/// </summary>
/// <param name="file">The planned file to write.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>A task representing the asynchronous write operation.</returns>
Task WriteAsync(PlannedFile file, CancellationToken cancellationToken = default);
}
28 changes: 28 additions & 0 deletions src/Refitter.Core/Abstractions/IOutputPlanner.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using System.Diagnostics.CodeAnalysis;

namespace Refitter.Core;

/// <summary>
/// Resolves a <see cref="GeneratorOutput"/> into a list of <see cref="PlannedFile"/> instances.
/// Pure logic — no I/O.
/// </summary>
public interface IOutputPlanner
{
/// <summary>
/// Plans the output file paths for the given generator output.
/// </summary>
/// <param name="output">The generator output containing generated files.</param>
/// <param name="config">The output configuration.</param>
/// <param name="settingsFilePath">
/// The path to the settings file, or <c>null</c> for direct CLI generation.
/// </param>
/// <param name="cliOutputPath">
/// The output path specified via CLI, or <c>null</c>.
/// </param>
/// <returns>A read-only list of planned files with resolved paths and content.</returns>
IReadOnlyList<PlannedFile> Plan(
GeneratorOutput output,
IOutputConfiguration config,
string? settingsFilePath,
string? cliOutputPath);
}
39 changes: 39 additions & 0 deletions src/Refitter.Core/Abstractions/OutputPlannerAdapter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using System.Collections.Generic;

namespace Refitter.Core;

/// <summary>
/// Adapts the static <see cref="OutputPlanner"/> methods to the <see cref="IOutputPlanner"/> interface.
/// </summary>
public class OutputPlannerAdapter : IOutputPlanner
{
/// <inheritdoc />
public IReadOnlyList<PlannedFile> Plan(
GeneratorOutput output,
IOutputConfiguration config,
string? settingsFilePath,
string? cliOutputPath)
{
if (config.GenerateMultipleFiles)
{
return OutputPlanner.PlanMultipleFiles(
settingsFilePath,
cliOutputPath,
config,
output);
}

var code = output.Files.Count > 0
? output.Files[0].Content
: string.Empty;

return
[
OutputPlanner.PlanSingleFile(
settingsFilePath,
cliOutputPath,
config,
code)
];
}
}
35 changes: 35 additions & 0 deletions src/Refitter.Core/Abstractions/SourceGeneratorFileWriter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Refitter.Core;

/// <summary>
/// Writes planned files to disk with content-equality checking.
/// Skips writing when the file already exists with identical content,
/// avoiding unnecessary disk writes during incremental / design-time builds.
/// </summary>
public class SourceGeneratorFileWriter : IFileWriter
{
/// <inheritdoc />
public Task WriteAsync(PlannedFile file, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();

var dir = Path.GetDirectoryName(file.Path);
if (!string.IsNullOrWhiteSpace(dir) && !Directory.Exists(dir))
Directory.CreateDirectory(dir);

var existingContent = File.Exists(file.Path)
? File.ReadAllText(file.Path, Encoding.UTF8)
: null;

if (existingContent is null || !string.Equals(existingContent, file.Content, System.StringComparison.Ordinal))
{
File.WriteAllText(file.Path, file.Content, Encoding.UTF8);
}

return Task.CompletedTask;
}
}
149 changes: 38 additions & 111 deletions src/Refitter.Core/Document/DocumentLoader.cs
Original file line number Diff line number Diff line change
@@ -1,28 +1,22 @@
using System.Diagnostics.CodeAnalysis;
using System.Net;
using Microsoft.OpenApi;
using Microsoft.OpenApi.Reader;
using NSwag;
using OpenApiDocument = NSwag.OpenApiDocument;

namespace Refitter.Core;

internal sealed class DocumentLoader : IDocumentLoader
{
private static readonly HttpClient HttpClient = new(
new HttpClientHandler
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
})
private readonly IReadOnlyList<IDocumentLoadingStrategy> strategies;

public DocumentLoader()
: this(CreateDefaultStrategies())
{
Timeout = TimeSpan.FromSeconds(30)
};
}

static DocumentLoader()
public DocumentLoader(IEnumerable<IDocumentLoadingStrategy> strategies)
{
HttpClient.DefaultRequestHeaders.Add(
"User-Agent",
$"refitter/{typeof(DocumentLoader).Assembly.GetName().Version}");
if (strategies == null)
throw new ArgumentNullException(nameof(strategies), "strategies cannot be null");

this.strategies = strategies.ToList();
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.

public async Task<OpenApiDocument> LoadAsync(
Expand All @@ -34,114 +28,47 @@ public async Task<OpenApiDocument> LoadAsync(
"The openApiPath parameter cannot be null, empty, or contain only whitespace.",
nameof(openApiPath));

try
{
cancellationToken.ThrowIfCancellationRequested();
var readResult = await OpenApiMultiFileReader
.Read(openApiPath, cancellationToken: cancellationToken)
.ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();

if (!readResult.ContainedExternalReferences)
return await CreateUsingNSwagAsync(openApiPath, cancellationToken).ConfigureAwait(false);
var errors = new List<string>();

var specificationVersion = readResult.OpenApiDiagnostic.SpecificationVersion;
PopulateMissingRequiredFields(openApiPath, readResult);
foreach (var strategy in strategies)
{
cancellationToken.ThrowIfCancellationRequested();

if (IsYaml(openApiPath))
try
{
var yaml = await readResult.OpenApiDocument
.SerializeAsYamlAsync(
specificationVersion,
cancellationToken: cancellationToken)
var result = await strategy
.TryLoadAsync(openApiPath, cancellationToken)
.ConfigureAwait(false);

return await OpenApiYamlDocument
.FromYamlAsync(yaml, cancellationToken)
.ConfigureAwait(false);
if (result != null)
return result;
}
catch (Exception ex)
{
if (ex is OperationCanceledException or TaskCanceledException)
throw;

var json = await readResult.OpenApiDocument
.SerializeAsJsonAsync(specificationVersion, cancellationToken: cancellationToken)
.ConfigureAwait(false);

return await OpenApiDocument
.FromJsonAsync(json, cancellationToken)
.ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException && ex is not TaskCanceledException)
{
return await CreateUsingNSwagAsync(openApiPath, cancellationToken)
.ConfigureAwait(false);
}
}

private static async Task<OpenApiDocument> CreateUsingNSwagAsync(
string openApiPath,
CancellationToken cancellationToken = default)
{
if (IsHttp(openApiPath))
{
var content = await GetHttpContent(openApiPath, cancellationToken).ConfigureAwait(false);
return IsYaml(openApiPath)
? await OpenApiYamlDocument.FromYamlAsync(content, cancellationToken).ConfigureAwait(false)
: await OpenApiDocument.FromJsonAsync(content, cancellationToken).ConfigureAwait(false);
errors.Add($"{strategy.GetType().Name}: {ex.Message}");
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}

return IsYaml(openApiPath)
? await OpenApiYamlDocument.FromFileAsync(openApiPath, cancellationToken).ConfigureAwait(false)
: await OpenApiDocument.FromFileAsync(openApiPath, cancellationToken).ConfigureAwait(false);
throw new InvalidOperationException(
$"Failed to load OpenAPI document from '{openApiPath}'. " +
$"All {strategies.Count} strategies failed." +
(errors.Count > 0
? $" Errors: {string.Join("; ", errors)}"
: ""));
}

[ExcludeFromCodeCoverage]
private static void PopulateMissingRequiredFields(
string openApiPath,
Result readResult)
private static List<IDocumentLoadingStrategy> CreateDefaultStrategies()
{
var document = readResult.OpenApiDocument;
if (document.Info is null)
{
document.Info = new()
{
Title = Path.GetFileNameWithoutExtension(openApiPath),
Version = readResult.OpenApiDiagnostic.SpecificationVersion.GetDisplayName()
};
}
else
return new List<IDocumentLoadingStrategy>
{
document.Info.Title ??= Path.GetFileNameWithoutExtension(openApiPath);
document.Info.Version ??= readResult.OpenApiDiagnostic.SpecificationVersion.GetDisplayName();
}
}

private static bool IsHttp(string path)
{
return path.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ||
path.StartsWith("https://", StringComparison.OrdinalIgnoreCase);
}

private static async Task<string> GetHttpContent(
string openApiPath,
CancellationToken cancellationToken = default)
{
var response = await HttpClient.GetAsync(openApiPath, cancellationToken).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}

private static bool IsYaml(string path)
{
var queryIndex = path.IndexOf('?');
var fragmentIndex = path.IndexOf('#');
var endIndex = path.Length;

if (queryIndex >= 0)
endIndex = Math.Min(endIndex, queryIndex);
if (fragmentIndex >= 0)
endIndex = Math.Min(endIndex, fragmentIndex);

var basePath = endIndex < path.Length ? path.Substring(0, endIndex) : path;

return basePath.EndsWith("yaml", StringComparison.OrdinalIgnoreCase) ||
basePath.EndsWith("yml", StringComparison.OrdinalIgnoreCase);
new FileDocumentStrategy(),
new HttpDocumentStrategy(),
new OpenApiReaderDocumentStrategy()
};
}
}
31 changes: 31 additions & 0 deletions src/Refitter.Core/Document/FileDocumentStrategy.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using NSwag;
using OpenApiDocument = NSwag.OpenApiDocument;

namespace Refitter.Core;

internal sealed class FileDocumentStrategy : IDocumentLoadingStrategy
{
public async Task<OpenApiDocument?> TryLoadAsync(
string path,
CancellationToken cancellationToken = default)
{
if (PathUtilities.IsHttp(path))
return null;

try
{
cancellationToken.ThrowIfCancellationRequested();

return PathUtilities.IsYaml(path)
? await OpenApiYamlDocument.FromFileAsync(path, cancellationToken).ConfigureAwait(false)
: await OpenApiDocument.FromFileAsync(path, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
if (ex is OperationCanceledException or TaskCanceledException)
throw;

return null;
}
}
}
Loading
Loading