Skip to content

Commit

Permalink
Add custom top-level comment to CSharpSerializer
Browse files Browse the repository at this point in the history
* since there is no way to overwrite the default top-level comment,
  we have to create a helper function to replace the default text at
  the top of the automatically generated code
  • Loading branch information
StefanGreve committed Mar 30, 2024
1 parent 096d728 commit b4bdc36
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
26 changes: 23 additions & 3 deletions JackTheEnumRipper/Serializer/CSharpSerializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,20 +55,40 @@ private static CodeCompileUnit GenerateEnumCode(IEnumerable<AbstractEnum> enums)
return compileUnit;
}

private static void ReplaceTopLevelComment(StringWriter writer, string? newComment)
{
if (string.IsNullOrEmpty(newComment)) return;

IEnumerable<string> lines = writer
.ToString()
.Split(new[] { Environment.NewLine }, StringSplitOptions.None)
.SkipWhile(line => line.TrimStart().StartsWith("//"));

writer.GetStringBuilder().Clear();
writer.WriteLine($"// {newComment}");

foreach (string line in lines)
{
writer.WriteLine(line);
}
}

public void Serialize(IEnumerable<AbstractEnum> enums, string path)
{
var provider = CodeDomProvider.CreateProvider(Enum.GetName(this.Format));
var codeCompileUnit = GenerateEnumCode(enums);
var compileUnit = GenerateEnumCode(enums);

var options = new CodeGeneratorOptions
{
BracingStyle = "C",
BlankLinesBetweenMembers = false,
IndentString = " "
IndentString = this._appSettings.Indentation ?? "\t"
};

using StringWriter writer = new();
var encoding = Encoding.GetEncoding(this._appSettings.Encoding);
provider.GenerateCodeFromCompileUnit(codeCompileUnit, writer, options);
provider.GenerateCodeFromCompileUnit(compileUnit, writer, options);
ReplaceTopLevelComment(writer, this._appSettings.Comment);
File.WriteAllText(path, writer.ToString(), encoding);
}
}
Expand Down
4 changes: 1 addition & 3 deletions JackTheEnumRipper/Serializer/IniSerializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@ public class IniSerializer(IOptions<AppSettings> appSettings) : ISerializer

public void Serialize(IEnumerable<AbstractEnum> enums, string path)
{
string comment = "This code was generated by a tool.";

var sections = enums.Select(@enum => new Section
{
Comment = $"scope={(@enum.IsPublic ? "public" : "internal")},type={@enum.Type}",
Expand All @@ -33,7 +31,7 @@ public void Serialize(IEnumerable<AbstractEnum> enums, string path)
}); ;

var encoding = Encoding.GetEncoding(this._appSettings.Encoding);
var ini = new Ini(sections, comment, commentSymbol: '#');
var ini = new Ini(sections, this._appSettings.Comment, commentSymbol: '#');
File.WriteAllText(path, ini.ToString(), encoding);
}
}
Expand Down

0 comments on commit b4bdc36

Please sign in to comment.