├── .gitattributes ├── .gitignore ├── RefitGenerator.TestApi ├── Controllers │ ├── BasicController.cs │ ├── DictionaryController.cs │ ├── FileController.cs │ ├── FormController.cs │ └── PlainTypeControler.cs ├── Models │ └── TestModels.cs ├── Program.cs ├── Properties │ └── launchSettings.json ├── RefitGenerator.TestApi.csproj ├── Startup.cs ├── appsettings.Development.json └── appsettings.json ├── RefitGenerator.sln ├── RefitGenerator ├── Generator.cs ├── GeneratorOptions.cs ├── Helpers │ ├── CSharpKeywords.cs │ ├── ConsoleHelper.cs │ ├── InterfaceWriter.cs │ ├── ModelWriter.cs │ ├── SchemaProcessor.cs │ ├── StringExtensions.cs │ ├── Strings.cs │ └── TypeHelper.cs ├── Program.cs ├── RefitGenerator.csproj ├── Templates │ ├── ClientTemplate.csx │ ├── CsprojExe.xml │ ├── CsprojLib.xml │ ├── InterfaceTemplate.csx │ ├── ModelTemplate.csx │ └── ProgramTemplate.csx └── pack.ps1 └── readme.md /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Dd]ebugPublic/ 19 | [Rr]elease/ 20 | [Rr]eleases/ 21 | x64/ 22 | x86/ 23 | [Aa][Rr][Mm]/ 24 | [Aa][Rr][Mm]64/ 25 | bld/ 26 | [Bb]in/ 27 | [Oo]bj/ 28 | [Ll]og/ 29 | 30 | # Visual Studio 2015/2017 cache/options directory 31 | .vs/ 32 | # Uncomment if you have tasks that create the project's static files in wwwroot 33 | #wwwroot/ 34 | 35 | # Visual Studio 2017 auto generated files 36 | Generated\ Files/ 37 | 38 | # MSTest test Results 39 | [Tt]est[Rr]esult*/ 40 | [Bb]uild[Ll]og.* 41 | 42 | # NUNIT 43 | *.VisualState.xml 44 | TestResult.xml 45 | 46 | # Build Results of an ATL Project 47 | [Dd]ebugPS/ 48 | [Rr]eleasePS/ 49 | dlldata.c 50 | 51 | # Benchmark Results 52 | BenchmarkDotNet.Artifacts/ 53 | 54 | # .NET Core 55 | project.lock.json 56 | project.fragment.lock.json 57 | artifacts/ 58 | 59 | # StyleCop 60 | StyleCopReport.xml 61 | 62 | # Files built by Visual Studio 63 | *_i.c 64 | *_p.c 65 | *_h.h 66 | *.ilk 67 | *.meta 68 | *.obj 69 | *.iobj 70 | *.pch 71 | *.pdb 72 | *.ipdb 73 | *.pgc 74 | *.pgd 75 | *.rsp 76 | *.sbr 77 | *.tlb 78 | *.tli 79 | *.tlh 80 | *.tmp 81 | *.tmp_proj 82 | *_wpftmp.csproj 83 | *.log 84 | *.vspscc 85 | *.vssscc 86 | .builds 87 | *.pidb 88 | *.svclog 89 | *.scc 90 | 91 | # Chutzpah Test files 92 | _Chutzpah* 93 | 94 | # Visual C++ cache files 95 | ipch/ 96 | *.aps 97 | *.ncb 98 | *.opendb 99 | *.opensdf 100 | *.sdf 101 | *.cachefile 102 | *.VC.db 103 | *.VC.VC.opendb 104 | 105 | # Visual Studio profiler 106 | *.psess 107 | *.vsp 108 | *.vspx 109 | *.sap 110 | 111 | # Visual Studio Trace Files 112 | *.e2e 113 | 114 | # TFS 2012 Local Workspace 115 | $tf/ 116 | 117 | # Guidance Automation Toolkit 118 | *.gpState 119 | 120 | # ReSharper is a .NET coding add-in 121 | _ReSharper*/ 122 | *.[Rr]e[Ss]harper 123 | *.DotSettings.user 124 | 125 | # JustCode is a .NET coding add-in 126 | .JustCode 127 | 128 | # TeamCity is a build add-in 129 | _TeamCity* 130 | 131 | # DotCover is a Code Coverage Tool 132 | *.dotCover 133 | 134 | # AxoCover is a Code Coverage Tool 135 | .axoCover/* 136 | !.axoCover/settings.json 137 | 138 | # Visual Studio code coverage results 139 | *.coverage 140 | *.coveragexml 141 | 142 | # NCrunch 143 | _NCrunch_* 144 | .*crunch*.local.xml 145 | nCrunchTemp_* 146 | 147 | # MightyMoose 148 | *.mm.* 149 | AutoTest.Net/ 150 | 151 | # Web workbench (sass) 152 | .sass-cache/ 153 | 154 | # Installshield output folder 155 | [Ee]xpress/ 156 | 157 | # DocProject is a documentation generator add-in 158 | DocProject/buildhelp/ 159 | DocProject/Help/*.HxT 160 | DocProject/Help/*.HxC 161 | DocProject/Help/*.hhc 162 | DocProject/Help/*.hhk 163 | DocProject/Help/*.hhp 164 | DocProject/Help/Html2 165 | DocProject/Help/html 166 | 167 | # Click-Once directory 168 | publish/ 169 | 170 | # Publish Web Output 171 | *.[Pp]ublish.xml 172 | *.azurePubxml 173 | # Note: Comment the next line if you want to checkin your web deploy settings, 174 | # but database connection strings (with potential passwords) will be unencrypted 175 | *.pubxml 176 | *.publishproj 177 | 178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 179 | # checkin your Azure Web App publish settings, but sensitive information contained 180 | # in these scripts will be unencrypted 181 | PublishScripts/ 182 | 183 | # NuGet Packages 184 | *.nupkg 185 | # The packages folder can be ignored because of Package Restore 186 | **/[Pp]ackages/* 187 | # except build/, which is used as an MSBuild target. 188 | !**/[Pp]ackages/build/ 189 | # Uncomment if necessary however generally it will be regenerated when needed 190 | #!**/[Pp]ackages/repositories.config 191 | # NuGet v3's project.json files produces more ignorable files 192 | *.nuget.props 193 | *.nuget.targets 194 | 195 | # Microsoft Azure Build Output 196 | csx/ 197 | *.build.csdef 198 | 199 | # Microsoft Azure Emulator 200 | ecf/ 201 | rcf/ 202 | 203 | # Windows Store app package directories and files 204 | AppPackages/ 205 | BundleArtifacts/ 206 | Package.StoreAssociation.xml 207 | _pkginfo.txt 208 | *.appx 209 | 210 | # Visual Studio cache files 211 | # files ending in .cache can be ignored 212 | *.[Cc]ache 213 | # but keep track of directories ending in .cache 214 | !?*.[Cc]ache/ 215 | 216 | # Others 217 | ClientBin/ 218 | ~$* 219 | *~ 220 | *.dbmdl 221 | *.dbproj.schemaview 222 | *.jfm 223 | *.pfx 224 | *.publishsettings 225 | orleans.codegen.cs 226 | 227 | # Including strong name files can present a security risk 228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 229 | #*.snk 230 | 231 | # Since there are multiple workflows, uncomment next line to ignore bower_components 232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 233 | #bower_components/ 234 | 235 | # RIA/Silverlight projects 236 | Generated_Code/ 237 | 238 | # Backup & report files from converting an old project file 239 | # to a newer Visual Studio version. Backup files are not needed, 240 | # because we have git ;-) 241 | _UpgradeReport_Files/ 242 | Backup*/ 243 | UpgradeLog*.XML 244 | UpgradeLog*.htm 245 | ServiceFabricBackup/ 246 | *.rptproj.bak 247 | 248 | # SQL Server files 249 | *.mdf 250 | *.ldf 251 | *.ndf 252 | 253 | # Business Intelligence projects 254 | *.rdl.data 255 | *.bim.layout 256 | *.bim_*.settings 257 | *.rptproj.rsuser 258 | *- Backup*.rdl 259 | 260 | # Microsoft Fakes 261 | FakesAssemblies/ 262 | 263 | # GhostDoc plugin setting file 264 | *.GhostDoc.xml 265 | 266 | # Node.js Tools for Visual Studio 267 | .ntvs_analysis.dat 268 | node_modules/ 269 | 270 | # Visual Studio 6 build log 271 | *.plg 272 | 273 | # Visual Studio 6 workspace options file 274 | *.opt 275 | 276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 277 | *.vbw 278 | 279 | # Visual Studio LightSwitch build output 280 | **/*.HTMLClient/GeneratedArtifacts 281 | **/*.DesktopClient/GeneratedArtifacts 282 | **/*.DesktopClient/ModelManifest.xml 283 | **/*.Server/GeneratedArtifacts 284 | **/*.Server/ModelManifest.xml 285 | _Pvt_Extensions 286 | 287 | # Paket dependency manager 288 | .paket/paket.exe 289 | paket-files/ 290 | 291 | # FAKE - F# Make 292 | .fake/ 293 | 294 | # JetBrains Rider 295 | .idea/ 296 | *.sln.iml 297 | 298 | # CodeRush personal settings 299 | .cr/personal 300 | 301 | # Python Tools for Visual Studio (PTVS) 302 | __pycache__/ 303 | *.pyc 304 | 305 | # Cake - Uncomment if you are using it 306 | # tools/** 307 | # !tools/packages.config 308 | 309 | # Tabs Studio 310 | *.tss 311 | 312 | # Telerik's JustMock configuration file 313 | *.jmconfig 314 | 315 | # BizTalk build output 316 | *.btp.cs 317 | *.btm.cs 318 | *.odx.cs 319 | *.xsd.cs 320 | 321 | # OpenCover UI analysis results 322 | OpenCover/ 323 | 324 | # Azure Stream Analytics local run output 325 | ASALocalRun/ 326 | 327 | # MSBuild Binary and Structured Log 328 | *.binlog 329 | 330 | # NVidia Nsight GPU debugger configuration file 331 | *.nvuser 332 | 333 | # MFractors (Xamarin productivity tool) working folder 334 | .mfractor/ 335 | 336 | # Local History for Visual Studio 337 | .localhistory/ 338 | 339 | # BeatPulse healthcheck temp database 340 | healthchecksdb 341 | /RefitGenerator/Properties/launchSettings.json 342 | -------------------------------------------------------------------------------- /RefitGenerator.TestApi/Controllers/BasicController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using RefitGenerator.TestApi.Models; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | 8 | namespace RefitGenerator.TestApi.Controllers 9 | { 10 | [ApiController, Route("[controller]")] 11 | public class BasicController : ControllerBase 12 | { 13 | [HttpGet(Name = "basicGet")] 14 | public ActionResult Get() => Ok(); 15 | 16 | [HttpGet("deprecated", Name = "deprecatedGet"), Obsolete] 17 | public ActionResult DeprecatedGet() => Ok(); 18 | 19 | [HttpGet("{id}", Name = "basicGetWithRouteParam")] 20 | public ActionResult Get(int id) => Ok(id); 21 | 22 | [HttpGet("withQuery", Name = "basicGetWitQueryParam")] 23 | public ActionResult Get(string queryParam) => Ok(queryParam); 24 | 25 | [HttpGet("withComplexQuery", Name = "basicGetWithComplexQueryParam")] 26 | public ActionResult Get([FromQuery] NumericTestModel model) => Ok(model); 27 | 28 | [HttpPost(Name = "emptyPost")] 29 | public ActionResult Post() => Ok(); 30 | 31 | [HttpPost("numbers", Name = "postNumbers")] 32 | public ActionResult Post(NumericTestModel numbers) => Ok(numbers); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /RefitGenerator.TestApi/Controllers/DictionaryController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using RefitGenerator.TestApi.Models; 3 | using System.Collections.Generic; 4 | 5 | namespace RefitGenerator.TestApi.Controllers 6 | { 7 | [ApiController, Route("[controller]")] 8 | public class DictionaryController : ControllerBase 9 | { 10 | [HttpPost("stringDictionary", Name = "stringDictionary")] 11 | public ActionResult> Post(Dictionary dictionary) => Ok(dictionary); 12 | 13 | [HttpPost("intDictionary", Name = "intDictionary")] 14 | public ActionResult> Post(Dictionary dictionary) => Ok(dictionary); 15 | 16 | [HttpPost("numbersDictionary", Name = "numbersDictionary")] 17 | public ActionResult> Post(Dictionary dictionary) => Ok(dictionary); 18 | 19 | [HttpPost("objectsDictionary", Name = "objectsDictionary")] 20 | public ActionResult> Post(Dictionary dictionary) => Ok(dictionary); 21 | 22 | [HttpPost("nestedDictionary", Name = "nestedDictionary")] 23 | public ActionResult>> Post(Dictionary> dictionary) => Ok(dictionary); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /RefitGenerator.TestApi/Controllers/FileController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Http; 2 | using Microsoft.AspNetCore.Mvc; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Text; 6 | 7 | namespace RefitGenerator.TestApi.Controllers 8 | { 9 | [ApiController, Route("[controller]")] 10 | public class FileController : ControllerBase 11 | { 12 | [HttpGet(Name = "downloadFile"), Produces(typeof(FileResult))] 13 | public FileResult Download() 14 | { 15 | var stream = new MemoryStream(Encoding.UTF8.GetBytes("Hello world!")); 16 | return new FileStreamResult(stream, "text/plain") { FileDownloadName = "hello.txt" }; 17 | } 18 | 19 | [HttpPost("uploadSingle", Name = "uploadSingleFile")] 20 | public ActionResult UploadSingle(IFormFile file) 21 | { 22 | using var stream = file.OpenReadStream(); 23 | return Ok(stream.Length); 24 | } 25 | 26 | [HttpPost("uploadMany", Name = "uploadManyFiles")] 27 | public ActionResult> UploadMany(List files) 28 | { 29 | List result = new List(); 30 | foreach(var file in files) 31 | { 32 | using var stream = file.OpenReadStream(); 33 | result.Add(stream.Length); 34 | } 35 | 36 | return Ok(result); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /RefitGenerator.TestApi/Controllers/FormController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Http; 2 | using Microsoft.AspNetCore.Mvc; 3 | using RefitGenerator.TestApi.Models; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.IO; 7 | using System.Linq; 8 | using System.Text; 9 | 10 | namespace RefitGenerator.TestApi.Controllers 11 | { 12 | [ApiController, Route("[controller]")] 13 | public class FormController : ControllerBase 14 | { 15 | [HttpPost("formDictionary", Name = "postFormDictionary")] 16 | public ActionResult> Post([FromForm] Dictionary formContent) => Ok(formContent); 17 | 18 | [HttpPost("formParameters", Name = "postFormParameters")] 19 | public ActionResult Post([FromForm] string text, [FromForm] int number) => Ok($"{text}-{number}"); 20 | 21 | [HttpPost("formModel", Name = "postFormModel")] 22 | public ActionResult Post([FromForm] NumericTestModel model) => Ok(model); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /RefitGenerator.TestApi/Controllers/PlainTypeControler.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace RefitGenerator.TestApi.Controllers 8 | { 9 | [ApiController, Route("[controller]")] 10 | public class PlainTypeController 11 | { 12 | [HttpGet("long", Name = "getLong")] 13 | public long GetLong() => 10; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /RefitGenerator.TestApi/Models/TestModels.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace RefitGenerator.TestApi.Models 7 | { 8 | public record NumericTestModel(int Integer, uint UnsignedInteger, long Long, ulong UnsignedLong, 9 | double Double, float Float, decimal Decimal, 10 | short Short, byte Byte); 11 | } 12 | -------------------------------------------------------------------------------- /RefitGenerator.TestApi/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Hosting; 2 | using Microsoft.Extensions.Configuration; 3 | using Microsoft.Extensions.Hosting; 4 | using Microsoft.Extensions.Logging; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Threading.Tasks; 9 | 10 | namespace RefitGenerator.TestApi 11 | { 12 | public class Program 13 | { 14 | public static void Main(string[] args) 15 | { 16 | CreateHostBuilder(args).Build().Run(); 17 | } 18 | 19 | public static IHostBuilder CreateHostBuilder(string[] args) => 20 | Host.CreateDefaultBuilder(args) 21 | .ConfigureWebHostDefaults(webBuilder => 22 | { 23 | webBuilder.UseStartup(); 24 | }); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /RefitGenerator.TestApi/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "profiles": { 4 | "RefitGenerator.TestApi": { 5 | "commandName": "Project", 6 | "dotnetRunMessages": "true", 7 | "launchBrowser": true, 8 | "launchUrl": "swagger", 9 | "applicationUrl": "http://localhost:5000", 10 | "environmentVariables": { 11 | "ASPNETCORE_ENVIRONMENT": "Development" 12 | } 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /RefitGenerator.TestApi/RefitGenerator.TestApi.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /RefitGenerator.TestApi/Startup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.AspNetCore.Hosting; 3 | using Microsoft.AspNetCore.Mvc; 4 | using Microsoft.Extensions.Configuration; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Microsoft.Extensions.Hosting; 7 | using Microsoft.Extensions.Logging; 8 | using Microsoft.OpenApi.Models; 9 | using System; 10 | using System.Collections.Generic; 11 | using System.Linq; 12 | using System.Threading.Tasks; 13 | 14 | namespace RefitGenerator.TestApi 15 | { 16 | public class Startup 17 | { 18 | public Startup(IConfiguration configuration) 19 | { 20 | Configuration = configuration; 21 | } 22 | 23 | public IConfiguration Configuration { get; } 24 | 25 | // This method gets called by the runtime. Use this method to add services to the container. 26 | public void ConfigureServices(IServiceCollection services) 27 | { 28 | services.AddControllers(); 29 | services.AddSwaggerGen(c => 30 | { 31 | c.SwaggerDoc("v1", new OpenApiInfo { Title = "RefitGenerator.TestApi", Version = "v1" }); 32 | }); 33 | } 34 | 35 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 36 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 37 | { 38 | if (env.IsDevelopment()) 39 | { 40 | app.UseDeveloperExceptionPage(); 41 | app.UseSwagger(); 42 | app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "RefitGenerator.TestApi v1")); 43 | } 44 | 45 | app.UseRouting(); 46 | 47 | app.UseAuthorization(); 48 | 49 | app.UseEndpoints(endpoints => 50 | { 51 | endpoints.MapControllers(); 52 | }); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /RefitGenerator.TestApi/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /RefitGenerator.TestApi/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "AllowedHosts": "*" 10 | } 11 | -------------------------------------------------------------------------------- /RefitGenerator.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.31019.35 5 | MinimumVisualStudioVersion = 15.0.26124.0 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RefitGenerator", "RefitGenerator\RefitGenerator.csproj", "{5432FA44-09C1-490B-8D66-AD6BD481207D}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RefitGenerator.TestApi", "RefitGenerator.TestApi\RefitGenerator.TestApi.csproj", "{95743AB8-A891-4CF9-8F7E-7FC7889B58FF}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Debug|x64 = Debug|x64 14 | Debug|x86 = Debug|x86 15 | Release|Any CPU = Release|Any CPU 16 | Release|x64 = Release|x64 17 | Release|x86 = Release|x86 18 | EndGlobalSection 19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 20 | {5432FA44-09C1-490B-8D66-AD6BD481207D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {5432FA44-09C1-490B-8D66-AD6BD481207D}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {5432FA44-09C1-490B-8D66-AD6BD481207D}.Debug|x64.ActiveCfg = Debug|Any CPU 23 | {5432FA44-09C1-490B-8D66-AD6BD481207D}.Debug|x64.Build.0 = Debug|Any CPU 24 | {5432FA44-09C1-490B-8D66-AD6BD481207D}.Debug|x86.ActiveCfg = Debug|Any CPU 25 | {5432FA44-09C1-490B-8D66-AD6BD481207D}.Debug|x86.Build.0 = Debug|Any CPU 26 | {5432FA44-09C1-490B-8D66-AD6BD481207D}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {5432FA44-09C1-490B-8D66-AD6BD481207D}.Release|Any CPU.Build.0 = Release|Any CPU 28 | {5432FA44-09C1-490B-8D66-AD6BD481207D}.Release|x64.ActiveCfg = Release|Any CPU 29 | {5432FA44-09C1-490B-8D66-AD6BD481207D}.Release|x64.Build.0 = Release|Any CPU 30 | {5432FA44-09C1-490B-8D66-AD6BD481207D}.Release|x86.ActiveCfg = Release|Any CPU 31 | {5432FA44-09C1-490B-8D66-AD6BD481207D}.Release|x86.Build.0 = Release|Any CPU 32 | {95743AB8-A891-4CF9-8F7E-7FC7889B58FF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {95743AB8-A891-4CF9-8F7E-7FC7889B58FF}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {95743AB8-A891-4CF9-8F7E-7FC7889B58FF}.Debug|x64.ActiveCfg = Debug|Any CPU 35 | {95743AB8-A891-4CF9-8F7E-7FC7889B58FF}.Debug|x64.Build.0 = Debug|Any CPU 36 | {95743AB8-A891-4CF9-8F7E-7FC7889B58FF}.Debug|x86.ActiveCfg = Debug|Any CPU 37 | {95743AB8-A891-4CF9-8F7E-7FC7889B58FF}.Debug|x86.Build.0 = Debug|Any CPU 38 | {95743AB8-A891-4CF9-8F7E-7FC7889B58FF}.Release|Any CPU.ActiveCfg = Release|Any CPU 39 | {95743AB8-A891-4CF9-8F7E-7FC7889B58FF}.Release|Any CPU.Build.0 = Release|Any CPU 40 | {95743AB8-A891-4CF9-8F7E-7FC7889B58FF}.Release|x64.ActiveCfg = Release|Any CPU 41 | {95743AB8-A891-4CF9-8F7E-7FC7889B58FF}.Release|x64.Build.0 = Release|Any CPU 42 | {95743AB8-A891-4CF9-8F7E-7FC7889B58FF}.Release|x86.ActiveCfg = Release|Any CPU 43 | {95743AB8-A891-4CF9-8F7E-7FC7889B58FF}.Release|x86.Build.0 = Release|Any CPU 44 | EndGlobalSection 45 | GlobalSection(SolutionProperties) = preSolution 46 | HideSolutionNode = FALSE 47 | EndGlobalSection 48 | GlobalSection(ExtensibilityGlobals) = postSolution 49 | SolutionGuid = {518AC925-E07A-47F8-87A6-83E56D85D8F3} 50 | EndGlobalSection 51 | EndGlobal 52 | -------------------------------------------------------------------------------- /RefitGenerator/Generator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Net.Http; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | using Microsoft.OpenApi.Models; 9 | using Microsoft.OpenApi.Readers; 10 | using RefitGenerator.Helpers; 11 | 12 | using static RefitGenerator.Helpers.TypeHelper; 13 | using static RefitGenerator.Helpers.Strings; 14 | 15 | namespace RefitGenerator 16 | { 17 | public static class Generator 18 | { 19 | public static async Task Generate(GeneratorOptions options) 20 | { 21 | Stream openApiStream = null; 22 | if (options.Url != null) 23 | { 24 | var http = new HttpClient(); 25 | try 26 | { 27 | openApiStream = await http.GetStreamAsync(options.Url); 28 | } 29 | catch 30 | { 31 | ConsoleHelper.WriteLineColored("Failed to load data from the given URL", ConsoleColor.Red); 32 | } 33 | } 34 | else if (options.File != null) openApiStream = File.OpenRead(options.File.FullName); 35 | else 36 | { 37 | ConsoleHelper.WriteLineColored("Either a file or a url is required", ConsoleColor.Red); 38 | return; 39 | } 40 | 41 | try 42 | { 43 | if (options.RemoveIfExists && Directory.Exists(options.OutputDirectory.FullName)) 44 | Directory.Delete(options.OutputDirectory.FullName, true); 45 | 46 | if (!Directory.Exists(options.OutputDirectory.FullName)) 47 | Directory.CreateDirectory(options.OutputDirectory.FullName); 48 | 49 | if (options.ProjectName == null) options.ProjectName = options.OutputDirectory.Name; 50 | 51 | var openApiDocument = new OpenApiStreamReader().Read(openApiStream, out var diagnostic); 52 | openApiStream.Dispose(); 53 | 54 | File.Copy(Path.Combine(AppContext.BaseDirectory, TemplatesDirectory, options.Executable ? "CsprojExe.xml" : "CsprojLib.xml"), 55 | Path.Combine(options.OutputDirectory.FullName, options.ProjectName + ".csproj")); 56 | Directory.CreateDirectory(Path.Combine(options.OutputDirectory.FullName, ModelsDirectory)); 57 | Directory.CreateDirectory(Path.Combine(options.OutputDirectory.FullName, ApisDirectory)); 58 | 59 | if (openApiDocument.Components == null && openApiDocument.Paths == null) 60 | { 61 | ConsoleHelper.WriteLineColored("Input document is not an OpenApi definition.", ConsoleColor.Red); 62 | return; 63 | } 64 | 65 | SchemaProcessor.ProcessSchemas(options, openApiDocument.Components.Schemas); 66 | 67 | var allApis = new List(); 68 | foreach (var pathGroup in GetPathGroups(openApiDocument.Paths, options.GroupingStrategy)) 69 | { 70 | string apiName = pathGroup.Key.ToPascalCase(); 71 | allApis.Add(apiName); 72 | string apiCode = InterfaceWriter.GetApiInterface(options, pathGroup.Key, pathGroup); 73 | await File.WriteAllTextAsync(Path.Combine(options.OutputDirectory.FullName, ApisDirectory, $"I{apiName}Api.cs"), apiCode); 74 | } 75 | 76 | string clientCode = GetClientClass(options.ProjectName, allApis); 77 | await File.WriteAllTextAsync(Path.Combine(options.OutputDirectory.FullName, $"ApiClient.cs"), clientCode); 78 | 79 | if (options.Executable) 80 | { 81 | string programTemplate = File.ReadAllText(Path.Combine(AppContext.BaseDirectory, TemplatesDirectory, "ProgramTemplate.csx")); 82 | await File.WriteAllTextAsync( 83 | Path.Combine(options.OutputDirectory.FullName, "Program.cs"), 84 | string.Format(programTemplate, options.ProjectName, openApiDocument.Servers.FirstOrDefault()?.Url ?? "url missing!")); 85 | } 86 | } 87 | catch (IOException) 88 | { 89 | ConsoleHelper.WriteLineColored("Could not write to that location.", ConsoleColor.Red); 90 | } 91 | } 92 | 93 | private static IEnumerable>> GetPathGroups(OpenApiPaths paths, GroupingStrategy groupingStrategy) 94 | { 95 | static string FirstTagOrDefault(OpenApiPathItem path) => path.Operations.FirstOrDefault().Value?.Tags?.FirstOrDefault()?.Name ?? "Default"; 96 | static string MostCommonTag(OpenApiPathItem path, Dictionary tags, bool mostCommon) 97 | { 98 | var pathTags = path.Operations.FirstOrDefault().Value?.Tags?.Select(x => x.Name.ToPascalCase()); 99 | if (!pathTags?.Any() ?? true) return "Default"; 100 | var ordered = pathTags.OrderBy(x => tags[x]); 101 | return mostCommon ? ordered.Last() : ordered.First(); 102 | }; 103 | 104 | if (groupingStrategy == GroupingStrategy.FirstTag) 105 | { 106 | return paths.GroupBy(x => FirstTagOrDefault(x.Value)); 107 | } 108 | 109 | if (groupingStrategy == GroupingStrategy.MostCommonTag || groupingStrategy == GroupingStrategy.LeastCommonTag) 110 | { 111 | var allTags = paths.SelectMany(x => x.Value.Operations.SelectMany(x => x.Value.Tags)).Select(x => x.Name.ToPascalCase()); 112 | var tagDictionary = allTags.GroupBy(x => x).ToDictionary(k => k.Key, v => v.Count()); 113 | 114 | return paths.GroupBy(x => MostCommonTag(x.Value, tagDictionary, groupingStrategy == GroupingStrategy.MostCommonTag)); 115 | } 116 | 117 | throw new ArgumentException($"Unsupported value: {groupingStrategy}", nameof(groupingStrategy)); 118 | } 119 | 120 | private static string GetClientClass(string projectName, List allApis) 121 | { 122 | string clientTemplate = File.ReadAllText(Path.Combine(AppContext.BaseDirectory, TemplatesDirectory, "ClientTemplate.csx")); 123 | string properties = $"{Environment.NewLine}{string.Join(Environment.NewLine, allApis.Select(x => Indent2 + string.Format(ApiPropFormat, x)))}{Environment.NewLine}"; 124 | string constructor = string.Join(Environment.NewLine, allApis.Select(x => $"{Indent3}{x}Api = RestService.For(http);")); 125 | return string.Format(clientTemplate, projectName, constructor, properties); 126 | } 127 | } 128 | } -------------------------------------------------------------------------------- /RefitGenerator/GeneratorOptions.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.IO; 3 | 4 | namespace RefitGenerator 5 | { 6 | public class GeneratorOptions 7 | { 8 | public string Url { get; set; } 9 | public FileInfo File { get; set; } 10 | public DirectoryInfo OutputDirectory { get; set; } 11 | public string ProjectName { get; set; } 12 | public bool RemoveIfExists { get; set; } 13 | public bool Executable { get; set; } 14 | public GroupingStrategy GroupingStrategy { get; set; } 15 | public bool IgnoreAllHeaders { get; set; } 16 | public string[] IgnoredHeaders { get; set; } 17 | public bool AddEqualsNullToOptionalParameters { get; set; } 18 | public string ConflictingNameAffix { get; set; } 19 | public bool PrefixConflictingName { get; set; } 20 | public bool SkipDeprecatedProperties { get; set; } 21 | 22 | public Dictionary SimpleTypeMap { get; } = new Dictionary(); 23 | } 24 | 25 | public enum GroupingStrategy 26 | { 27 | FirstTag, MostCommonTag, LeastCommonTag 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /RefitGenerator/Helpers/CSharpKeywords.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | 4 | namespace RefitGenerator.Helpers 5 | { 6 | static class CSharpKeywords 7 | { 8 | private static readonly string[] keywords = new[] 9 | { 10 | "abstract", 11 | "as", 12 | "base", 13 | "body", // not really a keyword, but body is a reserved param name for this codebase 14 | "bool", 15 | "break", 16 | "byte", 17 | "case", 18 | "catch", 19 | "char", 20 | "checked", 21 | "class", 22 | "const", 23 | "continue", 24 | "decimal", 25 | "default", 26 | "delegate", 27 | "do", 28 | "double", 29 | "else", 30 | "enum", 31 | "event", 32 | "explicit", 33 | "extern", 34 | "false", 35 | "finally", 36 | "fixed", 37 | "float", 38 | "for", 39 | "foreach", 40 | "goto", 41 | "if", 42 | "implicit", 43 | "in", 44 | "int", 45 | "interface", 46 | "internal", 47 | "is", 48 | "lock", 49 | "long", 50 | "namespace", 51 | "new", 52 | "null", 53 | "object", 54 | "operator", 55 | "out", 56 | "override", 57 | "params", 58 | "private", 59 | "protected", 60 | "public", 61 | "readonly", 62 | "ref", 63 | "return", 64 | "sbyte", 65 | "sealed", 66 | "short", 67 | "sizeof", 68 | "stackalloc", 69 | "static", 70 | "string", 71 | "struct", 72 | "switch", 73 | "this", 74 | "throw", 75 | "true", 76 | "try", 77 | "typeof", 78 | "uint", 79 | "ulong", 80 | "unchecked", 81 | "unsafe", 82 | "ushort", 83 | "using", 84 | "virtual", 85 | "void", 86 | "volatile", 87 | "while" 88 | }; 89 | 90 | public static bool IsKeyword(string input) => keywords.Contains(input); 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /RefitGenerator/Helpers/ConsoleHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace RefitGenerator.Helpers 4 | { 5 | static class ConsoleHelper 6 | { 7 | public static void WriteLineColored(string content, ConsoleColor foreground) 8 | { 9 | var currentForeground = Console.ForegroundColor; 10 | Console.ForegroundColor = foreground; 11 | Console.WriteLine(content); 12 | Console.ForegroundColor = currentForeground; 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /RefitGenerator/Helpers/InterfaceWriter.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.OpenApi.Models; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Text; 7 | 8 | using static RefitGenerator.Helpers.Strings; 9 | using static RefitGenerator.Helpers.TypeHelper; 10 | 11 | namespace RefitGenerator.Helpers 12 | { 13 | static class InterfaceWriter 14 | { 15 | private static readonly string[] nonNullableTypes = { "int", "double", "float", "long", "DateTime", "bool" }; 16 | 17 | public static string GetApiInterface(GeneratorOptions options, string apiName, IEnumerable> paths) 18 | { 19 | var sb = new StringBuilder(); 20 | string interfaceTemplate = File.ReadAllText(Path.Combine(AppContext.BaseDirectory, TemplatesDirectory, "InterfaceTemplate.csx")); 21 | 22 | foreach (var path in paths) 23 | { 24 | foreach (var operationDefiniton in path.Value.Operations) 25 | { 26 | var method = operationDefiniton.Key; 27 | var operation = operationDefiniton.Value; 28 | 29 | sb.Append(GetApiInterfaceMethod(options, method, path.Key, operation)); 30 | } 31 | } 32 | 33 | return string.Format(interfaceTemplate, options.ProjectName, apiName.ToPascalCase(), sb.ToString()); 34 | } 35 | 36 | private static string GetApiInterfaceMethod(GeneratorOptions options, OperationType method, string path, OpenApiOperation operation) 37 | { 38 | var sb = new StringBuilder(); 39 | sb.AppendLine(); 40 | 41 | if (operation.Deprecated) 42 | sb.AppendLine(Indent2 + "[Obsolete]"); 43 | 44 | var bodyContent = operation.RequestBody?.Content; 45 | bool isMultipart = bodyContent != null && (bodyContent.ContainsKey(MultipartFormData) || bodyContent.ContainsKey(FormDataUrlEncoded)); 46 | if (isMultipart) sb.AppendLine(Indent2 + "[Multipart]"); // is it a multipart upload endpoint? 47 | 48 | sb.AppendFormat(Indent2 + RefitAttributeFormat, method, path); // write refit attribute 49 | sb.AppendLine(); 50 | 51 | string operationName = GetOperationName(operation, method, path); 52 | // assuming there's at most one type of success response per operation 53 | // if there's none or content is not defined - do not expect response content type 54 | var success = operation.Responses.FirstOrDefault(x => x.Key.StartsWith("2")); 55 | var responseSchema = success.Value?.Content?.FirstOrDefault().Value?.Schema; 56 | string returnType = "Task"; 57 | if (responseSchema != null && (!responseSchema.Properties.Any() || responseSchema.Reference != null)) 58 | { 59 | returnType = $"Task<{ToCLRType(options, operationName, "Response", responseSchema)}>"; 60 | } 61 | else if (responseSchema != null && responseSchema.Reference == null) 62 | { 63 | // if response schema is not in the references section but defined per operation 64 | ModelWriter.WriteModel(options, operationName + "Response", responseSchema.Properties); 65 | returnType = $"Task<{operationName}Response>"; 66 | } 67 | 68 | // build parameters list from query, route, body, etc. 69 | string parameters = string.Join(", ", ParseBody(options, operationName, operation.RequestBody) 70 | .Concat(operation.Parameters 71 | .OrderByDescending(x => x.Required) 72 | .Select(x => ParseParameter(options, operationName, x)) 73 | .Where(x => x != null))); 74 | 75 | sb.AppendLine($"{Indent2}{returnType} {operationName}({parameters});"); 76 | 77 | return sb.ToString(); 78 | } 79 | 80 | private static string GetOperationName(OpenApiOperation operation, OperationType operationType, string path) 81 | { 82 | if (operation.OperationId != null) 83 | return operation.OperationId.ToPascalCase(); 84 | 85 | // operation id not found, create a name from method and route 86 | return operationType + "__" + string.Join("_", 87 | path.Split('/', StringSplitOptions.RemoveEmptyEntries).Where(x => !x.StartsWith("{")).Select(x => x.ToPascalCase())); 88 | } 89 | 90 | private static string ParseParameter(GeneratorOptions options, string operationName, OpenApiParameter parameter) 91 | { 92 | var nameSegments = new List(); 93 | string camelCaseName = parameter.Name.ToCamelCase(); 94 | 95 | if (parameter.In == ParameterLocation.Header) 96 | { 97 | if (options.IgnoreAllHeaders || (options.IgnoredHeaders?.Contains(parameter.Name) ?? false)) 98 | { 99 | return null; 100 | } 101 | 102 | nameSegments.Add($"[Header(\"{parameter.Name}\")]"); 103 | } 104 | 105 | if (parameter.In == ParameterLocation.Query) 106 | nameSegments.Add("[Query]"); 107 | 108 | if (parameter.In != ParameterLocation.Header && camelCaseName != parameter.Name) 109 | nameSegments.Add($"[AliasAs(\"{parameter.Name}\")]"); 110 | 111 | string parameterType = ToCLRType(options, operationName, "Parameter", parameter.Schema); 112 | 113 | if (!parameter.Required && !parameterType.EndsWith("?") && nonNullableTypes.Contains(parameterType)) 114 | { 115 | parameterType += "?"; 116 | } 117 | 118 | nameSegments.Add(parameterType); 119 | 120 | if (CSharpKeywords.IsKeyword(camelCaseName)) 121 | { 122 | camelCaseName = "@" + camelCaseName; 123 | } 124 | 125 | if (!parameter.Required && options.AddEqualsNullToOptionalParameters) 126 | { 127 | camelCaseName += " = null"; 128 | } 129 | 130 | nameSegments.Add(camelCaseName); 131 | return string.Join(" ", nameSegments); 132 | } 133 | 134 | private static IEnumerable ParseBody(GeneratorOptions options, string operationName, OpenApiRequestBody body) 135 | { 136 | if (body == null || body.Content == null) return Array.Empty(); 137 | if (body.Content.ContainsKey(MultipartFormData) || body.Content.ContainsKey(FormDataUrlEncoded)) 138 | { 139 | var parameters = new List(); 140 | body.Content.TryGetValue(MultipartFormData, out var multipart); 141 | body.Content.TryGetValue(FormDataUrlEncoded, out var formData); 142 | 143 | foreach (var property in (multipart ?? formData).Schema.Properties) 144 | { 145 | string propertyName = property.Key; 146 | var propertySchema = property.Value; 147 | string camelCaseName = propertyName.ToCamelCase(); 148 | 149 | if (propertySchema.Type == "array" && propertySchema.Items.Type == "string" && propertySchema.Items.Format == "binary") 150 | { 151 | if (camelCaseName != propertyName) 152 | parameters.Add($"[AliasAs(\"{propertyName}\")] IEnumerable {camelCaseName}"); 153 | else parameters.Add($"IEnumerable {camelCaseName}"); 154 | } 155 | else if (propertySchema.Type == "file" || propertySchema.Type == "string" && propertySchema.Format == "binary") 156 | { 157 | if (camelCaseName != propertyName) 158 | parameters.Add($"[AliasAs(\"{propertyName}\")] StreamPart {camelCaseName}"); 159 | else parameters.Add($"StreamPart {camelCaseName}"); 160 | } 161 | else 162 | { 163 | if (camelCaseName != propertyName) 164 | parameters.Add($"[AliasAs(\"{propertyName}\")] {ToCLRType(options, operationName, "Parameter", propertySchema)} {camelCaseName}"); 165 | else parameters.Add($"{ToCLRType(options, operationName, "Parameter", propertySchema)} {camelCaseName}"); 166 | } 167 | } 168 | 169 | return parameters; 170 | } 171 | 172 | return new[] { $"[Body] {ToCLRType(options, operationName, "Body", body.Content.FirstOrDefault().Value?.Schema)} body" }; 173 | } 174 | } 175 | } 176 | -------------------------------------------------------------------------------- /RefitGenerator/Helpers/ModelWriter.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.OpenApi.Models; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Text; 6 | using System.Text.RegularExpressions; 7 | using static RefitGenerator.Helpers.Strings; 8 | using static RefitGenerator.Helpers.TypeHelper; 9 | 10 | namespace RefitGenerator.Helpers 11 | { 12 | static class ModelWriter 13 | { 14 | private static readonly Regex propertyRegex = new Regex("[^a-zA-Z].*"); 15 | 16 | public static void WriteModel(GeneratorOptions options, string className, IDictionary properties) 17 | { 18 | string classCode = GetModelClass(options, className, properties); 19 | File.WriteAllText(Path.Combine(options.OutputDirectory.FullName, ModelsDirectory, className + ".cs"), classCode); 20 | } 21 | 22 | static string GetModelClass(GeneratorOptions options, string className, IDictionary properties) 23 | { 24 | var sb = new StringBuilder(); 25 | string modelTemplate = File.ReadAllText(Path.Combine(AppContext.BaseDirectory, TemplatesDirectory, "ModelTemplate.csx")); 26 | 27 | foreach (var property in properties) 28 | { 29 | 30 | string originalName = property.Key; 31 | var propertySchema = property.Value; 32 | 33 | if (options.SkipDeprecatedProperties && propertySchema.Deprecated) continue; 34 | 35 | string propertyName = originalName.ToPascalCase(); 36 | if (propertyRegex.IsMatch(propertyName)) 37 | propertyName = "Property_" + propertyName; 38 | 39 | // so that conflict-resolving affixes do not pollute the class name 40 | string propertyAsTypeName = propertyName; 41 | 42 | if (propertyName == className) 43 | { 44 | if (options.PrefixConflictingName) 45 | propertyName = options.ConflictingNameAffix + propertyName; 46 | else 47 | propertyName += options.ConflictingNameAffix; 48 | } 49 | 50 | sb.AppendLine(); 51 | if (propertySchema.Deprecated) 52 | { 53 | sb.AppendLine(Indent2 + "[Obsolete]"); 54 | } 55 | sb.AppendFormat(Indent2 + JpnFormat, originalName); 56 | sb.AppendLine(); 57 | sb.AppendFormat(Indent2 + ModelPropFormat, ToCLRType(options, className, propertyAsTypeName, propertySchema), propertyName); 58 | sb.AppendLine(); 59 | } 60 | 61 | return string.Format(modelTemplate, options.ProjectName, className, sb.ToString()); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /RefitGenerator/Helpers/SchemaProcessor.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.OpenApi.Models; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace RefitGenerator.Helpers 9 | { 10 | static class SchemaProcessor 11 | { 12 | public static void ProcessSchemas(GeneratorOptions options, IDictionary schemas) 13 | { 14 | // process definitions for simple types 15 | var simpleTypes = schemas.Where(x => !x.Value.Properties.Any() && !x.Value.OneOf.Any() && 16 | !x.Value.AllOf.Any() && !x.Value.OneOf.Any() && x.Value.Type != null && 17 | (x.Value.Type != "array" || x.Value.Type == "array" && x.Value.Items.Type != "object")); 18 | 19 | foreach (var type in simpleTypes) 20 | { 21 | options.SimpleTypeMap.Add(type.Key, TypeHelper.ToCLRSimpleType(options, type.Value)); 22 | } 23 | 24 | 25 | var compoundKeys = schemas.Keys.Except(simpleTypes.Select(x => x.Key)); 26 | foreach (var key in compoundKeys) 27 | { 28 | TypeHelper.GetCompoundType(options, key.ToPascalCase(), schemas[key]); 29 | } 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /RefitGenerator/Helpers/StringExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Text.RegularExpressions; 3 | 4 | namespace RefitGenerator.Helpers 5 | { 6 | static class StringExtensions 7 | { 8 | private static readonly Regex splitRegex = new ("\\W|_"); 9 | 10 | public static string ToPascalCase(this string input) => 11 | string.Join("", splitRegex.Split(input) 12 | .Select(x => x.Trim()) 13 | .Where(x => !string.IsNullOrWhiteSpace(x)) 14 | .Select(Capitalize)); 15 | 16 | public static string Capitalize(this string input) => input[0].ToString().ToUpper() + input[1..]; 17 | 18 | public static string ToCamelCase(this string input) 19 | { 20 | var segments = splitRegex.Split(input).Select(x => x.Trim()).Where(x => !string.IsNullOrWhiteSpace(x)).ToArray(); 21 | return string.Join("", new string[] { segments[0] }.Concat(segments[1..].Select(Capitalize))); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /RefitGenerator/Helpers/Strings.cs: -------------------------------------------------------------------------------- 1 | namespace RefitGenerator.Helpers 2 | { 3 | static class Strings 4 | { 5 | public const string Indent = " "; 6 | public const string Indent2 = Indent + Indent; 7 | public const string Indent3 = Indent2 + Indent; 8 | public const string JpnFormat = "[JsonPropertyName(\"{0}\")]"; 9 | public const string RefitAttributeFormat = "[{0}(\"{1}\")]"; 10 | public const string ModelPropFormat = "public {0} {1} {{ get; set; }}"; 11 | public const string ApiPropFormat = "public I{0}Api {0}Api {{ get; }}"; 12 | public const string MultipartFormData = "multipart/form-data"; 13 | public const string FormDataUrlEncoded = "application/x-www-form-urlencoded"; 14 | public const string TemplatesDirectory = "Templates"; 15 | public const string ModelsDirectory = "Models"; 16 | public const string ApisDirectory = "Apis"; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /RefitGenerator/Helpers/TypeHelper.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.OpenApi.Models; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | 6 | namespace RefitGenerator.Helpers 7 | { 8 | static class TypeHelper 9 | { 10 | public static string ToCLRSimpleType(GeneratorOptions options, OpenApiSchema property) => 11 | property switch 12 | { 13 | { Type: "array" } => ToCLRSimpleType(options, property.Items) + "[]", 14 | { Type: "string", Format: "binary" } => "Stream", 15 | { Type: "string", Format: "date" or "date-time" } => "DateTime" + Nullable(property), 16 | { Type: "string" } => "string", 17 | { Type: "boolean" } => "bool" + Nullable(property), 18 | { Type: "number", Format: "float" } => "float" + Nullable(property), 19 | { Type: "number" } => "double" + Nullable(property), 20 | { Type: "integer", Format: "int64" } => "long" + Nullable(property), 21 | { Type: "integer" } => "int" + Nullable(property), 22 | _ => "object" 23 | }; 24 | 25 | public static string ToCLRType(GeneratorOptions options, string enclosingType, string propertyName, OpenApiSchema property) => 26 | property switch 27 | { 28 | { Type: "array" } => ToCLRType(options, enclosingType, propertyName, property.Items) + "[]", 29 | { Items: { } } => ToCLRType(options, enclosingType, propertyName, property.Items) + "[]", 30 | { Type: "string", Format: "binary" } => "Stream", 31 | { Type: "string", Format: "date" or "date-time" } => "DateTime" + Nullable(property), 32 | { Type: "string" } => "string", 33 | { Type: "boolean" } => "bool" + Nullable(property), 34 | { Type: "number", Format: "float" } => "float" + Nullable(property), 35 | { Type: "number" } => "double" + Nullable(property), 36 | { Type: "integer", Format: "int64" } => "long" + Nullable(property), 37 | { Type: "integer" } => "int" + Nullable(property), 38 | { AdditionalProperties: { } ap } => $"Dictionary", 39 | { Reference: { Id: { } id } } => options.SimpleTypeMap.ContainsKey(id) ? options.SimpleTypeMap[id] : id.ToPascalCase(), 40 | { } => GetCompoundType(options, $"{enclosingType}_{propertyName}", property), 41 | _ => "object" 42 | }; 43 | 44 | public static string GetCompoundType(GeneratorOptions options, string typeName, OpenApiSchema schema) 45 | { 46 | var allProperties = new List(); 47 | ScanSchemaProperties(schema, allProperties); 48 | var properties = allProperties 49 | .SelectMany(x => x.Properties) 50 | .Concat(schema.Properties) 51 | .GroupBy(x => x.Key) 52 | .ToDictionary(k => k.Key, v => v.First().Value); 53 | 54 | if (!properties.Any()) return "object"; 55 | 56 | ModelWriter.WriteModel(options, typeName, properties); 57 | return typeName; 58 | } 59 | 60 | private static void ScanSchemaProperties(OpenApiSchema schema, List all) 61 | { 62 | if (schema == null) return; 63 | 64 | all.AddRange(schema.AllOf); 65 | all.AddRange(schema.AnyOf); 66 | // todo: OneOf ??? 67 | 68 | foreach (var allOf in schema.AllOf) ScanSchemaProperties(allOf, all); 69 | foreach (var anyOf in schema.AnyOf) ScanSchemaProperties(anyOf, all); 70 | } 71 | 72 | private static string Nullable(OpenApiSchema property) => property.Nullable ? "?" : string.Empty; 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /RefitGenerator/Program.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using System.IO; 3 | using System.CommandLine; 4 | using System.CommandLine.Invocation; 5 | 6 | namespace RefitGenerator 7 | { 8 | class Program 9 | { 10 | static async Task Main(string[] args) 11 | { 12 | var rootCommand = new RootCommand("A utility to generate Refit client code from OpenApi json or yaml") 13 | { 14 | new Option(new[] { "-u", "--url" }) 15 | { 16 | Description = "A url to OpenApi json or yaml" 17 | }, 18 | new Option(new[] { "-f", "--file" }) 19 | { 20 | Description = "Path to OpenApi json or yaml file" 21 | }, 22 | new Option(new[] { "-o", "--outputDirectory" }, () => new DirectoryInfo("./")) 23 | { 24 | Description = "Output directory" 25 | }, 26 | new Option(new[] { "-p", "--projectName" }) 27 | { 28 | Description = "Project name and namespace", 29 | }, 30 | new Option(new [] { "--groupBy", "--groupingStrategy" }, () => GroupingStrategy.FirstTag) 31 | { 32 | Description = "Strategy for grouping paths into api interfaces" 33 | }, 34 | new Option(new[] { "-r", "--removeIfExists" }) 35 | { 36 | Description = "Remove target directory if exists" 37 | }, 38 | new Option("--executable", "Generate a .NET 5 console app instead of .NET Standard 2.0 library"), 39 | new Option("--ignoreAllHeaders", "Ignores all header parameters"), 40 | new Option("--ignoredHeaders", "Provides a list of headers to ignore"), 41 | new Option("--addEqualsNullToOptionalParameters", "Makes optional parameters have a default null value in api interfaces"), 42 | new Option("--conflictingNameAffix", () => "Prop") 43 | { 44 | // todo - validate if not stupid? 45 | Description = "A string a property name will be prefixed with to avoid conflict with the enclosing type name", 46 | }, 47 | new Option("--prefixConflictingName", "Whether to prefix or suffix the conflicting property name with configured affix"), 48 | new Option("--skipDeprecatedProperties", "Whether to skip deprecated properties or include them with [Obsolete] attribute") 49 | }; 50 | 51 | rootCommand.Handler = CommandHandler.Create(Generator.Generate); 52 | 53 | await rootCommand.InvokeAsync(args); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /RefitGenerator/RefitGenerator.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | Exe 4 | net5.0 5 | true 6 | regen 7 | ./nupkg 8 | 0.8.2 9 | Velorien 10 | 11 | MIT 12 | Velorien 13 | https://github.com/velorien/refitgenerator 14 | https://github.com/velorien/refitgenerator 15 | A tool to generate Refit client code from OpenApi definitions 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | PreserveNewest 29 | 30 | 31 | PreserveNewest 32 | 33 | 34 | PreserveNewest 35 | 36 | 37 | PreserveNewest 38 | 39 | 40 | PreserveNewest 41 | 42 | 43 | PreserveNewest 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /RefitGenerator/Templates/ClientTemplate.csx: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net.Http; 3 | using Refit; 4 | using {0}.Apis; 5 | 6 | namespace {0} 7 | {{ 8 | public class ApiClient 9 | {{ 10 | public ApiClient(HttpClient http) 11 | {{ 12 | {1} 13 | }} 14 | {2} }} 15 | }} 16 | -------------------------------------------------------------------------------- /RefitGenerator/Templates/CsprojExe.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | Exe 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /RefitGenerator/Templates/CsprojLib.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /RefitGenerator/Templates/InterfaceTemplate.csx: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Threading.Tasks; 4 | using System.Collections.Generic; 5 | using Refit; 6 | 7 | using {0}.Models; 8 | 9 | namespace {0}.Apis 10 | {{ 11 | public interface I{1}Api 12 | {{{2} }} 13 | }} 14 | -------------------------------------------------------------------------------- /RefitGenerator/Templates/ModelTemplate.csx: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text.Json.Serialization; 4 | 5 | namespace {0}.Models 6 | {{ 7 | public class {1} 8 | {{{2} }} 9 | }} 10 | -------------------------------------------------------------------------------- /RefitGenerator/Templates/ProgramTemplate.csx: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net.Http; 3 | using System.Threading.Tasks; 4 | 5 | using {0}.Models; 6 | 7 | namespace {0} 8 | {{ 9 | class Program 10 | {{ 11 | static async Task Main(string[] args) 12 | {{ 13 | var http = new HttpClient(); 14 | http.BaseAddress = new Uri("{1}"); 15 | var apiClient = new ApiClient(http); 16 | }} 17 | }} 18 | }} 19 | -------------------------------------------------------------------------------- /RefitGenerator/pack.ps1: -------------------------------------------------------------------------------- 1 | rm -r nupkg 2 | dotnet pack 3 | dotnet tool uninstall -g RefitGenerator 4 | dotnet tool install -g --add-source nupkg RefitGenerator -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # RefitGenerator 2 | _aka `regen`_ 3 | 4 | [![nuget](https://img.shields.io/nuget/v/RefitGenerator)](https://www.nuget.org/packages/RefitGenerator/) 5 | 6 | RefitGenerator is a global `dotnet tool` used to generate [Refit](https://github.com/reactiveui/refit) client code from OpenApi schemas. 7 | 8 | ## Installation 9 | 10 | With .NET 5 installed run: `dotnet tool install -g refitgenerator` 11 | 12 | ## Usage 13 | 14 | Typing `regen -h` will display a list of parameters: 15 | 16 | * `-u` or `--url` - url to OpenApi json or yaml 17 | * `-f` or `--file` - path to OpenApi json or yaml local file 18 | * `-o` or `--outputDirectory` - where to put the generated files 19 | * defaults to the current directory 20 | * `-p` or `--projectName` - project name and root namespace 21 | * defaults to the output directory name 22 | * `--groupBy` or `--groupingStrategy` - method of grouping paths into interfaces 23 | * defaults to `FirstTag` 24 | * possible values 25 | * `FirstTag` - uses the first tag in the array for the given path 26 | * `MostCommonTag` - uses the most used tag, produces the smallest number of interfaces 27 | * `LeastCommonTag` - uses the least used tag, produces the largest number of finely grained interfaces 28 | * `-r` or `--removeIfExists` - a flag which controls whether to delete the output directory if exists first 29 | * `--executable` - generate a .NET 5 console app with a basic setup instead of .NET Standard 2.0 class library 30 | * `--ignoreAllHeaders` - do not include any header parameters in the resulting code 31 | * `--ignoredHeaders` - provide a list of headers to ignore, redundant if `--ignoreAllHeaders` flag is used 32 | * `--addEqualsNullToOptionalParameters` - if a method parameter is optional, it is generated with a default value of null 33 | * `--conflictingNameAffix` - adds an affix to a property if its name conflicts with the enclosing type name, not validated whether the resulting property name is a valid identifier 34 | * defaults to `Prop` 35 | * `--prefixConflictingName` - if this flag is set, the `--conflictingNameAffix` will be a prefix, otherwise it will be a suffix 36 | * `--skipDeprecatedProperties` - if this flag is set, schema properties marked as `Deprecated` are not included in the model 37 | 38 | ## Caveats 39 | 40 | * This tool does not resolve conflicting type names. For instance, if your schema defines a type which generates a class named `Environment`, you see an error that `System.Environment` conflicts with `YourNamespace.Models.Environment` 41 | * If an object schema has nested, non-reference object schemas, the tool cannot give the nested nice names, so the resulting type name will be `ParentType_PropertyName` 42 | 43 | ## Dependencies 44 | 45 | * [System.Commandline](https://github.com/dotnet/command-line-api) for parsing commandline parameters 46 | * [OpenAPI.NET](https://github.com/microsoft/OpenAPI.NET) - for reading the OpenApi schemas 47 | 48 | ## Try it out 49 | 50 | * [Github API](https://raw.githubusercontent.com/github/rest-api-description/main/descriptions/api.github.com/api.github.com.yaml) - causes the conflict described in Caveats 51 | * [Petstore](https://petstore.swagger.io/v2/swagger.json) - the one and only 52 | * [Slack API](https://raw.githubusercontent.com/slackapi/slack-api-specs/master/web-api/slack_web_openapi_v2_without_examples.json) 53 | * [Official examples from spec](https://github.com/OAI/OpenAPI-Specification/tree/master/examples) --------------------------------------------------------------------------------