Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 0 additions & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,6 @@ dotnet_diagnostic.SA1200.severity = none
dotnet_diagnostic.SA1309.severity = none
dotnet_diagnostic.SA1310.severity = none
dotnet_diagnostic.SA1311.severity = none
dotnet_diagnostic.SA1503.severity = none
dotnet_diagnostic.SA1600.severity = none
dotnet_diagnostic.SA1623.severity = none
dotnet_diagnostic.SA1633.severity = silent
Expand Down
1 change: 0 additions & 1 deletion ApiCodeGenerator.ruleset
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,6 @@
<Rule Id="SA1309" Action="None" />
<Rule Id="SA1310" Action="None" />
<Rule Id="SA1311" Action="None" />
<Rule Id="SA1503" Action="None" />
<Rule Id="SA1600" Action="None" />
<Rule Id="SA1623" Action="None" />
<Rule Id="SA1633" Action="Hidden" />
Expand Down
4 changes: 4 additions & 0 deletions src/ApiCodeGenerator.Abstraction/AssemblyResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -113,14 +113,18 @@ public static void Unregister()
{
var thisAsm = Assembly.GetCallingAssembly();
if (assemblyName == thisAsm.GetName())
{
return null;
}

var path = _resolvers.Select(r => r.Invoke(assemblyName)).FirstOrDefault(p => p != null);

var key = assemblyName.Name;

if (path == null && _asmPaths.TryGetValue(key, out var item))
{
path = item.Path;
}

return path == null
? null
Expand Down
2 changes: 1 addition & 1 deletion src/ApiCodeGenerator.Abstraction/GeneratorContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ internal GeneratorContext(

public ILogger? Logger { get; internal set; }

public T? GetSettings<T>(JsonSerializer? jsonSerializer = null, IReadOnlyDictionary<string, string>? additionalVariables = null)
public T? GetSettings<T>(JsonSerializer? jsonSerializer, IReadOnlyDictionary<string, string>? additionalVariables)
where T : class
=> (T?)_settingsFactory(typeof(T), jsonSerializer, additionalVariables);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ protected CSharpGeneratorBaseSettings()

CSharpGeneratorSettings.TemplateFactory = new DefaultTemplateFactory(CSharpGeneratorSettings, new[]
{
typeof(CSharpGeneratorBaseSettings).GetType().Assembly,
typeof(CSharpGeneratorSettings).GetType().Assembly,
GetType().Assembly,
typeof(CSharpGeneratorSettings).Assembly,
});

ResponseArrayType = "System.Collections.Generic.ICollection";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,13 @@ public CSharpOperationModel(

public CSharpParameterModel[] Parameters { get; }

public string PayloadType => _payloadType ??= ResolvePayloadType(Operation.Message.ActualObject.Payload.ActualSchema);
public string PayloadType => _payloadType ??= ResolvePayloadType(Operation.Message.ActualObject.Payload.ActualSchema, hint: null);

protected Channel Channel { get; }

protected Operation Operation { get; }

protected virtual string ResolvePayloadType(JsonSchema jsonSchema, string? hint = null)
protected virtual string ResolvePayloadType(JsonSchema jsonSchema, string? hint)
{
if (!jsonSchema.HasTypeNameTitle && string.IsNullOrEmpty(hint))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object? exis
/// <inheritdoc/>
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
throw new NotSupportedException();
}

private static Dictionary<string, Func<T>> GetFactories()
Expand Down
12 changes: 12 additions & 0 deletions src/ApiCodeGenerator.Core/ApiDocumentProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,29 +43,41 @@ public ApiDocumentProvider(IFileProvider fileProvider, HttpClient httpClient)
else
{
if (Uri.TryCreate(documentSource.FromDocument.Url, UriKind.Absolute, out var url))
{
return await FromUrlAsync(url);
}
else
{
return Failed("Invalid url format", null);
}
}
}
else
{
var json = documentSource.FromDocument.Json!;
if (IsPath(json))
{
return await FromFileAsync(json);
}
else
{
return FromContent(json, null);
}
}
}

if (documentSource.JsonSchemaToOpenApi != null)
{
var data = documentSource.JsonSchemaToOpenApi;
if (string.IsNullOrEmpty(data.Name))
{
return Failed("jsonSchemaToOpenApi.name must be not null or empty", null);
}

if (string.IsNullOrEmpty(data.Schema))
{
return Failed("jsonSchemaToOpenApi.schema must be not null or empty", null);
}

if (IsPath(data.Schema))
{
Expand Down
6 changes: 6 additions & 0 deletions src/ApiCodeGenerator.Core/ExtensionManager/ExtensionLoader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,15 @@ private static void GetAndMergeDict<T>(Type type, string propName, Dictionary<st
if (propInfo != null)
{
if (!typeof(IDictionary<string, T>).IsAssignableFrom(propInfo.PropertyType))
{
throw new InvalidOperationException($"Property {propName} in assembly {type.Assembly.FullName} must return type IDictionary<string, {typeof(T)}>");
}

var value = (IDictionary<string, T>)propInfo.GetValue(type, null);
foreach (var kv in value)
{
dict.Add(kv.Key, kv.Value);
}
}
}

Expand All @@ -80,7 +84,9 @@ private static void GetAndMergeDictOfList<T>(Type type, string propName, Diction
if (propInfo != null)
{
if (!typeof(IDictionary<string, T>).IsAssignableFrom(propInfo.PropertyType))
{
throw new InvalidOperationException($"Property {propName} in assembly {type.Assembly.FullName} must return type IDictionary<string, {typeof(T)}>");
}

var value = (IDictionary<string, T>)propInfo.GetValue(type, null);
if (value.Any())
Expand Down
2 changes: 1 addition & 1 deletion src/ApiCodeGenerator.Core/ExtensionManager/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ namespace ApiCodeGenerator.Core.ExtensionManager
/// <summary>
/// Информация о расширениях.
/// </summary>
public class Extensions : IExtensions
internal class Extensions : IExtensions
{
public Extensions(
IReadOnlyDictionary<string, ContentGeneratorFactory>? codeGenerators = null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ public override bool CanConvert(Type objectType)
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
if (reader.Value != null)
{
return _replaceExpression.Replace((string)reader.Value, Replace);
}

return null;
}
Expand Down
10 changes: 10 additions & 0 deletions src/ApiCodeGenerator.Core/NswagDocument/PreprocessorHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,29 @@ internal static class PreprocessorHelper
public static Preprocessors GetPreprocessors(IExtensions? extensions, IDictionary<string, JObject?>? processors, ILogger? log)
{
if (processors == null)
{
return new Preprocessors(new Dictionary<Type, Delegate[]>());
}

var result = new Dictionary<Type, List<Delegate>>();
foreach (var name in processors.Keys)
{
var value = processors[name]?.ToString(Formatting.None);

if (extensions?.Preprocessors.TryGetValue(name, out var type) != true)
{
throw new InvalidOperationException($"Preprocessor with name '{name}' not registred.");
}

foreach (var (dataType, dlgt) in CreatePreprocessors(name, type, value, log))
if (result.TryGetValue(dataType, out var list))
{
list.Add(dlgt);
}
else
{
result[dataType] = new List<Delegate> { dlgt };
}
}

return new Preprocessors(result.ToDictionary(i => i.Key, i => i.Value.ToArray()));
Expand All @@ -41,7 +49,9 @@ public static Preprocessors GetPreprocessors(IExtensions? extensions, IDictionar
var ctor = type.GetConstructors().First();
var ctorParams = ctor.GetParameters();
if (ctorParams.Length > 1 || (ctorParams.Length == 1 && ctorParams[0].ParameterType != typeof(string)))
{
throw new InvalidOperationException($"Constructor with one or zero parameters not found for preprocessor '{name}'");
}

var processor = ctor.GetParameters().Length == 0
? Activator.CreateInstance(type)
Expand Down
4 changes: 4 additions & 0 deletions src/ApiCodeGenerator.Core/NswagDocumentFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,9 @@ public Document LoadNswagDocument(TextReader reader, IReadOnlyDictionary<string,
};

if (variables?.Any() == true)
{
settings.Converters.Add(new VariableConverter(variables));
}

var jsonSerializer = JsonSerializer.Create(settings);
Document? document;
Expand Down Expand Up @@ -137,7 +139,9 @@ void MergeObject(IContractResolver contractResolver, JObject doc, JObject baseDo
curSrcToken = curSrcToken[curProp.PropertyName] as JObject;

if (curSrcToken is null || curTargToken is null)
{
break;
}

curContract = contractResolver.ResolveContract(curProp.PropertyType);
}
Expand Down
2 changes: 2 additions & 0 deletions src/ApiCodeGenerator.Core/PhysicalFileProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@ public async Task WriteAllTextAsync(string path, string contents)
{
var outDir = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(outDir) && !Directory.Exists(outDir))
{
Directory.CreateDirectory(outDir);
}

using var stream = File.Open(path, FileMode.Create, FileAccess.Write, FileShare.None);
using var writer = new StreamWriter(stream);
Expand Down
2 changes: 1 addition & 1 deletion src/ApiCodeGenerator.OpenApi/ContentGeneratorBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ protected static T InvokePreprocessors<T>(T data,
return data;
}

protected static TSettings ParseSettings(GeneratorContext context, IReadOnlyDictionary<string, string>? variables = null)
protected static TSettings ParseSettings(GeneratorContext context, IReadOnlyDictionary<string, string>? variables)
{
var unwrapProps = new[]
{
Expand Down
6 changes: 6 additions & 0 deletions src/ApiCodeGenerator.OpenApi/Converters/SettingsConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -104,13 +104,19 @@ void FillProperties(object targetObject, params string[] unwrapProp)
{
var pos = Array.IndexOf(unwrapProp, p.Name);
if (pos > -1)
{
forUnwrap[pos] = p;
}
else
{
props[p.Name] = (p, targetObject);
}
}

foreach (var item in forUnwrap.Where(pi => pi != null))
{
FillProperties(item.GetValue(targetObject), unwrapProp);
}
}
}
}
Expand Down
12 changes: 6 additions & 6 deletions src/ApiCodeGenerator.OpenApi/DefaultTemplateFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ public interface ITemplateProvider
{
string? GetFullName(string name, string language);

string? GetTemplateText(string fullName, string language);
string? GetTemplateText(string templateFullName, string language);
}

[System.Diagnostics.CodeAnalysis.SuppressMessage("Ordering Rules", "SA1402", Justification = "none")]
Expand All @@ -145,9 +145,9 @@ public EmbededResourceTemplateProvider(Assembly assembly, string resourcePrefix)
: null;
}

public string? GetTemplateText(string resourceName, string language)
public string? GetTemplateText(string templateFullName, string language)
{
var resource = _assembly.GetManifestResourceStream(resourceName);
var resource = _assembly.GetManifestResourceStream(templateFullName);
if (resource != null)
{
using var reader = new StreamReader(resource);
Expand Down Expand Up @@ -181,11 +181,11 @@ public DirectoryTemplateProvider(string path)
return null;
}

public string? GetTemplateText(string templateFilePath, string language)
public string? GetTemplateText(string templateFullName, string language)
{
if (File.Exists(templateFilePath))
if (File.Exists(templateFullName))
{
return File.ReadAllText(templateFilePath);
return File.ReadAllText(templateFullName);
}

return null;
Expand Down
4 changes: 4 additions & 0 deletions src/ApiCodeGenerator.OpenApi/Helpers/SettingsHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,19 @@ public static void SetSpecialSettings(IExtensions? extensions, ClientGeneratorBa
{
var mode = ((JToken?)value)?.Value<string>();
if (mode is not null)
{
SetOperationMode(extensions, settings, mode);
}
}
else if (propertyName.Equals("replaceNameCollection", StringComparison.OrdinalIgnoreCase))
{
if (((JToken?)value)?.Type == JTokenType.Object)
{
var replacementData = ((JObject)value).ToObject<IDictionary<string, string>>();
if (replacementData is not null)
{
SetReplaceCollection(settings, replacementData);
}
}
else
{
Expand Down
2 changes: 1 addition & 1 deletion test/ApiCodeGenerator.Core.Tests/GeneratorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ public async Task RunCodeGeneration()
Assert.True(result);
Assert.NotNull(generatorMock.Object.Context);
Assert.NotNull(generatorMock.Object.Context.DocumentReader);
Assert.NotNull(generatorMock.Object.Context.GetSettings<JObject>());
Assert.NotNull(generatorMock.Object.Context.GetSettings<JObject>(null, null));
generatorMock.Verify(g => g.Generate(), Times.Once);
_fileProviderMock.Verify(fp => fp.WriteAllTextAsync(It.Is<string>(v => v == OutFilePath), It.IsAny<string>()), Times.Once);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ internal class FakeCodeGenerator : IContentGenerator
public FakeCodeGenerator(GeneratorContext context, Dictionary<string, string>? additionalVars = null)
{
Context = context;
Settings = context.GetSettings<FakeCodeGeneratorSettings>(additionalVariables: additionalVars);
Settings = context.GetSettings<FakeCodeGeneratorSettings>(null, additionalVariables: additionalVars);
}

public GeneratorContext Context { get; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,14 @@ public TestTemplateProvider(string templateText)
_templateText = templateText;
}

public string? GetFullName(string name, string language)
string? ITemplateProvider.GetFullName(string name, string language)
{
return name == "Class"
? $"{_providerKey}.{name}"
: null;
}

public string? GetTemplateText(string name, string language)
string? ITemplateProvider.GetTemplateText(string name, string language)
{
if (name.StartsWith(_providerKey))
{
Expand Down
Loading