//
#nullable enable
using System;
using System.Text;
namespace CarpaNet.Generation;
///
/// Helper class for building C# source code with proper indentation.
///
public sealed class SourceBuilder
{
private readonly StringBuilder _sb = new();
private int _indentLevel;
private const string IndentString = " ";
public SourceBuilder AppendLine()
{
_sb.AppendLine();
return this;
}
public SourceBuilder AppendLine(string line)
{
if (string.IsNullOrEmpty(line))
{
_sb.AppendLine();
}
else
{
AppendIndent();
_sb.AppendLine(line);
}
return this;
}
public SourceBuilder Append(string text)
{
_sb.Append(text);
return this;
}
public SourceBuilder AppendIndent()
{
for (int i = 0; i < _indentLevel; i++)
{
_sb.Append(IndentString);
}
return this;
}
public SourceBuilder OpenBrace()
{
AppendLine("{");
_indentLevel++;
return this;
}
public SourceBuilder CloseBrace(bool withSemicolon = false)
{
_indentLevel--;
AppendLine(withSemicolon ? "};" : "}");
return this;
}
public SourceBuilder Indent()
{
_indentLevel++;
return this;
}
public SourceBuilder Unindent()
{
if (_indentLevel > 0)
{
_indentLevel--;
}
return this;
}
///
/// Writes an XML documentation summary.
///
public SourceBuilder WriteSummary(string? description)
{
if (string.IsNullOrWhiteSpace(description))
{
return this;
}
AppendLine("/// ");
// Split description into lines and escape XML
var lines = description!.Replace("\r\n", "\n").Split('\n');
foreach (var line in lines)
{
AppendLine($"/// {EscapeXml(line)}");
}
AppendLine("/// ");
return this;
}
///
/// Writes a using directive.
///
public SourceBuilder WriteUsing(string ns)
{
AppendLine($"using {ns};");
return this;
}
///
/// Writes a namespace declaration with file-scoped syntax.
///
public SourceBuilder WriteNamespace(string ns)
{
AppendLine($"namespace {ns};");
AppendLine();
return this;
}
///
/// Writes a namespace declaration with block syntax.
///
public SourceBuilder WriteNamespaceBlock(string ns)
{
AppendLine($"namespace {ns}");
OpenBrace();
return this;
}
///
/// Writes an attribute.
///
public SourceBuilder WriteAttribute(string attribute)
{
AppendLine($"[{attribute}]");
return this;
}
///
/// Writes the file header.
///
public SourceBuilder WriteHeader()
{
AppendLine("// ");
AppendLine("#nullable enable");
AppendLine();
return this;
}
private static string EscapeXml(string text)
{
return text
.Replace("&", "&")
.Replace("<", "<")
.Replace(">", ">")
.Replace("\"", """)
.Replace("'", "'");
}
public override string ToString() => _sb.ToString();
public int Length => _sb.Length;
}