Skip to content

Commit

Permalink
Merge pull request #879 from christianhelle/refitter-settings-file
Browse files Browse the repository at this point in the history
Add support for .refitter files
  • Loading branch information
christianhelle authored May 5, 2024
2 parents 7036905 + 0873c4e commit 3a478a9
Show file tree
Hide file tree
Showing 8 changed files with 180 additions and 9 deletions.
Binary file added images/refitter-command.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Serialization;

namespace Rapicgen.Core.Exceptions
{
[ExcludeFromCodeCoverage]
[Serializable]
public class RunRefitterCommandException : RapicgenException
{
public RunRefitterCommandException()
{
}

public RunRefitterCommandException(string message) : base(message)
{
}

public RunRefitterCommandException(string message, Exception inner) : base(message, inner)
{
}

protected RunRefitterCommandException(
SerializationInfo info,
StreamingContext context) : base(info, context)
{
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@
using System.Threading.Tasks;
using Rapicgen.Core.Logging;
using Newtonsoft.Json;
using System.IO;

namespace Rapicgen.Core.Generators.Refitter;

public class RefitterCodeGenerator : ICodeGenerator
{
private readonly string swaggerFile;
private readonly string inputFile;
private readonly string defaultNamespace;
private readonly IRefitterOptions options;

Expand All @@ -18,7 +19,7 @@ public RefitterCodeGenerator(
string defaultNamespace,
IRefitterOptions options)
{
this.swaggerFile = swaggerFile;
this.inputFile = swaggerFile;
this.defaultNamespace = defaultNamespace;
this.options = options;
}
Expand All @@ -31,19 +32,41 @@ public string GenerateCode(IProgressReporter? pGenerateProgress)
{
pGenerateProgress?.Progress(10);

var settings = new RefitGeneratorSettings
RefitGeneratorSettings settings;
if (inputFile.EndsWith(".refitter"))
{
settings = Serializer.Deserialize<RefitGeneratorSettings>(
File.ReadAllText(inputFile));
}
else
{
settings = new RefitGeneratorSettings
{
OpenApiPath = swaggerFile,
OpenApiPath = inputFile,
Namespace = defaultNamespace,
AddAutoGeneratedHeader = options.AddAutoGeneratedHeader,
GenerateContracts = options.GenerateContracts,
GenerateXmlDocCodeComments = options.GenerateXmlDocCodeComments,
ReturnIApiResponse = options.ReturnIApiResponse,
UseCancellationTokens = options.UseCancellationTokens,
GenerateOperationHeaders = options.GenerateHeaderParameters,
GenerateOperationHeaders = options.GenerateHeaderParameters
};

var fileInfo = new FileInfo(inputFile);
var json = Serializer.Serialize(settings);
File.WriteAllText(
Path.Combine(
fileInfo.Directory.FullName,
fileInfo.Name.Replace(fileInfo.Extension, ".refitter")),
json);
}

var generator = Task
.Run(() => RefitGenerator.CreateAsync(settings))
.Run(() =>
{
Directory.SetCurrentDirectory(Path.GetDirectoryName(inputFile));
return RefitGenerator.CreateAsync(settings);
})
.GetAwaiter()
.GetResult();

Expand All @@ -53,9 +76,31 @@ public string GenerateCode(IProgressReporter? pGenerateProgress)
context.Succeeded();

pGenerateProgress?.Progress(90);
return GeneratedCode.PrefixAutogeneratedCodeHeader(
var output = GeneratedCode.PrefixAutogeneratedCodeHeader(
code,
"Refitter",
"v1.0.0");

if (inputFile.EndsWith(".refitter"))
{
var fileInfo = new FileInfo(inputFile);
var outputFolder = fileInfo.Directory.FullName;
if (settings.OutputFolder != RefitGeneratorSettings.DefaultOutputFolder)
{
outputFolder = Path.Combine(outputFolder, settings.OutputFolder);
if (!Directory.Exists(outputFolder))
{
Directory.CreateDirectory(outputFolder);
}
}

File.WriteAllText(
Path.Combine(
outputFolder,
fileInfo.Name.Replace(fileInfo.Extension, ".cs")),
output);
}

return output;
}
}
13 changes: 13 additions & 0 deletions src/VSIX/ApiClientCodeGen.VSIX.Dev17/VSCommandTable.vsct
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,14 @@
</Strings>
</Button>

<Button guid="guidPackageRefitterCmdSet" id="RefitterCommand" priority="0x0002">
<Parent guid="guidSHLMainMenu" id="IDG_VS_CTXT_ITEM_INCLUDEEXCLUDE" />
<CommandFlag>DefaultInvisible</CommandFlag>
<Strings>
<ButtonText>Generate Refitter output</ButtonText>
</Strings>
</Button>

<Button guid="guidNewRestApiClientCmdSet" id="GenerateWithNSwag" priority="0x0100" type="Button">
<Strings>
<ButtonText>Generate with NSwag (v14.0.3)</ButtonText>
Expand Down Expand Up @@ -174,6 +182,7 @@
<VisibilityConstraints>
<VisibilityItem guid="guidPackageCmdSet" id="Submenu" context="guidUIContext"/>
<VisibilityItem guid="guidPackageNSwagStudioCmdSet" id="NSwagStudioCommand" context="guidNSwagStudioContext"/>
<VisibilityItem guid="guidPackageRefitterCmdSet" id="RefitterCommand" context="guidRefitterContext"/>
</VisibilityConstraints>

<Symbols>
Expand All @@ -196,6 +205,10 @@
<GuidSymbol name="guidPackageNSwagStudioCmdSet" value="{F76783DA-7AE3-4EDB-BDF4-B580CAB1BA90}">
<IDSymbol name="NSwagStudioCommand" value="0x0100" />
</GuidSymbol>
<GuidSymbol name="guidRefitterContext" value="{2A5A0DB6-FC9C-48AB-98E5-C69D7157CEF5}" />
<GuidSymbol name="guidPackageRefitterCmdSet" value="{E00623E7-31F9-40E9-BDEE-9D7829D09184}">
<IDSymbol name="RefitterCommand" value="0x0200"/>
</GuidSymbol>

<GuidSymbol name="guidNewRestApiClientContext" value="{7CEC8679-C1B8-48BF-9FA4-5FAA38CBE0FA}" />
<GuidSymbol name="guidNewRestApiClientCmdSet" value="{E4B99F94-D11F-4CAA-ADCD-24302C232938}">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
<Compile Include="$(MSBuildThisFileDirectory)Commands\CustomTool\SwaggerCodeGeneratorCustomToolSetter.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Commands\ICommandInitializer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Commands\NSwagStudio\NSwagStudioCommand.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Commands\Refitter\RefitterCommand.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Converters\CSharpToVisualBasicLanguageConverter.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CustomTool\AutoRest\AutoRestCodeGenerator.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CustomTool\AutoRest\AutoRestCSharpCodeGenerator.cs" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using Rapicgen.Core;
using Rapicgen.Core.Exceptions;
using Rapicgen.Core.Logging;
using Rapicgen.Extensions;
using EnvDTE;
using Microsoft.VisualStudio.Shell;
using Task = System.Threading.Tasks.Task;
using Rapicgen.Core.Generators.Refitter;

namespace Rapicgen.Commands.Refitter
{
[ExcludeFromCodeCoverage]
public class RefitterCommand : ICommandInitializer
{
public const string ContextGuid = "2A5A0DB6-FC9C-48AB-98E5-C69D7157CEF5";
public const string Name = "Refitter Context";
public const string Expression = "refitter";
public const string TermValue = "HierSingleSelectionName:.refitter";

protected int CommandId { get; } = 0x200;
protected Guid CommandSet { get; } = new Guid("E00623E7-31F9-40E9-BDEE-9D7829D09184");

public Task InitializeAsync(AsyncPackage package, CancellationToken token)
=> package.SetupCommandAsync(
CommandSet,
CommandId,
ExecuteAsync,
token);

private async Task ExecuteAsync(DTE dte, AsyncPackage package)
{
try
{
await OnExecuteAsync(dte, package);
}
catch (Exception e)
{
throw new RunRefitterCommandException(GetType().Name, e);
}
}

private static async Task OnExecuteAsync(DTE dte, AsyncPackage package)
{
Logger.Instance.TrackFeatureUsage("Generate Refitter output");

await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

var item = dte.SelectedItems.Item(1).ProjectItem;
var refitterSettingsFile = item.FileNames[0];

var codeGenerator = new RefitterCodeGenerator(refitterSettingsFile, default, default);
codeGenerator.GenerateCode(null);

var project = dte.GetActiveProject()!;
await project.InstallMissingPackagesAsync(package, SupportedCodeGenerator.Refitter);
}
}
}
13 changes: 11 additions & 2 deletions src/VSIX/ApiClientCodeGen.VSIX.Shared/VsPackage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
using Microsoft.VisualStudio.Shell.Interop;
using Task = System.Threading.Tasks.Task;
using Rapicgen.Options.Refitter;
using Rapicgen.Commands.Refitter;

namespace Rapicgen
{
Expand All @@ -38,6 +39,12 @@ namespace Rapicgen
NSwagStudioCommand.Expression,
new[] { NSwagStudioCommand.Expression },
new[] { NSwagStudioCommand.TermValue })]
[ProvideUIContextRule(
RefitterCommand.ContextGuid,
RefitterCommand.Name,
RefitterCommand.Expression,
new[] { RefitterCommand.Expression },
new[] { RefitterCommand.TermValue })]
[ProvideOptionPage(
typeof(GeneralOptionPage),
VsixName,
Expand Down Expand Up @@ -99,6 +106,7 @@ public sealed class VsPackage : AsyncPackage
new KiotaCodeGeneratorCustomToolSetter(),
new RefitterCodeGeneratorCustomToolSetter(),
new NSwagStudioCommand(),
new RefitterCommand(),
new NewAutoRestClientCommand(),
new NewNSwagClientCommand(),
new NewSwaggerClientCommand(),
Expand Down Expand Up @@ -131,13 +139,14 @@ protected override async Task InitializeAsync(
if (telemetryOptions?.TelemetryOptOut == true)
Logger.Instance.Disable();
else
await TrySetupVersionTrackingAsync();
await TrySetupVersionTrackingAsync(cancellationToken);
}

private async Task TrySetupVersionTrackingAsync()
private async Task TrySetupVersionTrackingAsync(CancellationToken cancellationToken)
{
try
{
await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
var shell = (IVsShell)(await GetServiceAsync(typeof(SVsShell)))!;
shell.GetProperty((int)__VSSPROPID5.VSSPROPID_ReleaseVersion, out object value);
if (value is string raw)
Expand Down
13 changes: 13 additions & 0 deletions src/VSIX/ApiClientCodeGen.VSIX/VSCommandTable.vsct
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,14 @@
</Strings>
</Button>

<Button guid="guidPackageRefitterCmdSet" id="RefitterCommand" priority="0x0002">
<Parent guid="guidSHLMainMenu" id="IDG_VS_CTXT_ITEM_INCLUDEEXCLUDE" />
<CommandFlag>DefaultInvisible</CommandFlag>
<Strings>
<ButtonText>Generate Refitter output</ButtonText>
</Strings>
</Button>

<Button guid="guidNewRestApiClientCmdSet" id="GenerateWithNSwag" priority="0x0100" type="Button">
<Strings>
<ButtonText>Generate with NSwag (v14.0.3)</ButtonText>
Expand Down Expand Up @@ -174,6 +182,7 @@
<VisibilityConstraints>
<VisibilityItem guid="guidPackageCmdSet" id="Submenu" context="guidUIContext"/>
<VisibilityItem guid="guidPackageNSwagStudioCmdSet" id="NSwagStudioCommand" context="guidNSwagStudioContext"/>
<VisibilityItem guid="guidPackageRefitterCmdSet" id="RefitterCommand" context="guidRefitterContext"/>
</VisibilityConstraints>

<Symbols>
Expand All @@ -196,6 +205,10 @@
<GuidSymbol name="guidPackageNSwagStudioCmdSet" value="{F76783DA-7AE3-4EDB-BDF4-B580CAB1BA90}">
<IDSymbol name="NSwagStudioCommand" value="0x0100" />
</GuidSymbol>
<GuidSymbol name="guidRefitterContext" value="{2A5A0DB6-FC9C-48AB-98E5-C69D7157CEF5}" />
<GuidSymbol name="guidPackageRefitterCmdSet" value="{E00623E7-31F9-40E9-BDEE-9D7829D09184}">
<IDSymbol name="RefitterCommand" value="0x0200"/>
</GuidSymbol>

<GuidSymbol name="guidNewRestApiClientContext" value="{7CEC8679-C1B8-48BF-9FA4-5FAA38CBE0FA}" />
<GuidSymbol name="guidNewRestApiClientCmdSet" value="{E4B99F94-D11F-4CAA-ADCD-24302C232938}">
Expand Down

0 comments on commit 3a478a9

Please sign in to comment.