using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceClientGenerator
{
///
/// Wrapper around string builder to help emit properly indented code
///
public class CodeBuilder
{
StringBuilder sb;
int tabWidth;
int currentIndent;
string indentSpaces;
///
/// Constructor.
///
/// StringBuilder instance to wrap
/// Staring indent width (in spaces)
/// Additional indent width (in spaces)
public CodeBuilder(StringBuilder sb, int startingIndent, int tabWidth = 4)
{
this.sb = sb;
this.tabWidth = tabWidth;
this.currentIndent = startingIndent;
this.indentSpaces = new string(' ', currentIndent);
}
///
/// Append a formatted string at the current location.
///
/// Format string
/// Parameters
/// This CodeBuilder instance for chaining
public CodeBuilder AppendFormat(string format, params object[] p)
{
sb.AppendFormat(format, p);
return this;
}
///
/// Append a string at the current location
///
/// a string
/// This CodeBuilder instance for chaining
public CodeBuilder Append(string s)
{
sb.Append(s);
return this;
}
///
/// Append a string at the current location, add a newline and indent to the current indent.
///
///
/// This CodeBuilder instance for chaining
public CodeBuilder AppendLine(string line)
{
sb.AppendLine(line);
sb.Append(indentSpaces);
return this;
}
///
/// Add a newline, and indent to the current indent
///
/// This CodeBuilder instance for chaining
public CodeBuilder AppendLine()
{
return this.AppendLine("");
}
///
/// Increase the indent and open a block, adding a '{' and a newline and indent.
///
///
/// The current position will be on a new line at the newly increased indent.
///
/// This CodeBuilder instance for chaining
public CodeBuilder OpenBlock()
{
this.currentIndent += this.tabWidth;
this.indentSpaces = new string(' ', currentIndent);
this.AppendLine("{");
return this;
}
///
/// Add a newline, reduce the indent by the tab width, and add a '}'
///
/// This CodeBuilder instance for chaining
public CodeBuilder CloseBlock()
{
this.currentIndent -= this.tabWidth;
if (currentIndent < 0)
throw new InvalidOperationException("Can't indent below 0");
this.indentSpaces = new string(' ', currentIndent);
this.AppendLine();
this.Append("}");
return this;
}
///
/// Append a string with quotes around it.
///
/// The string
/// The opening quote character. Defaults to double quotes.
/// The closing quote character. Defaults to the open character.
/// This CodeBuilder instance for chaining
public CodeBuilder AppendQuote(string s, string open = @"""", string close = null)
{
sb.Append(open).Append(s.Replace("\"", "\\\"")).Append(null == close ? open : close);
return this;
}
}
}