Skip to content

Commit

Permalink
feat(): clean up validations
Browse files Browse the repository at this point in the history
Signed-off-by: Joe Feser <[email protected]>

feat(): clean up generator so we can format the files correctly

Signed-off-by: Joe Feser <[email protected]>
  • Loading branch information
joefeser committed Aug 8, 2024
1 parent 38966ce commit bf221c0
Show file tree
Hide file tree
Showing 20 changed files with 68 additions and 1,776 deletions.
1 change: 0 additions & 1 deletion src/ApiGenerator/ApiGenerator.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
<PreserveCompilationContext>true</PreserveCompilationContext>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="CSharpier.Core" Version="0.28.2" />
<PackageReference Include="Glob" Version="1.1.9" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="NSwag.Core" Version="14.1.0" />
Expand Down
34 changes: 22 additions & 12 deletions src/ApiGenerator/Generator/CodeGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,19 +39,22 @@ public static class CodeGenerator
{
public static string CatFormatPropertyGenerator(string type, string name, string key, string setter) =>
$"public {type} {name} {{ "
+ $" get => Q<{type}>(\"{key}\");"
+ $" get => Q<{type}>(\"{key}\");{Environment.NewLine}"
+ $" set {{ Q(\"{key}\", {setter}); SetAcceptHeader({setter}); }}"
+ $"}}";

public static string PropertyGenerator(string type, string name, string key, string setter) =>
$"public {type} {name} {{ get => Q<{type}>(\"{key}\"); set => Q(\"{key}\", {setter}); }}";
$"public {type} {name} {{ get => Q<{type}>(\"{key}\");{Environment.NewLine} set => Q(\"{key}\", {setter}); }}";

public static string Property(string @namespace, string type, string name, string key, string setter, string obsolete, Version versionAdded, params string[] doc)
{
var components = new List<string>();
foreach (var d in RenderDocumentation(doc)) A(d);
if (versionAdded != null) A($"/// <remarks>Supported by OpenSearch servers of version {versionAdded} or greater.</remarks>");
if (!string.IsNullOrWhiteSpace(obsolete)) A($"[Obsolete(\"{obsolete}\")]");
foreach (var d in RenderDocumentation(doc))
A(d);
if (versionAdded != null)
A($"/// <remarks>Supported by OpenSearch servers of version {versionAdded} or greater.</remarks>");
if (!string.IsNullOrWhiteSpace(obsolete))
A($"[Obsolete(\"{obsolete}\")]");

var generated = @namespace != null && @namespace == "Cat" && name == "Format"
? CatFormatPropertyGenerator(type, name, key, setter)
Expand All @@ -69,12 +72,16 @@ void A(string s)
public static string Constructor(Constructor c)
{
var components = new List<string>();
if (!c.Description.IsNullOrEmpty()) A(c.Description);
if (!c.Description.IsNullOrEmpty())
A(c.Description);
var generated = c.Generated;
if (c.Body.IsNullOrEmpty()) generated += "{}";
if (c.Body.IsNullOrEmpty())
generated += "{}";
A(generated);
if (!c.Body.IsNullOrEmpty()) A(c.Body);
if (!c.AdditionalCode.IsNullOrEmpty()) A(c.AdditionalCode);
if (!c.Body.IsNullOrEmpty())
A(c.Body);
if (!c.AdditionalCode.IsNullOrEmpty())
A(c.AdditionalCode);
return string.Join($"{Environment.NewLine}\t\t", components);

void A(string s)
Expand All @@ -88,15 +95,17 @@ private static IEnumerable<string> RenderDocumentation(params string[] doc)
doc = (doc?.SelectMany(WrapDocumentation) ?? Enumerable.Empty<string>()).ToArray();
switch (doc.Length)
{
case 0: yield break;
case 0:
yield break;
case 1:
yield return $"/// <summary>{doc[0]}</summary>";

yield break;
default:
yield return "/// <summary>";

foreach (var d in doc) yield return $"/// {d}";
foreach (var d in doc)
yield return $"/// {d}";

yield return "/// </summary>";

Expand All @@ -106,7 +115,8 @@ private static IEnumerable<string> RenderDocumentation(params string[] doc)

private static string[] WrapDocumentation(string documentation)
{
if (string.IsNullOrWhiteSpace(documentation)) return Array.Empty<string>();
if (string.IsNullOrWhiteSpace(documentation))
return Array.Empty<string>();
const int max = 140;
var lines = documentation.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var charCount = 0;
Expand Down
15 changes: 9 additions & 6 deletions src/ApiGenerator/Generator/Razor/RazorGeneratorBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
using System.Threading;
using System.Threading.Tasks;
using ApiGenerator.Domain;
using CSharpier;
using RazorLight;
using RazorLight.Generation;
using RazorLight.Razor;
Expand All @@ -59,7 +58,8 @@ protected static async Task DoRazor<TModel>(TModel model, string viewLocation, s
}
catch (TemplateGenerationException e)
{
foreach (var d in e.Diagnostics) Console.WriteLine(d.GetMessage());
foreach (var d in e.Diagnostics)
Console.WriteLine(d.GetMessage());
throw;
}
}
Expand All @@ -86,14 +86,17 @@ CancellationToken token

private static async Task WriteFormattedCsharpFile(string path, string contents)
{
contents = (await CodeFormatter.FormatAsync(contents)).Code;

if (Directory.GetParent(path) is { Exists: false } dir) dir.Create();
if (Directory.GetParent(path) is { Exists: false } dir)
dir.Create();

await File.WriteAllTextAsync(path, contents);
}

public abstract string Title { get; }
public abstract string Title
{
get;
}

public abstract Task Generate(RestApiSpec spec, ProgressBar progressBar, CancellationToken token);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -85,18 +85,6 @@ internal static object CreateInstance(this Type t, params object[] args)
where p.Length == args.Length
select c;


/* Unmerged change from project 'OpenSearch.Client(netstandard2.1)'
Before:
var ctor = constructors.FirstOrDefault();
if (ctor == null)
throw new Exception($"Cannot create an instance of {t.FullName} because it has no constructor taking {args.Length} arguments");
activator = (ObjectActivator<object>)generic.Invoke(null, new object[] { ctor });
After:
var ctor = constructors.FirstOrDefault() ?? throw new Exception($"Cannot create an instance of {t.FullName} because it has no constructor taking {args.Length} arguments");
activator = (ObjectActivator<object>)generic.Invoke(null, new object[] { ctor });
*/
var ctor = constructors.FirstOrDefault() ?? throw new Exception($"Cannot create an instance of {t.FullName} because it has no constructor taking {args.Length} arguments");
activator = (ObjectActivator<object>)generic.Invoke(null, new object[] { ctor });
CachedActivators.TryAdd(key, activator);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,27 +86,13 @@ public string Resolve(PropertyName property)
private string Resolve(Expression expression, MemberInfo member, bool toLastToken = false)
{
var visitor = new FieldExpressionVisitor(_settings);

/* Unmerged change from project 'OpenSearch.Client(netstandard2.1)'
Before:
var name = expression != null
? visitor.Resolve(expression, toLastToken)
: member != null
? visitor.Resolve(member)
: null;
After:
var name = (expression != null
? visitor.Resolve(expression, toLastToken)
: member != null
? visitor.Resolve(member)
: null) ?? throw new ArgumentException("Name resolved to null for the given Expression or MemberInfo.");
*/
var name = (expression != null
var name = expression != null
? visitor.Resolve(expression, toLastToken)
: member != null
? visitor.Resolve(member)
: null) ?? throw new ArgumentException("Name resolved to null for the given Expression or MemberInfo.");
return name;
: null;

return name ?? throw new ArgumentException("Name resolved to null for the given Expression or MemberInfo.");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -70,18 +70,6 @@ internal static object GetFormatter(Type t)

Type implementationType;
if (t.IsInterface)

/* Unmerged change from project 'OpenSearch.Client(netstandard2.1)'
Before:
var readAsAttribute = t.GetCustomAttribute<ReadAsAttribute>();
if (readAsAttribute == null)
throw new Exception($"Unable to deserialize interface {t.FullName}");
implementationType = readAsAttribute.Type.IsGenericType
After:
var readAsAttribute = t.GetCustomAttribute<ReadAsAttribute>() ?? throw new Exception($"Unable to deserialize interface {t.FullName}");
implementationType = readAsAttribute.Type.IsGenericType
*/
{
// need an implementation to deserialize interface to
var readAsAttribute = t.GetCustomAttribute<ReadAsAttribute>() ?? throw new Exception($"Unable to deserialize interface {t.FullName}");
Expand All @@ -99,31 +87,6 @@ internal static object GetFormatter(Type t)
orderby p.Length descending
select c;


/* Unmerged change from project 'OpenSearch.Client(netstandard2.1)'
Before:
var ctor = constructors.FirstOrDefault();
if (ctor == null)
throw new Exception($"Cannot create an instance of {t.FullName} because it does not "
+ $"have a public constructor accepting "
+ $"IDictionary<{typeArguments[0].FullName},{typeArguments[1].FullName}> argument "
+ $"or a public parameterless constructor");
// construct a delegate for the ctor
var activatorMethod = TypeExtensions.GetActivatorMethodInfo.MakeGenericMethod(t);
var activator = activatorMethod.Invoke(null, new object[] { ctor });
return CreateInstance(genericTypeArgs, activator, ctor.GetParameters().Length == 0);
After:
var ctor = constructors.FirstOrDefault() ?? throw new Exception($"Cannot create an instance of {t.FullName} because it does not "
+ $"have a public constructor accepting "
+ $"IDictionary<{typeArguments[0].FullName},{typeArguments[1].FullName}> argument "
+ $"or a public parameterless constructor");
// construct a delegate for the ctor
var activatorMethod = activatorMethod.Invoke(null, new object[] { ctor });
var activator = activatorMethod.Invoke(null, new object[] { ctor });
return CreateInstance(genericTypeArgs, activator, ctor.GetParameters().Length == 0);
*/
var ctor = constructors.FirstOrDefault() ?? throw new Exception($"Cannot create an instance of {t.FullName} because it does not "
+ $"have a public constructor accepting "
+ $"IDictionary<{typeArguments[0].FullName},{typeArguments[1].FullName}> argument "
Expand Down Expand Up @@ -173,18 +136,6 @@ internal static object GetFormatter(Type t)

Type implementationType;
if (t.IsInterface)

/* Unmerged change from project 'OpenSearch.Client(netstandard2.1)'
Before:
var readAsAttribute = t.GetCustomAttribute<ReadAsAttribute>();
if (readAsAttribute == null)
throw new Exception($"Unable to deserialize interface {t.FullName}");
implementationType = readAsAttribute.Type.IsGenericType
After:
var readAsAttribute = t.GetCustomAttribute<ReadAsAttribute>() ?? throw new Exception($"Unable to deserialize interface {t.FullName}");
implementationType = readAsAttribute.Type.IsGenericType
*/
{
// need an implementation to deserialize interface to
var readAsAttribute = t.GetCustomAttribute<ReadAsAttribute>() ?? throw new Exception($"Unable to deserialize interface {t.FullName}");
Expand All @@ -204,27 +155,6 @@ internal static object GetFormatter(Type t)
orderby p.Length descending
select c;


/* Unmerged change from project 'OpenSearch.Client(netstandard2.1)'
Before:
var ctor = constructors.FirstOrDefault();
if (ctor == null)
throw new Exception($"Cannot create an instance of {t.FullName} because it does not "
+ $"have a public constructor accepting IDictionary<{typeArguments[0].FullName},{typeArguments[1].FullName}> argument");
// construct a delegate for the ctor
var activatorMethod = TypeExtensions.GetActivatorMethodInfo.MakeGenericMethod(t);
var activator = activatorMethod.Invoke(null, new object[] { ctor });
return CreateInstance(genericTypeArgs, activator, ctor.GetParameters().Length == 0);
After:
var ctor = constructors.FirstOrDefault() ?? throw new Exception($"Cannot create an instance of {t.FullName} because it does not "
+ $"have a public constructor accepting IDictionary<{typeArguments[0].FullName},{typeArguments[1].FullName}> argument");
// construct a delegate for the ctor
var activatorMethod = activatorMethod.Invoke(null, new object[] { ctor });
var activator = activatorMethod.Invoke(null, new object[] { ctor });
return CreateInstance(genericTypeArgs, activator, ctor.GetParameters().Length == 0);
*/
var ctor = constructors.FirstOrDefault() ?? throw new Exception($"Cannot create an instance of {t.FullName} because it does not "
+ $"have a public constructor accepting IDictionary<{typeArguments[0].FullName},{typeArguments[1].FullName}> argument");

Expand Down Expand Up @@ -297,16 +227,6 @@ public void Serialize(ref JsonWriter writer, TDictionary value, IJsonFormatterRe
// TODO mutator is not used, should it?
var mutator = formatterResolver.GetConnectionSettings().DefaultFieldNameInferrer;
var valueFormatter = formatterResolver.GetFormatterWithVerify<TValue>();

/* Unmerged change from project 'OpenSearch.Client(netstandard2.1)'
Before:
var valueFormatter = formatterResolver.GetFormatterWithVerify<TValue>();
writer.WriteBeginObject();
After:
writer.WriteBeginObject();
*/

writer.WriteBeginObject();

var e = GetSourceEnumerator(value);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,18 +66,6 @@ internal static object GetFormatter(Type t)

Type implementationType;
if (t.IsInterface)

/* Unmerged change from project 'OpenSearch.Client(netstandard2.1)'
Before:
var readAsAttribute = t.GetCustomAttribute<ReadAsAttribute>();
if (readAsAttribute == null)
throw new Exception($"Unable to deserialize interface {t.FullName}");
implementationType = readAsAttribute.Type.IsGenericType
After:
var readAsAttribute = t.GetCustomAttribute<ReadAsAttribute>() ?? throw new Exception($"Unable to deserialize interface {t.FullName}");
implementationType = readAsAttribute.Type.IsGenericType
*/
{
// need an implementation to deserialize interface to
var readAsAttribute = t.GetCustomAttribute<ReadAsAttribute>() ?? throw new Exception($"Unable to deserialize interface {t.FullName}");
Expand All @@ -95,31 +83,6 @@ internal static object GetFormatter(Type t)
orderby p.Length descending
select c;


/* Unmerged change from project 'OpenSearch.Client(netstandard2.1)'
Before:
var ctor = constructors.FirstOrDefault();
if (ctor == null)
throw new Exception($"Cannot create an instance of {t.FullName} because it does not "
+ $"have a constructor accepting "
+ $"{genericDictionaryInterface.FullName} argument "
+ $"or a parameterless constructor");
// construct a delegate for the ctor
var activatorMethod = TypeExtensions.GetActivatorMethodInfo.MakeGenericMethod(t);
var activator = activatorMethod.Invoke(null, new object[] { ctor });
return CreateInstance(genericTypeArgs.ToArray(), activator, ctor.GetParameters().Length == 0);
After:
var ctor = constructors.FirstOrDefault() ?? throw new Exception($"Cannot create an instance of {t.FullName} because it does not "
+ $"have a constructor accepting "
+ $"{genericDictionaryInterface.FullName} argument "
+ $"or a parameterless constructor");
// construct a delegate for the ctor
var activatorMethod = activatorMethod.Invoke(null, new object[] { ctor });
var activator = activatorMethod.Invoke(null, new object[] { ctor });
return CreateInstance(genericTypeArgs.ToArray(), activator, ctor.GetParameters().Length == 0);
*/
var ctor = constructors.FirstOrDefault() ?? throw new Exception($"Cannot create an instance of {t.FullName} because it does not "
+ $"have a constructor accepting "
+ $"{genericDictionaryInterface.FullName} argument "
Expand All @@ -144,25 +107,6 @@ internal class IsADictionaryBaseFormatter<TKey, TValue, TDictionary>
private readonly bool _parameterlessCtor;

public IsADictionaryBaseFormatter(TypeExtensions.ObjectActivator<TDictionary> activator, bool parameterlessCtor)

/* Unmerged change from project 'OpenSearch.Client(netstandard2.1)'
Before:
var keyFormatter = formatterResolver.GetFormatterWithVerify<TKey>() as IObjectPropertyNameFormatter<TKey>;
var valueFormatter = formatterResolver.GetFormatterWithVerify<TValue>();
writer.WriteBeginObject();
After:
var valueFormatter = formatterResolver.GetFormatterWithVerify<TValue>();
writer.WriteBeginObject();
*/

/* Unmerged change from project 'OpenSearch.Client(netstandard2.1)'
Before:
if (keyFormatter != null)
After:
if (formatterResolver.GetFormatterWithVerify<TKey>() is IObjectPropertyNameFormatter<TKey> keyFormatter)
*/
{
_activator = activator;
_parameterlessCtor = parameterlessCtor;
Expand Down
9 changes: 8 additions & 1 deletion src/OpenSearch.Client/CommonOptions/Geo/Distance.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,14 @@ public Distance(string distanceUnit)
return;
}

var unitMeasure = unit.ToEnum<DistanceUnit>() ?? throw new InvalidCastException($"cannot parse {typeof(DistanceUnit).Name} from string '{unit}'");
var unitMeasure = unit.ToEnum<DistanceUnit>();
#pragma warning disable IDE0270 // Use coalesce expression
if (unitMeasure == null)
{
throw new InvalidCastException($"cannot parse {typeof(DistanceUnit).Name} from string '{unit}'");
}
#pragma warning restore IDE0270 // Use coalesce expression

Unit = unitMeasure.Value;
}

Expand Down
Loading

0 comments on commit bf221c0

Please sign in to comment.