Skip to content

Commit

Permalink
Merge pull request #79 from svenheden/enum-missing-values
Browse files Browse the repository at this point in the history
Keep C# enum value sequence
  • Loading branch information
SafeerH authored May 28, 2024
2 parents b9468d9 + 596688e commit 6b03f19
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 3 deletions.
8 changes: 6 additions & 2 deletions converter.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,9 +113,13 @@ const createConverter = config => {
} else {
rows.push(`export enum ${enum_.Identifier} {`);

entries.forEach(([key, value], i) => {
entries.forEach(([key, value]) => {
if (config.numericEnums) {
rows.push(` ${key} = ${value != null ? value : i},`);
if (value == null) {
rows.push(` ${key},`);
} else {
rows.push(` ${key} = ${value},`);
}
} else {
rows.push(` ${key} = '${getEnumStringValue(key)}',`);
}
Expand Down
43 changes: 43 additions & 0 deletions lib/csharp-models-to-json_test/EnumCollector_test.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using System.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using NUnit.Framework;

namespace CSharpModelsToJson.Tests
{
[TestFixture]
public class EnumCollectorTest
{
[Test]
public void ReturnEnumWithMissingValues()
{
var tree = CSharpSyntaxTree.ParseText(@"
public enum SampleEnum
{
A,
B = 7,
C,
D = 4,
E
}"
);

var root = (CompilationUnitSyntax)tree.GetRoot();

var enumCollector = new EnumCollector();
enumCollector.VisitEnumDeclaration(root.DescendantNodes().OfType<EnumDeclarationSyntax>().First());

var model = enumCollector.Enums.First();

Assert.That(model, Is.Not.Null);
Assert.That(model.Values, Is.Not.Null);

var values = model.Values.ToArray();
Assert.That(values[0].Value, Is.Null);
Assert.That(values[1].Value, Is.EqualTo("7"));
Assert.That(values[2].Value, Is.Null);
Assert.That(values[3].Value, Is.EqualTo("4"));
Assert.That(values[4].Value, Is.Null);
}
}
}
3 changes: 2 additions & 1 deletion test-files/TestClass.cs → test-files/TestFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
using System.Diagnostics;
using System.Runtime.Serialization;

namespace TestClass
namespace TestNamespace
{
/// <summary>
/// Sample class comment.
Expand All @@ -29,5 +29,6 @@ public enum TestEnum {
D = 0b_0000_0100, // binary: 4 in decimal
E = 0x005, // hexadecimal: 5 in decimal
F = 0x000_01a, // hexadecimal: 26 in decimal
G // 27 in decimal
}
}

0 comments on commit 6b03f19

Please sign in to comment.