105 lines
2.4 KiB
C#
105 lines
2.4 KiB
C#
using System;
|
|
using System.IO;
|
|
using System.Text;
|
|
|
|
namespace NBF
|
|
{
|
|
public interface ICodeWriterConfig
|
|
{
|
|
string BlockStart { get; set; }
|
|
string BlockEnd { get; set; }
|
|
bool BlockFromNewLine { get; set; }
|
|
bool UsingTabs { get; set; }
|
|
string EndOfLine { get; set; }
|
|
}
|
|
|
|
public class DefCSharpCodeWriterConfig : ICodeWriterConfig
|
|
{
|
|
public string BlockStart { get; set; } = "{";
|
|
public string BlockEnd { get; set; } = "}";
|
|
public bool BlockFromNewLine { get; set; }
|
|
public bool UsingTabs { get; set; } = true;
|
|
public string EndOfLine { get; set; }
|
|
}
|
|
|
|
public class CodeWriter
|
|
{
|
|
private ICodeWriterConfig _config;
|
|
|
|
private StringBuilder _stringBuilder = new StringBuilder();
|
|
|
|
private int _nowTabCount;
|
|
|
|
public CodeWriter()
|
|
{
|
|
Init();
|
|
}
|
|
|
|
public CodeWriter(ICodeWriterConfig config)
|
|
{
|
|
Init(config);
|
|
}
|
|
|
|
public void Write(string content)
|
|
{
|
|
_stringBuilder.Append(content);
|
|
}
|
|
|
|
public void Writeln()
|
|
{
|
|
_stringBuilder.Append(Environment.NewLine);
|
|
}
|
|
|
|
public void Writeln(string str)
|
|
{
|
|
_stringBuilder.Append(GetLinePrefix());
|
|
_stringBuilder.Append(str);
|
|
_stringBuilder.Append(Environment.NewLine);
|
|
}
|
|
|
|
public void StartBlock()
|
|
{
|
|
Writeln(_config.BlockStart);
|
|
_nowTabCount++;
|
|
}
|
|
|
|
public void EndBlock()
|
|
{
|
|
_nowTabCount--;
|
|
Writeln(_config.BlockEnd);
|
|
}
|
|
|
|
public void Save(string path)
|
|
{
|
|
var dirPath = Path.GetDirectoryName(path);
|
|
if (dirPath != null && !Directory.Exists(dirPath))
|
|
{
|
|
Directory.CreateDirectory(dirPath);
|
|
}
|
|
|
|
var content = _stringBuilder.ToString();
|
|
File.WriteAllText(path, content);
|
|
}
|
|
|
|
#region 内部方法
|
|
|
|
private void Init(ICodeWriterConfig config = null)
|
|
{
|
|
_config = config ?? new DefCSharpCodeWriterConfig();
|
|
}
|
|
|
|
private string GetLinePrefix()
|
|
{
|
|
string ret = string.Empty;
|
|
if (!_config.UsingTabs) return ret;
|
|
for (var i = 0; i < _nowTabCount; i++)
|
|
{
|
|
ret += "\t";
|
|
}
|
|
|
|
return ret;
|
|
}
|
|
|
|
#endregion
|
|
}
|
|
} |