Skip to content

Commit

Permalink
fix: improved formatting for C# (#724)
Browse files Browse the repository at this point in the history
  • Loading branch information
slowikowskiarkadiusz authored Apr 25, 2022
1 parent d8904f4 commit 18eed3e
Show file tree
Hide file tree
Showing 13 changed files with 247 additions and 170 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

exports[`Should be able to generate a model with functions to serialize the data model into JSON and should log expected output to console 1`] = `
Array [
"public class Address {
"public class Address
{
public Dictionary<string, object> dictionaryProp;
}",
]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

exports[`Should be able to render auto-implemented properties in CSharp and should log expected output to console 1`] = `
Array [
"public class Root {
"public class Root
{
public string[] Emails { get; set; }
public string StringProp { get; set; }
public double? NumberProp { get; set; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

exports[`Should be able to render collections in C# as IEnumerable and should log expected output to console 1`] = `
Array [
"public class Root {
"public class Root
{
private IEnumerable<string> email;
public IEnumerable<string> Email
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

exports[`Should be able to generate a model to overwrite the Equal and GetHashCode methods and should log expected output to console 1`] = `
Array [
"public class Root {
"public class Root
{
private string email;
public string Email
Expand All @@ -18,6 +19,7 @@ Array [
if(ReferenceEquals(this, model)) { return true; }
return Email == model.Email;
}
return false;
}
Expand All @@ -27,7 +29,6 @@ Array [
hash.Add(Email);
return hash.ToHashCode();
}
}",
]
`;
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
exports[`Should be able to generate a model with functions to serialize the data model into JSON and should log expected output to console 1`] = `
Array [
"[JsonConverter(typeof(RootConverter))]
public class Root {
public class Root
{
private string email;
public string Email
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

exports[`Should be able to render C# models and should log expected output to console 1`] = `
Array [
"public class Root {
"public class Root
{
private string email;
public string Email
Expand Down
18 changes: 10 additions & 8 deletions src/generators/csharp/CSharpGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
defaultGeneratorOptions
} from '../AbstractGenerator';
import { CommonModel, CommonInputModel, RenderOutput } from '../../models';
import { TypeHelpers, ModelKind, CommonNamingConvention, CommonNamingConventionImplementation } from '../../helpers';
import { TypeHelpers, ModelKind, CommonNamingConvention, CommonNamingConventionImplementation, FormatHelpers } from '../../helpers';
import { CSharpPreset, CSHARP_DEFAULT_PRESET } from './CSharpPreset';
import { EnumRenderer } from './renderers/EnumRenderer';
import { ClassRenderer } from './renderers/ClassRenderer';
Expand Down Expand Up @@ -52,25 +52,27 @@ export class CSharpGenerator extends AbstractGenerator<CSharpOptions, CSharpRend
}

const outputModel = await this.render(model, inputModel);

const outputDependencies = outputModel.dependencies.length === 0 ? '' : `${outputModel.dependencies.join('\n')}\n\n`;

const outputContent = `namespace ${options.namespace}
{
${outputModel.dependencies.join('\n')}
${outputModel.result}
${FormatHelpers.indent(outputDependencies + outputModel.result, this.options.indentation?.size, this.options.indentation?.type)}
}`;
return RenderOutput.toRenderOutput({result: outputContent, renderedName: outputModel.renderedName, dependencies: outputModel.dependencies});

return RenderOutput.toRenderOutput({ result: outputContent, renderedName: outputModel.renderedName, dependencies: outputModel.dependencies });
}

render(model: CommonModel, inputModel: CommonInputModel): Promise<RenderOutput> {
const kind = TypeHelpers.extractKind(model);
switch (kind) {
case ModelKind.UNION:
//We dont support union in Csharp generator, however, if union is an object, we render it as a class.
if (!model.type?.includes('object')) {break;}
if (!model.type?.includes('object')) { break; }
return this.renderClass(model, inputModel);
case ModelKind.OBJECT:
case ModelKind.OBJECT:
return this.renderClass(model, inputModel);
case ModelKind.ENUM:
case ModelKind.ENUM:
return this.renderEnum(model, inputModel);
}
Logger.warn(`C# generator, cannot generate this type of model, ${model.$id}`);
Expand Down
17 changes: 9 additions & 8 deletions src/generators/csharp/presets/CommonPreset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,17 @@ function renderEqual({ renderer, model }: {
return `${accessorMethodProp} == model.${accessorMethodProp}`;
}).join(' && \n');
equalProperties = `return ${equalProperties !== '' ? equalProperties : 'true'}`;
const methodContent = `if(obj is ${formattedModelName} model)
{
${renderer.indent('if(ReferenceEquals(this, model)) { return true; }')}
${renderer.indent(equalProperties)};
}
return false;`;

return `public override bool Equals(object obj)
{
if(obj is ${formattedModelName} model)
{
if(ReferenceEquals(this, model)) { return true; }
${renderer.indent(equalProperties, 4)};
}
return false;
${renderer.indent(methodContent)}
}`;
}

Expand All @@ -64,8 +66,7 @@ function renderHashCode({ renderer, model }: {
HashCode hash = new HashCode();
${renderer.indent(hashProperties, 2)}
return hash.ToHashCode();
}
`;
}`;
}

/**
Expand Down
3 changes: 2 additions & 1 deletion src/generators/csharp/renderers/ClassRenderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ export class ClassRenderer extends CSharpRenderer {
}

const formattedName = this.nameType(this.model.$id);
return `public class ${formattedName} {
return `public class ${formattedName}
{
${this.indent(this.renderBlock(content, 2))}
}`;
}
Expand Down
54 changes: 30 additions & 24 deletions src/generators/csharp/renderers/EnumRenderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,29 +14,35 @@ export class EnumRenderer extends CSharpRenderer {
const formattedName = this.nameType(this.model.$id);
const getValueCaseItemValues = await this.getValueCaseItemValues();
const toEnumCaseItemValues = await this.toEnumCaseItemValues();
return `public enum ${formattedName} {
${this.indent(enumItems)}
const enumValueSwitch = `switch (enumValue)
{
${this.indent(getValueCaseItemValues)}
}
return null;`;
const valueSwitch = `switch (value)
{
${this.indent(toEnumCaseItemValues)}
}
return null;`;
const classContent = `public static dynamic GetValue(this ${formattedName} enumValue)
{
${this.indent(enumValueSwitch)}
}
public static class ${formattedName}Extensions {
public static dynamic GetValue(this ${formattedName} enumValue)
{
switch (enumValue)
{
${this.indent(getValueCaseItemValues, 6)}
}
return null;
}
public static ${formattedName}? To${formattedName}(dynamic value)
{
switch (value)
{
${this.indent(toEnumCaseItemValues, 6)}
}
return null;
}
public static ${formattedName}? To${formattedName}(dynamic value)
{
${this.indent(valueSwitch)}
}`;

return `public enum ${formattedName}
{
${this.indent(enumItems)}
}
public static class ${formattedName}Extensions
{
${this.indent(classContent)}
}
`;
}

Expand All @@ -49,7 +55,7 @@ ${this.indent(toEnumCaseItemValues, 6)}
items.push(renderedItem);
}

const content = items.join(', ');
const content = items.join(',\n');
return `${content}`;
}

Expand All @@ -62,7 +68,7 @@ ${this.indent(toEnumCaseItemValues, 6)}
case 'bigint':
case 'boolean':
return enumValue;
case 'object':
case 'object':
return `"${JSON.stringify(enumValue).replace(/"/g, '\\"')}"`;
default:
return `"${enumValue}"`;
Expand All @@ -79,7 +85,7 @@ ${this.indent(toEnumCaseItemValues, 6)}
const value = this.getEnumValue(enumValue);
items.push(`case ${value}: return ${formattedName}.${renderedItem};`);
}

const content = items.join('\n');
return `${content}`;
}
Expand All @@ -93,7 +99,7 @@ ${this.indent(toEnumCaseItemValues, 6)}
const value = this.getEnumValue(enumValue);
items.push(`case ${formattedName}.${renderedItem}: return ${value};`);
}

const content = items.join('\n');
return `${content}`;
}
Expand All @@ -115,7 +121,7 @@ export const CSHARP_DEFAULT_ENUM_PRESET: EnumPreset<EnumRenderer> = {
itemName = `${JSON.stringify(item)}`;
} else if (!(/^[a-zA-Z]+$/).test(itemName.charAt(0))) {
itemName = `String_${itemName}`;
}
}

return pascalCase(itemName);
},
Expand Down
Loading

0 comments on commit 18eed3e

Please sign in to comment.